Search completed in 1.12 seconds.
4837 results for "code":
Your results are loading. Please wait...
TextEncoder.prototype.encodeInto() - Web APIs
the textencoder.prototype.encodeinto() method takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. this is potentially more performant than the older encode() method especially when the target buffer is a view into a wasm heap. syntax b1 = encoder.encodeinto(string, uint8array); parameters string is a usvstring containing the text to encode. uint8array is a uint8array object instance to place the resulting utf-8 encoded text into. return value a textencoderencodeintoresult dictionary, which contains two members: read the number of utf-16 units of code from the source that has been converted over to utf-8. this may be less than string.length if uint8array di...
... value a textencoderencodeintoresult dictionary, which contains two members: read the number of utf-16 units of code from the source that has been converted over to utf-8. this may be less than string.length if uint8array did not have enough space. written the number of bytes modified in the destination uint8array. the bytes written are guaranteed to form complete utf-8 byte sequences. encode into a specific position encoder.encodeinto always puts its output at the start of the array. however, it is sometimes useful to make the output start at a particular index. the solution is typedarray.prototype.subarray(). observe. ...
...h space. written the number of bytes modified in the destination uint8array. the bytes written are guaranteed to form complete utf-8 byte sequences. encode into a specific position encoder.encodeinto always puts its output at the start of the array. however, it is sometimes useful to make the output start at a particular index. the solution is typedarray.prototype.subarray(). observe. ...
...And 46 more matches
TextDecoder.prototype.decode() - Web APIs
the textdecoder.prototype.decode() method returns a domstring containing the text, given in parameters, decoded with the specific method for that textdecoder object. syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode(); parameters buffer optional is either an arraybuffer or an arraybufferview containing the text to decode. options optional is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. example this example encodes and decodes the euro symbol, €. ...
... to decode. options optional is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. example this example encodes and decodes the euro symbol, €. ...
...onal is a textdecodeoptions dictionary with the property: stream a boolean flag indicating that additional data will follow in subsequent calls to decode(). set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. it defaults to false. example this example encodes and decodes the euro symbol, €. ...
...And 7 more matches
<code>: The Inline Code element - HTML: Hypertext Markup Language
Web › HTML › Element › code
by default, the content text is displayed using the user agent's default monospace font. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. ...
...nts any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement up to gecko 1.9.2 (firefox 4) inclusive, firefox implements the htmlspanelement interface for this element. attributes this element only includes the global attributes. example a paragraph of text that includes <code>: <p>the function <code>selectall()</code> highlights all the text in the input field so the user can, for example, copy or delete the text.</p> the output generated by this html looks like this: notes to represent multiple lines of code, wrap the <code> element within a <pre> element. the <code> element by itself only represents a single phrase of code or line of code. a css rule can be ...
...ion <code>selectall()</code> highlights all the text in the input field so the user can, for example, copy or delete the text.</p> the output generated by this html looks like this: notes to represent multiple lines of code, wrap the <code> element within a <pre> element. the <code> element by itself only represents a single phrase of code or line of code. a css rule can be defined for the code selector to override the browser's default font face. preferences set by the user might take precedence over the specified css. specifications specification status comment html living standardthe definition of '<code>' in that specification. living standard html5the definition of '<code>' in that specification. recommendation html 4.01...
...s default font face. preferences set by the user might take precedence over the specified css. specifications specification status comment html living standardthe definition of '<code>' in that specification. living standard html5the definition of '<code>' in that specification. recommendation html 4.01 specificationthe definition of '<code>' in that specification. recommendation ...
TextEncoder.prototype.encode() - Web APIs
the textencoder.prototype.encode() method takes a usvstring as input, and returns a uint8array containing the text given in parameters encoded with the specific method for that textencoder object. syntax b1 = encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. ...
...pe.encode() method takes a usvstring as input, and returns a uint8array containing the text given in parameters encoded with the specific method for that textencoder object. syntax b1 = encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. ...
...x b1 = encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. examples <p class="source">this is a sample paragraph.</p> <p class="result">encoded result: </p> const sourcepara = document.queryselector('.source'); const resultpara = document.queryselector('.result'); const string = sourcepara.textcontent; const textencoder = new textencoder(); let encoded = textencoder.encode(string); resultpara.textcontent += encoded; specifications specification status comment encodingthe definition of 'textencoder.prototype.encode()' in that specification. living standard initial definition. ...
Web audio codec guide - Web media technologies
even modest quality, high-fidelity stereo sound can use a substantial amount of disk space. for web developers, an even bigger concern is the network bandwidth needed in order to transfer audio, whether for streaming or to download it for use during gameplay. the processing of audio data to encode and decode it is handled by an audio codec (coder/decoder). ...
... even modest quality, high-fidelity stereo sound can use a substantial amount of disk space. for web developers, an even bigger concern is the network bandwidth needed in order to transfer audio, whether for streaming or to download it for use during gameplay. the processing of audio data to encode and decode it is handled by an audio codec (coder/decoder). ...
...rn is the network bandwidth needed in order to transfer audio, whether for streaming or to download it for use during gameplay. the processing of audio data to encode and decode it is handled by an audio codec (coder/decoder). in this article, we look at audio codecs used on the web to compress and decompress audio, what their capabilities and use cases are, and offer guidance when choosing audio codecs to use for your content. additionally, webrtc implementations generally use a subset of these codecs for their encoding and decoding of media, and may support additional codecs as well, for optimal cross-platform support of video and audio conferencing, and to integrate better with legacy telecommunication solutions. see codecs used by webrtc for details. for information about the fundamental...
...And 68 more matches
Web video codec guide - Web media technologies
eo would need 14.93 gb of storage. a fairly typical 30 minute video conference would need about 447.9 gb of storage, and a 2-hour movie would take almost 1.79 tb (that is, 1790 gb). not only is the required storage space enormous, but the network bandwidth needed to transmit an uncompressed video like that would be enormous, at 249 mb/sec—not including audio and overhead. ...
...age. a fairly typical 30 minute video conference would need about 447.9 gb of storage, and a 2-hour movie would take almost 1.79 tb (that is, 1790 gb). not only is the required storage space enormous, but the network bandwidth needed to transmit an uncompressed video like that would be enormous, at 249 mb/sec—not including audio and overhead. this is where video codecs come in. ...
...eo conference would need about 447.9 gb of storage, and a 2-hour movie would take almost 1.79 tb (that is, 1790 gb). not only is the required storage space enormous, but the network bandwidth needed to transmit an uncompressed video like that would be enormous, at 249 mb/sec—not including audio and overhead. this is where video codecs come in. just as audio codecs do for the sound data, video codecs compress the video data and encode it into a format that can later be decoded and played back or edited. most video codecs are lossy, in that the decoded video does not precisely match the source. some details may be lost; the amount of loss depends on the codec and how it's configured, but as a general rule, the more compression you achieve, the more loss of detail and fidelity will occur. so...
...And 62 more matches
Codecs used by WebRTC - Web media technologies
the webrtc api makes it possible to construct web sites and apps that let users communicate in real time, using audio and/or video as well as optional data and other information. to communicate, the two devices need to be able to agree upon a mutually-understood codec for each track so they can successfully communicate and present the shared media. this guide reviews the codecs that browsers are required to implement as well as other codecs that some or all browsers support for webrtc. containerless media webrtc uses bare mediastreamtrack objects for each track being shared from one peer to another, without a container or even a mediastream associated with the tracks. which codecs can be within those tracks is not mandated by the webrtc specification. however, rfc 7742 specifies that all we...
...rack being shared from one peer to another, without a container or even a mediastream associated with the tracks. which codecs can be within those tracks is not mandated by the webrtc specification. however, rfc 7742 specifies that all webrtc-compatible browsers must support vp8 and h.264's constrained baseline profile for video, and rfc 7874 specifies that browsers must support at least the opus codec as well as g.711's pcma and pcmu formats. these two rfcs also lay out options that must be supported for each codec, as well as specific user comfort features such as echo cancelation. this guide reviews the codecs that browsers are required to implement as well as other codecs that some or all browsers support for webrtc. while compression is always a necessity when dealing with media on the ...
...media on the web, it's of additional importance when videoconferencing in order to ensure that the participants are able to communicate without lag or interruptions. of secondary importance is the need to keep the video and audio synchronized, so that the movements and any ancillary information (such as slides or a projection) are presented at the same time as the audio that corresponds. general codec requirements before looking at codec-specific capabilities and requirements, there are a few overall requirements that must be met by any codec configuration used with webrtc. unless the sdp specifically signals otherwise, the web browser receiving a webrtc video stream must be able to handle video at at least 20 fps at a minimum resolution of 320 pixels wide by 240 pixels tall. it's encourage...
...And 54 more matches
Bytecode Descriptions
constants undefined stack: ⇒ undefined push undefined. null stack: ⇒ null push null. false, true stack: ⇒ true/false push a boolean constant. int32 operands: (int32_t val) stack: ⇒ val push the int32_t immediate operand as an int32value. jsop::zero, jsop::one, jsop::int8, jsop::uint16, and jsop::uint24 are all compact encodings for jsop::int32. zero stack: ⇒ 0 push the number 0. one stack: ⇒ 1 push the number 1. int8 operands: (int8_t val) stack: ⇒ val push the int8_t immediate operand as an int32value. uint16 operands: (uint16_t val) stack: ⇒ val push the uint16_t immediate operand as an int32value. ...
...doublevalue. if the operand is a nan, it must be the canonical nan (see js::detail::canonicalizenan). bigint operands: (uint32_t bigintindex) stack: ⇒ bigint push the bigint constant script->getbigint(bigintindex). string operands: (uint32_t atomindex) stack: ⇒ string push the string constant script->getatom(atomindex). format: jof_atom symbol operands: (uint8_t symbol (the js::symbolcode of the symbol to use)) stack: ⇒ symbol push a well-known symbol. symbol must be in range for js::symbolcode. expressions unary operators void stack: val ⇒ undefined pop the top value on the stack, discard it, and push undefined. implements: the void operator, step 3. typeof, typeofexpr stack: val ⇒ (typeof val) the typeof operator. infallible. the result is always a string that depe...
...except that--amazingly--jsop::typeof affects the behavior of an immediately preceding jsop::getname or jsop::getgname instruction! this is how we implement typeof step 2, making typeof nonexistingvariable return "undefined" instead of throwing a referenceerror. in a global scope: typeof x compiles to getgname "x"; typeof. typeof (0, x) compiles to getgname "x"; typeofexpr. emitting the same bytecode for these two expressions would be a bug. per spec, the latter throws a referenceerror if x doesn't exist. format: jof_ic pos stack: val ⇒ (+val) the unary + operator. +val doesn't do any actual math. it just calls tonumber(val). the conversion can call .tostring()/.valueof() methods and can throw. the result on success is always a number. (per spec, unary - supports bigints, but unary + doe...
...And 46 more matches
Looping code - Learn web development
haven't explicitly illustrated this above, but we could think about the farmer being able to collect say 2 portions of food per hour. after each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. if he has reached 10 portions (the point where the condition is no longer true, so the loop exits), he can stop collecting and go home. in pseudocode, this would look something like the following: loop(food = 0; foodneeded = 10) { if (food >= foodneeded) { exit loop; // we have enough food; let's go home } else { food += 2; // spend an hour collecting 2 more food // loop will then run again } } so the amount of food needed is set at 10, and the amount the farmer currently has is set at 0. in each iteration of the loop, ...
..., we check whether the amount of food the farmer has is larger or equal to the amount he needs. if so, we can exit the loop. if not, the farmer spends an hour collecting two portions of food, and the loop runs again. ...
...lecting two portions of food, and the loop runs again. why bother? at this point, you probably understand the high-level concepts behind loops, but you are probably thinking "ok, great, but how does this help me write better javascript code?" as we said earlier, loops are all to do with doing the same thing over and over again, which is great for rapidly completing repetitive tasks. often, the code will be slightly different on each successive iteration of the loop, which means that you can complete a whole load of tasks that are similar but slightly different — if you've got a lot of different calculations to do, you want to do each different one, not the same one over and over again! let's look at an example to perfectly illustrate why loops are such a good thing. let's say we wanted t...
...And 44 more matches
Making decisions in your code — conditionals - Learn web development
for example, in a game, if the player's number of lives is 0, then it's game over. in a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. in this article, we'll explore how so-called conditional statements work in javascript. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. objective: to understand how to use conditional structures in javascript. ...
...tcome of "ate one cookie" might be "still felt hungry", and the outcome of "ate two cookies" might be "felt full, but mom scolded me for eating all the cookies".) if...else statements let's look at by far the most common type of conditional statement you'll use in javascript — the humble if...else statement. basic if ... else syntax basic if...else syntax looks like the following in pseudocode: if (condition) { code to run if condition is true } else { run some other code instead } here we've got: the keyword if followed by some parentheses. a condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). the condition makes use of the comparison operators we discussed in the last module and returns tru...
...{ run some other code instead } here we've got: the keyword if followed by some parentheses. a condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). the condition makes use of the comparison operators we discussed in the last module and returns true or false. a set of curly braces, inside which we have some code — this can be any code we like, and it only runs if the condition returns true. the keyword else. another set of curly braces, inside which we have some more code — this can be any code we like, and it only runs if the condition is not true — or in other words, the condition is false. ...
...And 35 more matches
The "codecs" parameter in common media types - Web media technologies
sing a simple mime type, such as video/mp4 or audio/mpeg. however, many media types—especially those that support video tracks—can benefit from the ability to more precisely describe the format of the data within them. for instance, just describing a video in an mpeg-4 file with the mime type video/mp4 doesn't say anything about what format the actual media within takes. ...
...t of the data within them. for instance, just describing a video in an mpeg-4 file with the mime type video/mp4 doesn't say anything about what format the actual media within takes. for that reason, the codecs parameter can be added to the mime type describing media content. with it, container-specific information can be provided. this information may include things like the profile of the video codec, the type used for the audio tracks, and so forth. this guide briefly examines the syntax of the media type codecs parameter and how it's used with the mime type string to provide details about the contents of audio or video media beyond simply indicating the container type. general syntax a basic mime media type is expressed by stating the type of media (audio, video, etc), then a slash char...
...file type, such as an mp3. video/ogg a video file using the ogg file type. video/mp4 a video file using the mpeg-4 file type. video/quicktime a video file in apple's quicktime format. as noted elsewhere, this format was once commonly used on the web but no longer is, since it required a plugin to use. however, each of these mime types is vague. ...
...And 34 more matches
Source code directories overview - Archive of obsolete content
this document is a guide for developers to the directory structure of the mozilla source code tree. it gives a bird's eye view of the source code so a developer can get a good idea what is in mozilla and where to find things. it is a good document for a new mozilla developer to start learning about the mozilla code base. this document contains material for seamonkey, firefox, and toolkit. it is a living document which is (supposed to be) updated monthly according to changes in the mozilla source tree. see also similar information in mozilla source code directory structure, and also see the more detailed overview of how the parts of gecko fit together. introduction: common subdirectories a common naming scheme is used throughout the mozilla source trees. at the top level is the name of th...
...are usually put in their own third level directory and given a unique name (e.g. txmgr in the editor directory in seamonkey). beneath this third level directory, there may be fourth level base, public and idl directories. thus, the scheme is recursive; it can apply to submodules, sub-submodules and so on. base contains the basic (core) functionality for the module. base contains all the source code that cannot be categorized into a submodule. build contains any special makefiles for building the particular module. doc contains any documentation associated with this module. idl contains the xpidl (cross platform interface definition language) interface files. interfaces are used so functionality can be available to both javascript scripts and c code with as little effort as possible. xpid...
... for building the particular module. doc contains any documentation associated with this module. idl contains the xpidl (cross platform interface definition language) interface files. interfaces are used so functionality can be available to both javascript scripts and c code with as little effort as possible. xpidl files have their own mini-language and processing tools. public contains source code that will be exported to the dist/include directory. they are not all necessarily public in the general sense; some are only meant for internal use in a certain module. as more code is written with or converted to xpidl interfaces, the value of the public directory diminishes. src contains the bulk of the source code. tests contains c harnesses, html or xul that exercise this module. tools con...
...And 33 more matches
imgIDecoderObserver
image/public/imgidecoderobserver.idlscriptable this interface is used both for observing imgidecoder objects and for observing imgirequest objects. it lets you monitor the progress of loading an image. 1.0 66 introduced gecko 12.0 inherits from: imgicontainerobserver last changed in gecko 1.7 we make the distinction here between "load" and "decode" notifications. load notifications are fired as the image is loaded from the network or filesystem. decode notifications are fired as the image is decoded. if an image is decoded on load and not visibly discarded, decode notifications are nested logically inside load notifications as one might expect. ...
...t changed in gecko 1.7 we make the distinction here between "load" and "decode" notifications. load notifications are fired as the image is loaded from the network or filesystem. decode notifications are fired as the image is decoded. if an image is decoded on load and not visibly discarded, decode notifications are nested logically inside load notifications as one might expect. however, with decode-on-draw, the set of decode notifications can come completely after the load notifications, and can come multiple times if the image is discardable. moreover, they can be interleaved in various ways. in general, any presumed ordering between load and decode notifications should not be relied upon. ...
...ifications are nested logically inside load notifications as one might expect. however, with decode-on-draw, the set of decode notifications can come completely after the load notifications, and can come multiple times if the image is discardable. moreover, they can be interleaved in various ways. in general, any presumed ordering between load and decode notifications should not be relied upon. decode notifications may or may not be synchronous, depending on the situation. if imgidecoder::flag_sync_decode is passed to a function that triggers a decode, all notifications that can be generated from the currently loaded data fire before the call returns. if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the call returns. method overview void ondat...
...And 18 more matches
Functions — reusable blocks of code - Learn web development
in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. ...
...in this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define them, scope, and parameters. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps. ...
...om() function generates a random number between // 0 and up to but not including 1, and returns that number ...we were using a function! note: feel free to enter these lines into your browser's javascript console to re-familiarize yourself with their functionality, if needed. the javascript language has many built-in functions to allow you to do useful things without having to write all that code yourself. in fact, some of the code you are calling when you invoke (a fancy word for run, or execute) a built in browser function couldn't be written in javascript — many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like c++, not web languages like javascript. bear in mind that some built-in browser functions are n...
...And 17 more matches
String.fromCodePoint() - JavaScript
the static string.fromcodepoint() method returns a string created by using the specified sequence of code points. the source for this interactive example is stored in a github repository. if 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 string.fromcodepoint(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of code points. return value a string created by using the specified sequence of code points. exceptions a rangeerror is thrown if an invalid unicode code point is given (e.g. "rangeerror: nan is not a valid code point"). description this method returns a string (and not a string object). ...
... string.fromcodepoint(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of code points. return value a string created by using the specified sequence of code points. exceptions a rangeerror is thrown if an invalid unicode code point is given (e.g. "rangeerror: nan is not a valid code point"). description this method returns a string (and not a string object). because fromcodepoint() is a static method of string, you must call it as string.fromcodepoint(), rather than as a method of a string object you created. polyfill the string.fromcodepoint() method has been added to ecmascript 2015 and may not be supported in all web browsers or environments yet. ...
...alid code point"). description this method returns a string (and not a string object). because fromcodepoint() is a static method of string, you must call it as string.fromcodepoint(), rather than as a method of a string object you created. polyfill the string.fromcodepoint() method has been added to ecmascript 2015 and may not be supported in all web browsers or environments yet. ...
...And 15 more matches
encodeURIComponent() - JavaScript
the encodeuricomponent() function encodes a uri by replacing each instance of certain characters by one, two, three, or four escape sequences representing the utf-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax encodeuricomponent(str); parameters str string. a component of a uri. return value a new string representing the provided string encoded as a uri component. description encodeuricomponent() escapes all characters except: not escaped: a-z a-z 0-9 - _ . ! ~ * ' ( ) e...
...ve examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax encodeuricomponent(str); parameters str string. a component of a uri. return value a new string representing the provided string encoded as a uri component. description encodeuricomponent() escapes all characters except: not escaped: a-z a-z 0-9 - _ . ...
...https://github.com/mdn/interactive-examples and send us a pull request. syntax encodeuricomponent(str); parameters str string. a component of a uri. return value a new string representing the provided string encoded as a uri component. description encodeuricomponent() escapes all characters except: not escaped: a-z a-z 0-9 - _ . ...
...And 14 more matches
Working with windows in chrome code
opening windows from a <script> in a window or an overlay to open a new window, we usually use a window.open or window.opendialog dom call, like this: var win = window.open("chrome://myextension/content/about.xul", "aboutmyextension", "chrome,centerscreen"); the first parameter to window.open is the uri of the xul file that describes the window and its contents. ...
... is the window's name; the name can be used in links or forms as the target attribute. this is different from the user-visible window title, which is specified using xul. the third, and optional, parameter is a list of special window features the window should have. the window.opendialog function works similarly, but lets you specify optional arguments that can be referenced from the javascript code. it also handles window features a little differently, including always assuming the dialog feature is specified. from xpcom components and modules if the window object is unavailable (for example, when opening a window from xpcom component code), you might want to use nsiwindowwatcher interface. its parameters are similar to window.open; in fact, window.open's implementation calls nsiwindowwat...
... but it also contains the user-defined properties for global variables and functions of the window. so, for example, to access the dom document corresponding to the window, you can use win.document. note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.getelementbyid() will fail. to overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. you can get a window object from a document using document.defaultview. content windows when a xul window contains a widget capable of displaying a page, such as <browser> or <iframe>, the document in that widget is, naturally, separate from the document of the chrome window itself. there also is a wi...
...And 13 more matches
String.prototype.charCodeAt() - JavaScript
the charcodeat() method returns an integer between 0 and 65535 representing the utf-16 code unit at the given index. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the utf-16 code unit matches the unicode code point for code points which can be represented in a single utf-16 code unit. if the unicode code point cannot be represented in a single utf-16 code unit (because its value is greater than 0xffff) then the code unit returned will be the first part of a surrogate pair for the code point. if you want the entire code point value, use codepointat(). ...
...code unit matches the unicode code point for code points which can be represented in a single utf-16 code unit. if the unicode code point cannot be represented in a single utf-16 code unit (because its value is greater than 0xffff) then the code unit returned will be the first part of a surrogate pair for the code point. if you want the entire code point value, use codepointat(). syntax str.charcodeat(index) parameters index an integer greater than or equal to 0 and less than the length of the string. if index is not a number, it defaults to 0. return value a number representing the utf-16 code unit value of the character at the given index. if index is out of range, charcodeat() returns nan. description unicode code points range from 0 to 1114111 (0x10ffff). ...
...rcodeat(index) parameters index an integer greater than or equal to 0 and less than the length of the string. if index is not a number, it defaults to 0. return value a number representing the utf-16 code unit value of the character at the given index. if index is out of range, charcodeat() returns nan. description unicode code points range from 0 to 1114111 (0x10ffff). the first 128 unicode code points are a direct match of the ascii character encoding. (for information on unicode, see the javascript guide.) note: charcodeat() will always return a value that is less than 65536. this is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character. because of this, in order to examine (or repr...
...And 13 more matches
Using JavaScript code modules
javascript code modules are a concept introduced in gecko 1.9 and can be used for sharing code between different privileged scopes. modules can also be used to create global javascript singletons that previously required using javascript xpcom objects. a javascript code module is simply some javascript code located in a registered location. the module is loaded into a specific javascript scope, such as xul script or javascript xpcom script, using components.utils.import() or components.utils["import"](). ...
...odules can also be used to create global javascript singletons that previously required using javascript xpcom objects. a javascript code module is simply some javascript code located in a registered location. the module is loaded into a specific javascript scope, such as xul script or javascript xpcom script, using components.utils.import() or components.utils["import"](). creating a javascript code module a very simple javascript module looks like this: var exported_symbols = ["foo", "bar"]; function foo() { return "foo"; } var bar = { name : "bar", size : 3 }; var dummy = "dummy"; notice that the module uses normal javascript to create functions, objects, constants, and any other javascript type. the module also defines a special array named exported_symbols. any javascript it...
...item named in exported_symbols will be exported from the module and injected into the importing scope. ...
...And 12 more matches
HTTP response status codes - HTTP
Web › HTTP › Status
http response status codes indicate whether a specific http request has been successfully completed. responses are grouped in five classes: informational responses (100–199), successful responses (200–299), redirects (300–399), client errors (400–499), and server errors (500–599). the below status codes are defined by section 10 of rfc 2616. you can find an updated specification in rfc 7231. if you receive a response that is not in this list, it is a non-standard response, possibly custom to the server's software. information responses 100 continue this interim response indicates that everything so far is ok and that the client should continue the request, or ignore the response if the request is already finished. ...
...dated specification in rfc 7231. if you receive a response that is not in this list, it is a non-standard response, possibly custom to the server's software. information responses 100 continue this interim response indicates that everything so far is ok and that the client should continue the request, or ignore the response if the request is already finished. ...
...e. information responses 100 continue this interim response indicates that everything so far is ok and that the client should continue the request, or ignore the response if the request is already finished. 101 switching protocol this code is sent in response to an upgrade request header from the client, and indicates the protocol the server is switching to. 102 processing (webdav) this code indicates that the server has received and is processing the request, but no response is available yet. 103 early hints this status code is primarily intended to be used with the link header, letting the user agent start preloading resources while the server prepares a response. successful responses 200 ok the request has succeeded. the meaning of the success depends on the http method: ...
...And 12 more matches
Code snippets - Archive of obsolete content
this is a quick list of useful code snippets (small code samples) available for developers of extensions for the various mozilla applications. many of these samples can also be used in xulrunner applications, as well as in actual mozilla code itself. these examples demonstrate how to accomplish basic tasks that might not be immediately obvious. general examples and demos from mdn articles a collection of examples and demos from articles. window code opening and manipulating windows toolbar toolbar related code sidebar sidebar related code forms forms related code xml code used to parse, write, manipulate, etc. ...
.... these examples demonstrate how to accomplish basic tasks that might not be immediately obvious. general examples and demos from mdn articles a collection of examples and demos from articles. window code opening and manipulating windows toolbar toolbar related code sidebar sidebar related code forms forms related code xml code used to parse, write, manipulate, etc. ...
...ks that might not be immediately obvious. general examples and demos from mdn articles a collection of examples and demos from articles. window code opening and manipulating windows toolbar toolbar related code sidebar sidebar related code forms forms related code xml code used to parse, write, manipulate, etc. ...
...And 11 more matches
Creating the Component Code
« previousnext » this chapter goes over the basic code required to handle the relationship between your component and xpcom. having the component found and registered properly is the goal of this first chapter of the tutorial. in the subsequent chapters, we can begin to work on the example weblock component functionality itself. use the calculator (after learning long division) you have to write a fair amount of code to create a component library that gets loaded into xpcom. an xpcom component needs to implement at least three interfaces that xpcom requires, and often others as well. there is more code in this chapter than you'll eventually need, however. using xpcom utilities to make things easier shows some simpler and more elegant ways to create an xpcom component using...
...r software that uses xpcom. registration provides the information that applications need in order to use components properly. the weblock component must do a number of things to register itself. specifically, the component library has to contain implementations for the component-related interfaces described in this chapter: nsimodule and nsifactory, which are entry points for your implementation code. once your component implements these interfaces, the rest of the registration process itself is simple. applications typically use regxpcom, described in the next section. the regxpcom program an explicit way to register a component is to run the application regxpcom. without any arguments passed to regxpcom, the program registers the component in the default component registry. we suggest th...
... locking features happens. you also have to create weblockmodule to implement the necessary nsimodule interface, and you have to create weblockfactory to implement nsifactory and create a factory that hands instances of your component to clients. ...
...And 11 more matches
RangeError: argument is not a valid code point - JavaScript
the javascript exception "invalid code point" occurs when nan values, negative integers (-1), non-integers (5.4), or values larger than 0x10ffff (1114111) are used with string.fromcodepoint(). message rangeerror: {0} is not a valid code point (firefox) rangeerror: invalid code point {0} (chromium) error type rangeerror what went wrong? ...
... the javascript exception "invalid code point" occurs when nan values, negative integers (-1), non-integers (5.4), or values larger than 0x10ffff (1114111) are used with string.fromcodepoint(). message rangeerror: {0} is not a valid code point (firefox) rangeerror: invalid code point {0} (chromium) error type rangeerror what went wrong? ...
...ntegers (5.4), or values larger than 0x10ffff (1114111) are used with string.fromcodepoint(). message rangeerror: {0} is not a valid code point (firefox) rangeerror: invalid code point {0} (chromium) error type rangeerror what went wrong? ...
...And 11 more matches
encodeURI() - JavaScript
the encodeuri() function encodes a uri by replacing each instance of certain characters by one, two, three, or four escape sequences representing the utf-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax encodeuri(uri) parameters uri a complete uri. return value a new string representing the provided string encoded as a uri. description the encodeuri() function does not encode characters that have special meaning (reserved characters) for a uri. the following example shows all the p...
...g encoded as a uri. description the encodeuri() function does not encode characters that have special meaning (reserved characters) for a uri. the following example shows all the parts that a uri "scheme" can possibly contain. note how certain characters are used to signify special meaning: http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor hence encodeuri() does not encode characters that are necessary to formulate a complete uri. also, encodeuri() does not encode a few additional characters, known as "unreserved marks", which do not have a reserved purpose but are allowed in a uri "as is". (see rfc2396) encodeuri() escapes all characters except: not escaped: a-z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # examples encodeuri vs e...
...ri() does not encode characters that are necessary to formulate a complete uri. also, encodeuri() does not encode a few additional characters, known as "unreserved marks", which do not have a reserved purpose but are allowed in a uri "as is". (see rfc2396) encodeuri() escapes all characters except: not escaped: a-z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # examples encodeuri vs encodeuricomponent encodeuri() differs from encodeuricomponent() as follows: var set1 = ";,/?:@&=+$#"; // reserved characters var set2 = "-_.!~*'()"; // unreserved marks var set3 = "abc abc 123"; // alphanumeric characters + space console.log(encodeuri(set1)); // ;,/?:@&=+$# console.log(encodeuri(set2)); // -_.!~*'() console.log(encodeuri(set3)); // abc%20abc%20123 (the space gets encoded as %20) ...
...And 11 more matches
JS_EncodeString
this article covers features introduced in spidermonkey 1.8 convert a javascript string to a c string. syntax char * js_encodestring(jscontext *cx, jsstring *str); char * js_encodestringtoutf8(jscontext *cx, js::handlestring str); // added in spidermonkey 24 name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext.. str jsstring * / js::handlestring a string to encode. description js_encodestring and js_encodestringtoutf8 convert the specified javascript str to a c string (an array of 8-bit chars). if js_cstringsareutf8 is true, then the returned string of js_encodestring is utf-8, and the conversion is lossless. otherwise the high byte is si...
...the caller may modify it and is responsible for freeing it. ...
...the caller may modify it and is responsible for freeing it. note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can return a corrupted copy of the contents of the string. ...
...And 9 more matches
TextDecoder - Web APIs
the textdecoder interface represents a decoder for a specific text encoding, such as utf-8, iso-8859-2, koi8-r, gbk, etc. a decoder takes a stream of bytes as input and emits a stream of code points. examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array. ...
...ts a decoder for a specific text encoding, such as utf-8, iso-8859-2, koi8-r, gbk, etc. a decoder takes a stream of bytes as input and emits a stream of code points. examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array. ...
... specific text encoding, such as utf-8, iso-8859-2, koi8-r, gbk, etc. a decoder takes a stream of bytes as input and emits a stream of code points. examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array. ...
...And 9 more matches
String.prototype.codePointAt() - JavaScript
the codepointat() method returns a non-negative integer that is the unicode code point value. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.codepointat(pos) parameters pos position of an element in str to return the code point value from. return value a number representing the code point value of the character at the given pos. if there is no element at pos, returns undefined. description if there is no element at the specified position, undefined is returned. if no utf-16 surrogate pair begins at pos, the code unit at pos is returned. polyfill the following extends strings to include the ...
... return the code point value from. return value a number representing the code point value of the character at the given pos. if there is no element at pos, returns undefined. description if there is no element at the specified position, undefined is returned. if no utf-16 surrogate pair begins at pos, the code unit at pos is returned. polyfill the following extends strings to include the codepointat() function as specified in ecmascript 2015 for browsers without native support. ...
... the given pos. if there is no element at pos, returns undefined. description if there is no element at the specified position, undefined is returned. if no utf-16 surrogate pair begins at pos, the code unit at pos is returned. polyfill the following extends strings to include the codepointat() function as specified in ecmascript 2015 for browsers without native support. ...
...And 9 more matches
KeyboardEvent.code - Web APIs
the keyboardevent.code property represents a physical key on the keyboard (as opposed to the character generated by pressing the key). in other words, this property returns a value that isn't altered by keyboard layout or the state of the modifier keys. if the input device isn't a physical keyboard, but is instead a virtual keyboard or accessibility device, the returned value will be set by the browser to match as closely as possible to what would happen with a physical keyboard, to maximize compatibility between physical and virtual input devices. ...
...e, the returned value will be set by the browser to match as closely as possible to what would happen with a physical keyboard, to maximize compatibility between physical and virtual input devices. this property is useful when you want to handle keys based on their physical positions on the input device rather than the characters associated with those keys; this is especially common when writing code to handle input for games that simulate a gamepad-like environment using keys on the keyboard. be aware, however, that you can't use the value reported by keyboardevent.code to determine the character generated by the keystroke, because the keycode's name may not match the actual character that's printed on the key or that's generated by the computer when the key is pressed. for example, the cod...
...s on the keyboard. be aware, however, that you can't use the value reported by keyboardevent.code to determine the character generated by the keystroke, because the keycode's name may not match the actual character that's printed on the key or that's generated by the computer when the key is pressed. for example, the code returned is "keyq" for the q key on a qwerty layout keyboard, but the same code value also represents the ' key on dvorak keyboards and the a key on azerty keyboards. that makes it impossible to use the value of code to determine what the name of the key is to users if they're not using an anticipated keyboard layout. ...
...And 8 more matches
PerformanceResourceTiming.encodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged. ...
...dysize read-only property represents the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. note: this feature is available in web workers. if the resource is retrieved from an application cache or a local resource, it must return the size of the payload body before removing any applied content-codings. syntax resource.encodedbodysize; return value a number representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their val...
...ber representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. ...
...And 8 more matches
Unicode property escapes - JavaScript
unicode property escapes regular expressions allows for matching characters based on their unicode properties. a character is described by several properties which are either binary ("boolean-like") or non-binary. for instance, unicode property escapes can be used to match emojis, punctuations, letters (even letters from specific languages or scripts), etc. note: for unicode property escapes to work, a regular expression must use the u flag which indicates a string must be considered as a series of unicode code points. see also regexp.prototype.unicode. note: some unicode properties encompasses much more characters than some character classes (such as \w which matches only latin letters, a to z) but the latter is better supported among browsers (as of january 2020). syntax the follo...
...ts. see also regexp.prototype.unicode. note: some unicode properties encompasses much more characters than some character classes (such as \w which matches only latin letters, a to z) but the latter is better supported among browsers (as of january 2020). syntax the following section is also duplicated on this cheatsheet. do not forget to edit it as well, thanks! // non-binary values \p{unicodepropertyvalue} \p{unicodepropertyname=unicodepropertyvalue} // binary and non-binary values \p{unicodebinarypropertyname} // negation: \p is negated \p \p{unicodepropertyvalue} \p{unicodebinarypropertyname} general_category (gc) script (sc) script_extensions (scx) see also propertyvaluealiases.txt unicodebinarypropertyname the name of a binary property. e.g.: ascii, alpha, math, dia...
...e} // binary and non-binary values \p{unicodebinarypropertyname} // negation: \p is negated \p \p{unicodepropertyvalue} \p{unicodebinarypropertyname} general_category (gc) script (sc) script_extensions (scx) see also propertyvaluealiases.txt unicodebinarypropertyname the name of a binary property. e.g.: ascii, alpha, math, diacritic, emoji, hex_digit, math, white_space, etc. see unicode data proplist.txt for more info. unicodepropertyname the name of a non-binary property: unicodepropertyvalue one of the tokens listed in the values section, below. many values have aliases or shorthand (e.g. the value decimal_number for the general_category property may be written nd, digit, or decimal_number). for most values, the unicodepropertyname part and equals sign may be omitted. if a...
...And 8 more matches
nsIScriptableUnicodeConverter
this legacy api represents binary data using the lower haft of each 16-bit code unit in a javascript string. if the other apis you are reading data from or writing data to don't require you to use this legacy representation, you should use textdecoder and textencoder (available to chrome javascript via components.utils.importglobalproperties) instead of this api. intl/uconv/idl/nsiscriptableuconv.idlscriptable this interface is a unicode encoder for use by scripts. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
...rties) instead of this api. intl/uconv/idl/nsiscriptableuconv.idlscriptable this interface is a unicode encoder for use by scripts. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
...nterface is a unicode encoder for use by scripts. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
...And 7 more matches
BaseAudioContext.decodeAudioData() - Web APIs
the decodeaudiodata() method of the baseaudiocontext interface is used to asynchronously decode audio file data contained in an arraybuffer. in this case the arraybuffer is loaded from xmlhttprequest and filereader. the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise. this is the preferred method of creating an audio source for web audio api from an audio track. this method only works on complete file data, not fragments of audio file data. ...
... arraybuffer is loaded from xmlhttprequest and filereader. the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise. this is the preferred method of creating an audio source for web audio api from an audio track. this method only works on complete file data, not fragments of audio file data. syntax older callback syntax: baseaudiocontext.decodeaudiodata(arraybuffer, successcallback, errorcallback); newer promise-based syntax: promise<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader. successcallback a callback function to be invoked when the decoding succes...
...se<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader. successcallback a callback function to be invoked when the decoding successfully finishes. the single argument to this callback is an audiobuffer representing the decodeddata (the decoded pcm audio data). usually you'll want to put the decoded data into an audiobuffersourcenode, from which it can be played and manipulated how you want. errorcallback an optional error callback, to be invoked if an error occurs when the audio data is being decoded. return value void, or a promise object that fulfills with the decodeddata. example in this section we will firs...
...And 7 more matches
PerformanceResourceTiming.decodedBodySize - Web APIs
the decodedbodysize read-only property returns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. if the resource is retrieved from an application cache or local resources, it returns the size of the payload after removing any applied content-codings. note: this feature is available in web workers. syntax resource.decodedbodysize; return value the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the *size properties and print their values // if supported. ...
...ce.decodedbodysize; return value the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the *size properties and print their values // if supported. ...
... octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the *size properties and print their values // if supported. ...
...And 7 more matches
TextEncoder - Web APIs
textencoder takes a stream of code points as input and emits a stream of utf-8 bytes. note: there is a polyfill implementation to support non-utf-8 text encodings on github. example const encoder = new textencoder() const view = encoder.encode('€') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding. properties the textencoder interface doesn't inherit any property. textencoder.prototype.encodingread only always returns "utf-8". methods the textencoder interface doesn't inherit any method. textencoder.prototype.encode() takes a usvstring as input, and returns a uint8array containing utf-8 encoded text. ...
... polyfill the below polyfill is compliant with the standard and therefore only supports utf-8. ...
...at will generate a byte stream with utf-8 encoding. properties the textencoder interface doesn't inherit any property. textencoder.prototype.encodingread only always returns "utf-8". methods the textencoder interface doesn't inherit any method. textencoder.prototype.encode() takes a usvstring as input, and returns a uint8array containing utf-8 encoded text. textencoder.prototype.encodeinto() takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. this is potentially more performant than the older encode() method. polyfill the below polyfill is compliant with the standard and therefore only supports utf-8. it is designed to work in ie5 "out of the box". however...
...And 7 more matches
Components.isSuccessCode
summary determines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively. syntax var succeeded = components.issuccesscode(returncode); parameters returncode the return code (of type nsresult) to be checked. description components.issuccesscode() may be used to determine whether an xpcom return code (an nsresult) indicates success or failure. an xpcom return code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. note: a non-zero xpcom return code (that is, not ns_ok) does not necessarily indicate failure. ...
...however, if you are using asynchronous apis, it may be essential. ...
...however, if you are using asynchronous apis, it may be essential. ...
...And 6 more matches
KeyboardEvent.charCode - Web APIs
the charcode read-only property of the keyboardevent interface returns the unicode value of a character key pressed during a keypress event. do not use this property, as it is deprecated. use the key property instead. syntax var code = event.charcode; return value a number that represents the unicode value of the character key that was pressed. ...
...property of the keyboardevent interface returns the unicode value of a character key pressed during a keypress event. do not use this property, as it is deprecated. use the key property instead. syntax var code = event.charcode; return value a number that represents the unicode value of the character key that was pressed. ...
...of the keyboardevent interface returns the unicode value of a character key pressed during a keypress event. do not use this property, as it is deprecated. use the key property instead. syntax var code = event.charcode; return value a number that represents the unicode value of the character key that was pressed. ...
...And 6 more matches
Solve common problems in your JavaScript code - Learn web development
correctly. ...
...sure you don't place any semi-colons incorrectly. for example: correct wrong elem.style.color = 'red'; elem.style.color = 'red;' functions there are a number of things that can go wrong with functions. one of the most common errors is to declare the function, but not call it anywhere. ...
... alert('this is my function.'); }; this code won't do anything unless you call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function. running code after a return statement remember also that when you return from a function, the javascript interpreter exits the function — no code after the return statement will run. in fact, some browsers (like firefox) will give you an error message in the developer console if you have code after a return statement. firefox gives you "unreachable code after return statement". object notation versus nor...
...And 5 more matches
Contributing to the Mozilla code base
and/or html/css firefox developers documentation devtools javascript and/or html/css contribute to devtools add-ons javascript and/or html/css contribute to add-ons firefox focus for android java contribute to firefox focus for android firefox for fire tv java contribute to firefox for fire tv firefox preview (mobile browser, codename: "fenix") kotlin contribute to firefox preview firefox for ios swift contribute to firefox for ios firefox focus for ios swift contribute to firefox focus for ios mozilla hubs javascript and/or html/css, vr contribute to mozilla hubs servo rust contribute to servo there are even many ways to contribute to the mozilla mis...
... using the components list. browse this component on bugzilla for related bugs ask in our matrix channels : #introduction:mozilla.org or #developers:mozilla.org find a bug we've identified as a good fit for new contributors. with more than a million bugs filed in bugzilla, it can be hard to know where to start, so we've created these bug categories to make getting involved a little easier: codetribute - our site for finding bugs that are mentored, some are good first bugs, some are slightly harder. your mentor will help guide you with the bug fix and through the submission and landing process. good first bugs - are the best way to take your first steps into the mozilla ecosystem. they're all about small changes, sometimes as little as a few lines, but they're a great way to learn about...
...er. your mentor will help guide you with the bug fix and through the submission and landing process. good first bugs - are the best way to take your first steps into the mozilla ecosystem. they're all about small changes, sometimes as little as a few lines, but they're a great way to learn about setting up your development environment, navigating bugzilla, and making contributions to the mozilla codebase. visit firefox-dev.tools - we list firefox developer tools bugs for new contributors. student projects - are larger projects, such as might be suitable for a university student for credit. of course, if you are not a student, feel free to fix one of these bugs. we maintain two lists: one for projects based on the existing codebase, and one for implementing new applications. use a bug sear...
...And 5 more matches
Error codes returned by Mozilla APIs
an error will typically be displayed on the error console, but can be captured using a try-catch block in javascript. these constants can be accessed through components.results. for example, by using components.results.ns_error_not_initialized general errors the following errors are general and can occur when using any component. ns_error_not_initialized (0xc1f30001) an attempt was made to use a component or object which has not yet been initialized. ...
...use a value was set to null when this was not expected. ns_error_abort (0x80004004) this error indicates that an operation failed and the caller should abort whatever action is being performed. this typically will occur if an operation could not complete properly. ns_error_failure (0x80004005) this is the most general of all the errors and occurs for all errors for which a more specific error code does not apply. ns_error_unexpected (0x8000ffff) an operation did not complete due to a condition which was not expected. this error occurred rather than continuing. ns_error_out_of_memory (0x8007000e) this error occurs when there is not enough memory available to carry out an operation, or an error occurred trying to allocate memory. ns_error_illegal_value (0x80070057) an argument supplied...
...eady been closed. ns_base_stream_oserror (0x80470003) this error occurs when an operating system error occurs. currently, this error only occurs when a file stream is closed. ns_base_stream_illegal_args (0x80470004) ns_base_stream_no_converter (0x80470005) ns_base_stream_bad_conversion (0x80470006) this error occurs when the component nsistringbundleservice has been set with a badly encoded property file. try using utf-8 encoding instead. see nsistringbundle. ns_base_stream_would_block (0x80470007) this error occurs when an attempt is made to read from a non blocking stream yet there is not enough data available to read without waiting for more. document and node errors the following errors can occur when using documents, nodes and elements. ns_error_dom_index_size_err (0x8...
...And 5 more matches
String.fromCharCode() - JavaScript
the static string.fromcharcode() method returns a string created from the specified sequence of utf-16 code units. the source for this interactive example is stored in a github repository. if 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 string.fromcharcode(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of numbers that are utf-16 code units. the range is between 0 and 65535 (0xffff). numbers greater than 0xffff are truncated. no validity checks are performed. return value a string of length n consisting of the n specified utf-16 code units. description this method returns a string and not a string object. ...
...rcode(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of numbers that are utf-16 code units. the range is between 0 and 65535 (0xffff). numbers greater than 0xffff are truncated. no validity checks are performed. return value a string of length n consisting of the n specified utf-16 code units. description this method returns a string and not a string object. because fromcharcode() is a static method of string, you always use it as string.fromcharcode(), rather than as a method of a string object you created. returning supplementary characters in utf-16, the most common characters can be represented by a single 16-bit value (i.e. a code unit). ...
...a valid combination of two surrogates used to represent a supplementary character is known as a surrogate pair. ...
...And 5 more matches
Loading and running WebAssembly code - WebAssembly
webassembly is not yet integrated with <script type='module'> or es2015 import statements, thus there is not a path to have the browser fetch modules for you using imports. ...
... there is not a path to have the browser fetch modules for you using imports. the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it. this is analogous to new function(string), except that we are substituting a string of characters (javascript source code) with an array buffer of bytes (webassembly source code). the newer webassembly.compilestreaming/webassembly.instantiatestreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step. so how do we get those bytes into an array buffer and compiled? the following sections explain.
...and compiled? the following sections explain. using fetch fetch is a convenient, modern api for fetching network resources. ...
...And 5 more matches
Building Firefox with Rust code - Archive of obsolete content
our goal is to always ship a firefox release build with a stable rust toolchain release. ...
...our goal is to always ship a firefox release build with a stable rust toolchain release. ...
...fox release build with a stable rust toolchain release. if you don't have rust already, use the rustup tool to install it and update as new releases become available, or use the ./mach bootstrap command. the build system will generate a special 'rust unified library' crate, compiled to a static library (libgkrust.a) which is in turn linked into xul, so all public symbols will be available to c++ code. ...
...And 4 more matches
imgIEncoder
modules/libpr0n/public/imgiencoder.idlscriptable please add a summary to this article. ...
...lease add a summary to this article. ...
...eam last changed in gecko 1.9 (firefox 3) method overview void addimageframe( [array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 frameformat, in astring frameoptions); void encodeclipboardimage(in nsiclipboardimage aclipboardimage, out nsifile aimagefile); obsolete since gecko 1.9 void endimageencode(); void initfromdata([array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 inputformat, in astring outputoptions); void startimageencode(in pruint32 width, in pruint32 height, in pruint32 inputformat, in astring outputoptions); constants possible values for input format (note that not all image fo...
...And 4 more matches
RTCRtpTransceiver.setCodecPreferences() - Web APIs
the rtcrtptransceiver method setcodecpreferences() configures the transceiver's codecs given a list of rtcrtpcodeccapability objects specifying the new preferences for each codec. the specified set of codecs and configurations will be used for all future connections including this transceiver until this method is called again. when preparing to open an rtcpeerconnection, you can change the codec parameters from the user agent's default configuration by calling setcodecparameters() before calling either rtcpeerconnection.createoffer() or createanswer(). a guide to codecs supported by webrtc—and each codec's positive and negative characteristics—can be found in codecs used by webrtc. ...
.... when preparing to open an rtcpeerconnection, you can change the codec parameters from the user agent's default configuration by calling setcodecparameters() before calling either rtcpeerconnection.createoffer() or createanswer(). a guide to codecs supported by webrtc—and each codec's positive and negative characteristics—can be found in codecs used by webrtc. syntax rtcrtptransceiver.setcodecpreferences(codecs) parameters codecs an array of rtcrtpcodeccapability objects, in order of preference, each providing the parameters for one of the transceiver's supported codecs. if codecs is empty, the codec configurations are all returned to the user agent's defaults. note: any codecs not included in codecs will not be considered during the process of negotiating a connection. this ...
...ters codecs an array of rtcrtpcodeccapability objects, in order of preference, each providing the parameters for one of the transceiver's supported codecs. if codecs is empty, the codec configurations are all returned to the user agent's defaults. note: any codecs not included in codecs will not be considered during the process of negotiating a connection. this lets you prevent the use of codecs you don't wish to use. return value undefined exceptions invalidaccesserror the codecs list includes one or more codecs which are not supported by the transceiver. usage notes getting a list of supported codecs you can only include in the codecs list codecs which the transceiver actually supports. that means that either the associated rtcrtpsender or the rtcrtpreceiver needs to su...
...And 4 more matches
Canvas code snippets - Archive of obsolete content
this can be very useful to compare for example if a user has painted over another area as explained in this blog post. ...
... saving a canvas image to a file the following function accepts a canvas object and a destination file path string. the canvas is converted to a png file and saved to the specified location. the function returns a promise which resolves when the file has been completely s...
... saving a canvas image to a file the following function accepts a canvas object and a destination file path string. the canvas is converted to a png file and saved to the specified location. the function returns a promise which resolves when the file has been completely saved. function savecanvas(canvas...
...And 3 more matches
Bytecodes
a frame on the stack has space for javascript values (the tagged value format) in a few different categories. ...
...a frame on the stack has space for javascript values (the tagged value format) in a few different categories. ...
...a frame on the stack has space for javascript values (the tagged value format) in a few different categories. ...
...And 3 more matches
JS_EncodeCharacters
obsolete since jsapi 19this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. convert a 16-bit string to an 8-bit string. syntax jsbool js_encodecharacters(jscontext *cx, const jschar *src, size_t srclen, char *dst, size_t *dstlen); name type description cx jscontext * a context. src const jschar * the pointer to 16-bit values of jsstring. this can be obtained with js_getstringchars. srclen size_t the length of the source string, in 16-bit values. dst const char * the pointer to an array of bytes to be filled with encoded characters; or null. the caller is responsible for allocating an...
...er is responsible for allocating and freeing this buffer. dstlenp size_t * in/out parameter. on entry, if dst is non-null, *dstlenp must be the length of the destination string in 16-bit units. on success, *dstlenp receives the length of the converted string, in bytes. on failure, *dstlenp receives the number of bytes written to dst before the error occurred. description js_encodecharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values. if spidermonkey was built with js_c_strings_are_utf8 defined or js_setcstringsareutf8 was called, the string is converted to utf-8. otherwise each character is simply truncated to 8 bits. if utf-8 is turned on, the length of the encoded string may vary. to calculate the number of b...
...haracters of a jschar array into a char array, converting the 16-bit values to 8-bit values. if spidermonkey was built with js_c_strings_are_utf8 defined or js_setcstringsareutf8 was called, the string is converted to utf-8. otherwise each character is simply truncated to 8 bits. if utf-8 is turned on, the length of the encoded string may vary. to calculate the number of bytes needed, call js_encodecharacters twice, like this: /* determine how many bytes to allocate. ...
...And 3 more matches
BlobEvent.timecode - Web APIs
working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
... working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
... working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
...And 3 more matches
KeyboardEvent: code values - Web APIs
the following tables show what code values are used for each native scancode or virtual keycode on major platforms. the reason is that some browsers choose to interpret physical keys differently, there are some differences in which keys map to which codes. these tables show those variations when known. code values code values on windows this table shows the windows scan codes representing keys and the keyboardevent.code values which correspond to those hardware keys. only keys which generate scan codes on windows are listed. ...
...erpret physical keys differently, there are some differences in which keys map to which codes. these tables show those variations when known. code values code values on windows this table shows the windows scan codes representing keys and the keyboardevent.code values which correspond to those hardware keys. only keys which generate scan codes on windows are listed. ...
... differently, there are some differences in which keys map to which codes. these tables show those variations when known. code values code values on windows this table shows the windows scan codes representing keys and the keyboardevent.code values which correspond to those hardware keys. only keys which generate scan codes on windows are listed. ...
...And 3 more matches
Writing Web Audio API code that works in every browser - Developer guides
more, as a result of the spec being still in flux, some browsers use deprecated properties and method names that are not present in standards-compliant browsers: safari uses the old method names, firefox uses the new ones, and chrome and opera use both. in addition, not all features of web audio are already implemented in firefox yet. what do we do!? we don't want to maintain two or more separate code bases, and feature detection code is cumbersome! plus we want to write code that reliably works in the future, or at least, works with a minimum amount of changes. is there a way to satisfy all these constraints at the same time? probably! writing for today (and tomorrow) first, get a copy of audiocontext-monkeypatch by chris wilson. this little library will "normalise" the interfaces for you and...
...and it won't do anything if the unprefixed versions are already present. once you include it in your page, you can write in "modern web audio api" style, and do things such as: var audiocontext = new audiocontext(); everywhere, including chrome/ium, opera, safari, and ---of course!--- firefox. ...
...an write in "modern web audio api" style, and do things such as: var audiocontext = new audiocontext(); everywhere, including chrome/ium, opera, safari, and ---of course!--- firefox. also, if new methods such as start are not detected in some nodes, the library will also alias them to their old names. thus, start is mapped to noteon, stop to noteoff, and so on. ...
...And 3 more matches
The Unicode Bidirectional Text Algorithm - Developer guides
understanding this algorithm in at least basic terms is helpful when you're striving to produce localization-ready web content or apps. in this guide, we'll take a look at the bidi algorithm and learn in general what it does and how it applies to your content, so that you'll be better prepared when using the features of html and css to which the algorithm applies while determining the order and directionality of text during rendering. ...
...ity of text during rendering. fundamentals (base direction, character types, etc) the algorithm character level directionality directional runs (what they are, how base direction applies) handling neutral characters overriding the algorithm content about using html and css to override the default behavior of the algorithm; include info about isolating ranges etc. ...
.... fundamentals (base direction, character types, etc) the algorithm character level directionality directional runs (what they are, how base direction applies) handling neutral characters overriding the algorithm content about using html and css to override the default behavior of the algorithm; include info about isolating ranges etc. ...
...And 3 more matches
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
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. ...
...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. ...
...her 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. ...
...And 2 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
nss sample code 3: basic encryption and macing this example program demonstrates how to encrypt and mac a file. ...
... nss sample code 3: basic encryption and macing this example program demonstrates how to encrypt and mac a file. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. */ /* nspr headers */ #include <prthread.h> #include <plgetopt.h> #include <prerror.h> #include <prinit.h> #include <prlog.h> #include <prtypes.h> #include <plstr.h> /* * gather a cka_id */ secstatus gathercka_id(...
...And 2 more matches
NSS Sample Code sample5
nss sample code 5: pki encryption with a raw public & private key in der format /* example code to illustrate pki crypto ops (encrypt with public key, * decrypt with private key) * * no nss db needed. the public key & private key to use are * sourced from a base64-encoded der subjectpublickeyinfo structure, * and a base64-encoded der privatekeyinfo structure. * * there is no attempt to link the public & private key together * * this example does not do any padding. it simply encrypts/decrypts a block * of length equal to modulus length of the public/private key. ...
...re * sourced from a base64-encoded der subjectpublickeyinfo structure, * and a base64-encoded der privatekeyinfo structure. * * there is no attempt to link the public & private key together * * this example does not do any padding. it simply encrypts/decrypts a block * of length equal to modulus length of the public/private key. ...
...vate key together * * this example does not do any padding. it simply encrypts/decrypts a block * of length equal to modulus length of the public/private key. ...
...And 2 more matches
JS_EncodeStringToBuffer
this article covers features introduced in spidermonkey 1.8.5 convert a javascript string to a c string. syntax size_t js_encodestringtobuffer(jscontext *cx, jsstring *str, char *buffer, size_t length); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * a string to encode. buffer char * a character buffer to receive encoded string. length size_t the size of buffer in bytes. description js_encodestringtobuffer converts the specified javascript str to a c string (an array of 8-bit chars) and fills the specified buffer with up to length bytes of the string. it returns the length of the whole stri...
... char * a character buffer to receive encoded string. length size_t the size of buffer in bytes. description js_encodestringtobuffer converts the specified javascript str to a c string (an array of 8-bit chars) and fills the specified buffer with up to length bytes of the string. it returns the length of the whole string encoding or (size_t)-1 if the string can't be encoded as bytes. if the returned value is greater than the length you specified, the string was truncated. to encode to utf8, use js::getdeflatedutf8stringlength and js::deflatestringtoutf8buffer instead. ...
...nd fills the specified buffer with up to length bytes of the string. it returns the length of the whole string encoding or (size_t)-1 if the string can't be encoded as bytes. if the returned value is greater than the length you specified, the string was truncated. to encode to utf8, use js::getdeflatedutf8stringlength and js::deflatestringtoutf8buffer instead. ...
...And 2 more matches
Mailnews and Mail code review requirements
mailnews and mail review rules patches affecting thunderbird user experience or interfaces note: it is recommended that when working on bugs that affect user experience or interfaces, that ui-review is obtained at an early stage in the patch development process. ...
... mailnews and mail review rules patches affecting thunderbird user experience or interfaces note: it is recommended that when working on bugs that affect user experience or interfaces, that ui-review is obtained at an early stage in the patch development process. ...
... mailnews and mail review rules patches affecting thunderbird user experience or interfaces note: it is recommended that when working on bugs that affect user experience or interfaces, that ui-review is obtained at an early stage in the patch development process. ...
...And 2 more matches
DOMException.code - Web APIs
Web › API › DOMException › code
candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
...And 2 more matches
HTMLImageElement.decode() - Web APIs
return value a promise which is resolved once the image data is ready to be used. exceptions encodingerror a domexception indicating that an error occurred while decoding the image. ...
...he dom. this can be used to initiate loading of the image prior to attaching it to an element in the dom (or adding it to the dom as a new element), so that the image can be rendered immediately upon being added to the dom. this, in turn, prevents the rendering of the next frame after adding the image to the dom from causing a delay while the image loads. ...
...g of the next frame after adding the image to the dom from causing a delay while the image loads. syntax var promise = htmlimageelement.decode(); parameters none. return value a promise which is resolved once the image data is ready to be used. exceptions encodingerror a domexception indicating that an error occurred while decoding the image. usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use. at tha...
...And 2 more matches
TextDecoder() - Web APIs
the textdecoder() constructor returns a newly created textdecoder object for the encoding specified in parameter. if the value for utflabel is unknown, or is one of the two values leading to a 'replacement' decoding algorithm ( "iso-2022-cn" or "iso-2022-cn-ext"), a domexception with the "typeerror" value is thrown. syntax decoder = new textdecoder(utflabel, options); parameters utflabeloptional is a domstring, defaulting to "utf-8", containing the label of the encoder. ...
... algorithm ( "iso-2022-cn" or "iso-2022-cn-ext"), a domexception with the "typeerror" value is thrown. syntax decoder = new textdecoder(utflabel, options); parameters utflabeloptional is a domstring, defaulting to "utf-8", containing the label of the encoder. ...
... 'iso-2022-jp' "csshiftjis", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis" 'shift-jis' "cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601...
...And 2 more matches
unicode-range - CSS: Cascading Style Sheets
the unicode-range css descriptor sets the specific range of characters to be used from a font defined by @font-face and made available for use on the current page. if the page doesn't use any character in this range, the font is not downloaded; if it uses at least one, the whole font is downloaded. syntax /* <unicode-range> values */ unicode-range: u+26; /* single codepoint */ unicode-range: u+0-7f; unicode-range: u+0025-00ff; /* codepoint range */ unicode-range: u+4??; /* wildcard range */ unicode-range: u+0025-00ff, u+4??; /* multiple values */ values single codepoint a single unicode character code point, for example u+26. codepoint range a range of unicode code points. so for example, u+0025-00ff means include all characters in the range u+0025 ...
... description the purpose of this descriptor is to allow the font resources to be segmented so that a browser only needs to download the font resource needed for the text content of a particular page. ...
... description the purpose of this descriptor is to allow the font resources to be segmented so that a browser only needs to download the font resource needed for the text content of a particular page. ...
...And 2 more matches
unicode-bidi - CSS: Cascading Style Sheets
the unicode-bidi css property, together with the direction property, determines how bidirectional text in a document is handled. for example, if a block of content contains both left-to-right and right-to-left text, the user-agent uses a complex unicode algorithm to decide how to display the text. the unicode-bidi property overrides this algorithm and allows the developer to control the text embedding. the unicode-bidi and direction properties are the only properties that are not affected by the all shorthand. note: this property is intended for document type definition (dtd) designers. web designers and similar authors should not override it. ...
...o display the text. the unicode-bidi property overrides this algorithm and allows the developer to control the text embedding. the unicode-bidi and direction properties are the only properties that are not affected by the all shorthand. note: this property is intended for document type definition (dtd) designers. web designers and similar authors should not override it. /* keyword values */ unicode-bidi: normal; unicode-bidi: embed; unicode-bidi: isolate; unicode-bidi: bidi-override; unicode-bidi: isolate-override; unicode-bidi: plaintext; /* global values */ unicode-bidi: inherit; unicode-bidi: initial; unicode-bidi: unset; syntax values normal the element does not offer an additional level of embedding with respect to the bidirectional algorithm. for inline elements, implicit reorde...
...his keyword applies the isolation behavior of the isolate keyword to the surrounding content and the override behavior of the bidi-override keyword to the inner content. plaintext this keyword makes the elements directionality calculated without considering its parent bidirectional state or the value of the direction property. the directionality is calculated using the p2 and p3 rules of the unicode bidirectional algorithm. this value allows the display of data that is already formatted using a tool following the unicode bidirectional algorithm. formal definition initial valuenormalapplies toall elements, though some values have no effect on non-inline elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax normal | embed | isolate | bidi-override | isolate-ov...
...And 2 more matches
decodeURIComponent() - JavaScript
the decodeuricomponent() function decodes a uniform resource identifier (uri) component previously created by encodeuricomponent or by a similar routine. the source for this interactive example is stored in a github repository. if 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 decodeuricomponent(encodeduri) parameters encodeduri an encoded component of a uniform resource identifier. return value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component. exceptions throws an urierror ("malformed uri sequence") exception when used wrongly. ...
...request. syntax decodeuricomponent(encodeduri) parameters encodeduri an encoded component of a uniform resource identifier. return value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component. exceptions throws an urierror ("malformed uri sequence") exception when used wrongly. description replaces each escape sequence in the encoded uri component with the character that it represents. ...
...rm resource identifier. return value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component. exceptions throws an urierror ("malformed uri sequence") exception when used wrongly. description replaces each escape sequence in the encoded uri component with the character that it represents. ...
...And 2 more matches
Forms related code snippets - Archive of obsolete content
here are some <form> related code snippets. date picker (before implementing it in a working environment, please read the note about the const statement compatibility) <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>datepicker example - mdn</title> <script type="text/javascript"> /*\ |*| |*| datepicker example mdndeveloper network |*| |*| https://developer.mozilla.org/docs/code_snippets/forms |*| https://developer.mozilla.org/user:fusionchess |*| |*| this snippet is released under the gnu public license, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ (function () { function datepicker (otarget) { const otable = document.createelement("table"), ohrow = document.createelemen...
...n the preview of internet explorer 10. const is going to be defined by ecmascript 6, but with different semantics. similar to variables declared with the let statement, constants declared with const will be block-scoped. we used it only for didactic purpose. if you want a full browser compatibility of this library, please replace all the const statements with the var statements. ...
... going to be defined by ecmascript 6, but with different semantics. similar to variables declared with the let statement, constants declared with const will be block-scoped. we used it only for didactic purpose. if you want a full browser compatibility of this library, please replace all the const statements with the var statements. ...
...nsert some html tags or smiles or any custom text in a textarea. image preview before upload the filereader.prototype.readasdataurl() method can be useful, for example, to get a preview of an image before uploading it.[article] this example shows how to use it in this way. note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code you can see our crossbrowser possible solution for image preview. filter the digitation into a form field this example shows the use of the onkeypress event during a digitation into a form field in order to match some rules. ...
Code Samples - Archive of obsolete content
change the first line to specify the file that you want to launch. you can launch an executable file or some other file that your operating system knows how to open. note: on operating systems that use backslash characters, double each backslash character. on operating systems that use forward-slash characters, specify the file in the normal way. ...
...sh characters, double each backslash character. on operating systems that use forward-slash characters, specify the file in the normal way. const path = "c:\\windows\\charmap.exe" var file = components .classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile) file.initwithpath(path) file.launch() open a web page if your button is in firefox or seamonkey, use code like this to open a web page. change the first line to specify the page that you want to open: const url = "http://www.mozilla.org/" document .getelementbyid("content") .webnavigation .loaduri(url, 0, null, null, null) if your button is in thunderbird or sunbird, use code like this to open a web page. change the first line to specify the page that you want to open: const url = "http://www...
...otherwise it opens the window: const name = "...internal name of the window..." const uri = "...chrome uri of the window..." var w = components ...
...= url components .classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice) .loadurl(uri) compose an e-mail to compose an e-mail, use the same code as in the section open a web page above. change the first line to specify: const url = "mailto://" open an application window to open one of the application's windows, use code like this. if the window already exists, this code just focusses it. otherwise it opens the window: const name = "...internal name of the window..." const uri = "...chrome uri of the window..." var w = components .classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator) .getmostrecentwindow(name) if (w) w.focus() else components .classes["@...
Codec - MDN Web Docs Glossary: Definitions of Web-related terms
a codec (a blend word derived from "coder-decoder") is a program, algorithm, or device that encodes or decodes a data stream. a given codec knows how to handle a specific encoding or compression technology. ...
... a codec (a blend word derived from "coder-decoder") is a program, algorithm, or device that encodes or decodes a data stream. a given codec knows how to handle a specific encoding or compression technology. ...
... a codec (a blend word derived from "coder-decoder") is a program, algorithm, or device that encodes or decodes a data stream. a given codec knows how to handle a specific encoding or compression technology. ...
... a codec (a blend word derived from "coder-decoder") is a program, algorithm, or device that encodes or decodes a data stream. a given codec knows how to handle a specific encoding or compression technology. ...
The Firefox codebase: CSS Guidelines
this document contains guidelines defining how css inside the firefox codebase should be written, it is notably relevant for firefox front-end engineers. basics here are some basic tips that can optimize reviews if you are changing css: avoid !important but if you have to use it, make sure it's obvious why you're using it (ideally with a comment). the overriding css section contains more information about this. avoid magic numbers; prefer automatic sizing or alignment methods. some examples to avoid: absolutely positioned elements hardcoded values such as: vertical-align: -2px; . the reason you should avoid such "hardcoded" values is that, they don't necessarily work for all font-size configurations. avoid setting styles in javascript. it's generally better to set a cla...
... reused with or without changes. most of the time, the common component already follows the a11y/theme standards defined in this guide. so, when possible, always prefer editing common components to writing your own. also, it is good practice to introduce a common class when the new element you are styling reuses some styles from another element, this allows the maintenance cost and the amount of code duplication to be reduced. formatting spacing & indentation 2 spaces indentation is preferred add a space after each comma, except within color functions: linear-gradient(to bottom, black 1px, rgba(255,255,255,0.2) 1px) always add a space before !important. omit units on 0 values do this: margin: 0; not this: margin: 0px; use expanded syntax it is often harder to unde...
...olor: red; not this: border: red; put multiple selectors on different lines do this: h1, h2, h3 { font-family: sans-serif; text-align: center; } not this: h1, h2, h3 { font-family: sans-serif; text-align: center; } naming standards for class names lower-case-with-dashes is the most common. but camelcase is also used sometimes. try to follow the style of existing or related code. other tips assume ="true" in attribute selectors. example: use option[checked], not option[checked="true"]. avoid id selectors unless it is really the wanted goal, since ids have higher specificity and therefore are harder to override. using descendant selectors is good practice for performance when possible: for example: .autocomplete-item[selected] > .autocomplete-item...
...refore are harder to override. using descendant selectors is good practice for performance when possible: for example: .autocomplete-item[selected] > .autocomplete-item-title would be more efficient than .autocomplete-item[selected] .autocomplete-item-title overriding css before overriding any css rules, check whether overriding is really needed. sometimes, when copy-pasting older code, it happens that the code in question contains unnecessary overrides. this could be because the css that it was overriding got removed in the meantime. in this case, simply dropping the override should work. it is also good practice to look at whether the rule you are overriding is still needed: maybe the ux spec for the component has changed and that rule can actually be updated or removed. whe...
Working with Mozilla source code
the articles below will help you get your hands on the mozilla source code, learn to navigate the code, and how to get the changes you propose checked into the tree. getting a pre-configured mozilla build system virtual machine this is the easiest way to get started: use a virtualbox virtual machine which is already configured with a complete build environment for you to use. just boot the vm and build! viewing and searching mozilla source code online learn how to use searchfox, mozilla's online search and browsing tool for accessing the source code. this isn't a good way to download the code, but is a great way to search it. navigating the mozilla source code learn about the various folders in the mozilla source tree, and how to find what you're looking for. bugs for newco...
... svg cleanup guide guidelines and best practices for shipping new svgs. try servers mozilla products build on at least three platforms. ...
...e various folders in the mozilla source tree, and how to find what you're looking for. bugs for newcomers if you are new to the project and want something to work on, look here. interface development guide guidelines and documentation for how to create and update xpcom interfaces. the firefox codebase: css guidelines this document contains guidelines defining how css inside the firefox codebase should be written, it is notably relevant for firefox front-end engineers. ...
...codebase should be written, it is notably relevant for firefox front-end engineers. svg cleanup guide guidelines and best practices for shipping new svgs. try servers mozilla products build on at least three platforms. if you don't have access to them all, you can use the try servers to test your patches and make sure the tests pass. creating a patch once you've made a change to the mozilla code, the next step (after making sure it works) is to create a patch and submit it for review. this article needs to be updated fully for mercurial. getting commit access to the source code feel ready to join the few, the proud, the committers? find out how to get check-in access to the mozilla code. ...
JavaScript code modules
note: these are not the same thing as standard javascript modules. see export and import to learn more about how to use standard modules. javascript code modules let multiple privileged javascript scopes share code. for example, a module could be used by firefox itself as well as by extensions, in order to avoid code duplication. general topics using javascript code modules an introduction to how to use javascript code modules. components.utils.import how to import a javascript code module. components.utils.unload how to unload a javascript code module. code snippets: modules examples of how to use code modules. mozilla labs js modules this page features a list of javascript modules, along with download links and documentation, that extension developers can use in the...
...o how to use javascript code modules. components.utils.import how to import a javascript code module. components.utils.unload how to unload a javascript code module. code snippets: modules examples of how to use code modules. mozilla labs js modules this page features a list of javascript modules, along with download links and documentation, that extension developers can use in their code. standard code modules addonmanager.jsm an interface to install, manage, and uninstall add-ons. addonrepository.jsm provides a search of add-ons in the repository. assert.jsm implements the commonjs unit testing specification version 1.1, which provides a basic standardized interface for performing in-code logical assertions with optional, customizable error reporting. bookmarkhtml...
... customizableui.jsm allows you to interact with customizable buttons and items in firefox's main window ui. deferredtask.jsm run a task after a delay. ...
...he downloading capabilities of the platform. fileutils.jsm provides helpers for dealing with files. geometry.jsm provides routines for performing basic geometric operations on points and rectangles. http.jsm a wrapper for xmlhttprequest that provides convenient and simplified api for dealing with http requests. jni.jsm abstracts the js-ctypes to provide an interface that allows javascript code to call code running in native jvms. iso8601dateutils.jsm provides routines to convert between javascript date objects and iso 8601 date strings. log.jsm (formerly log4moz) provides a log4j style api for logging, log messages to various endpoints, such as the browser console or a file on disk. netutil.jsm provides helpful networking utility functions, including the ability to easily c...
Writing localizable code
this page tells you about best practices and guidelines when dealing with ui code with respect to localization. it is aimed at mozilla and extension developers. for technical details please also look at xul_tutorial:localization. about localizers a few notes about localizers for developers who rarely deal with them: localizers like tools, and they don't like editors, localization tools are often based on key-value pairs, at least some localizers have their talents focused on language skills and are not savvy in programming, or even building applications. ...
...bout localizers for developers who rarely deal with them: localizers like tools, and they don't like editors, localization tools are often based on key-value pairs, at least some localizers have their talents focused on language skills and are not savvy in programming, or even building applications. guidelines thus, there are a few guidelines you should follow to make localization of your code easier: choose good key names the names chosen for your keys (regardless of whether that's a dtd or a properties file) should be descriptive. think of them as long variable names. if you change the semantics of a localized string, change the key. this will more likely be a good key name, and it will help tools to pick up that the change you do is different from just a spell fix. try not to...
...r macros the use of #if #else #endif or #expand is strongly discouraged. there are few exceptions to this rule, but in general, the localized file should comply with standards and should not require build tools to be transformed. if you want to add build processing to localized files, be sure to request feedback from l10n@. in most cases, you can just as well put the processing into the content code and reference different key-value pairs in l10n. use a good source directory structure be sure to put the localizable files in the right place. the addition of new top-level directories is a compromise between module ownership in the cvsroot repository and the ease of localization. use a good chrome directory structure for a particular module mod, a target path jar:ab-cd.jar!/locale/ab-cd...
...mise between module ownership in the cvsroot repository and the ease of localization. use a good chrome directory structure for a particular module mod, a target path jar:ab-cd.jar!/locale/ab-cd/mod/foo.dtd has been widely tested and is a good place for your files referenced as chrome://mod/locale/foo.dtd. using a directory structure like this eases the localization process without the source code and is especcially recommended to extension authors. jar manifests can make this easy. l10n impact on frozen trees, there is the rule to not check in l10n-impact changes. so what does that mean? l10n-impact is any change to mozilla/@mod@/locales; localizers find out if they have to catch up on changes by doing bonsai queries, just as everybody else does. no change means that this query result...
NSS Sample Code Sample1
this is an example program that demonstrates how to do key generation and transport between cooperating servers. this program shows the following: rsa key pair generation naming rsa key pairs looking up a previously generated key pair by name creating aes and mac keys (or encryption and mac keys in general) wrapping symmetric keys using your own rsa key pair so that they can be stored on disk or in a database. ...
...a way to store large numbers of symmetric keys wrapping symmetric keys using an rsa key from another server unwrapping keys using your own rsa key pair the main part of the program shows a typical sequence of events for two servers that are trying to extablish a shared key pair. we will add message protection (encryption and macing) examples to this program in the future. sample code #include <iostream.h> #include "pk11pub.h" #include "keyhi.h" #include "nss.h" // key management for keys share among multiple hosts // // this example shows how to use nss functions to create and // distribute keys that need to be shared among multiple servers // or hosts. // // the management scheme assumes that one host is primary. it // generates the secret keys that will be used by all par...
...et_key_gen, 0, 160/8, 0); if (!key) { rv = 1; goto mac_done; } rv = wrapkey(key, pubkey, &mwrappedmackey); mac_done: if (key) pk11_freesymkey(key); } done: if (slot) pk11_freeslot(slot); return rv; } int server::exportpublickey(secitem **pubkeydata) { int rv = 0; seckeypublickey *pubkey = 0; rv = getpublickey(&pubkey); if (rv) goto done; *pubkeydata = seckey_encodedersubjectpublickeyinfo(pubkey); if (!*pubkeydata) { rv = 1; goto done; } done: if (pubkey) seckey_destroypublickey(pubkey); return rv; } int server::exportkeys(secitem *pubkeydata, secitem **wrappedenckey, secitem **wrappedmackey) { int rv; certsubjectpublickeyinfo *keyinfo = 0; seckeypublickey *pubkey = 0; secitem *data = 0; // make sure the keys are availa...
...v; } int server::exportkeys(secitem *pubkeydata, secitem **wrappedenckey, secitem **wrappedmackey) { int rv; certsubjectpublickeyinfo *keyinfo = 0; seckeypublickey *pubkey = 0; secitem *data = 0; // make sure the keys are available (server running) if (!menckey || !mmackey) { rv = 1; goto done; } // import the public key of the other server keyinfo = seckey_decodedersubjectpublickeyinfo(pubkeydata); if (!keyinfo) { rv = 1; goto done; } pubkey = seckey_extractpublickey(keyinfo); if (!pubkey) { rv = 1; goto done; } // export the encryption key rv = wrapkey(menckey, pubkey, &data); if (rv) goto done; // export the mac key rv = wrapkey(mmackey, pubkey, wrappedmackey); if (rv) goto done; // commit the rest of the operation *wrappedenck...
NSS Third-Party Code
often this is configurable at build time, with various trade-offs. ...
...often this is configurable at build time, with various trade-offs. ...
...often this is configurable at build time, with various trade-offs. ...
...often this is configurable at build time, with various trade-offs. ...
Getting SpiderMonkey source code
you can get the spidermonkey source code in gzipped form or directly from the mercurial repository. downloading gzipped spidermonkey source code you can download gzipped spidermonkey source code from the following urls: http://ftp.mozilla.org/pub/spidermonkey/releases/ http://ftp.mozilla.org/pub/spidermonkey/prereleases/ here is a command-line example of downloading and unzipping spidermonkey source code version 59.0: mkdir mozilla cd mozilla wget http://ftp.mozilla.org/pub/spidermonkey/prereleases/59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell. ...
...and-line example of downloading and unzipping spidermonkey source code version 59.0: mkdir mozilla cd mozilla wget http://ftp.mozilla.org/pub/spidermonkey/prereleases/59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell. getting the latest spidermonkey source code from mercurial the mercurial repository at https://hg.mozilla.org/mozilla-central/ hosts the latest spidermonkey sources. mercurial is also known as hg. the following command line downloads the entire mozilla repository, including the full change history and a lot of gecko and firefox source code that isn't part of spidermonkey. it also changes to the spidermonkey directory (js/src). hg clone ...
...to the spidermonkey directory (js/src). hg clone https://hg.mozilla.org/mozilla-central/ cd js/src to avoid getting the full change history, click the zip or gz links at https://hg.mozilla.org/index.cgi/mozilla-central/file/tip. this fetches a snapshot of the current mozilla tree. if you have problems with the instructions above, you can read the full details of using mercurial to get mozilla code here. that page also contains links to several bundles, which can be useful if you have a poor network connection. getting the latest spidermonkey source code from git the following command line downloads the entire mozilla repository, including the full change history and a lot of gecko and firefox source code that isn't part of spidermonkey. it also changes to the spidermonkey directory (js/s...
...cvs note: you will need to explicitly fetch the javascript shell sources even if you currently build another mozilla project, as there are files specific to the shell that are not normally found in a mozilla source tree. just like when you're fetching any other mozilla project from cvs, you need to log into the cvs server first. to do this, cd into the base directory you'd like to check out the code into, then enter the following command at your command line: cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot login when prompted, enter the password anonymous. once you've logged in, cd into the root of your cvs tree and enter the following command: cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co -l mozilla/js/src mozilla/js/src/config mozilla/js/src/editline mozilla/j...
imgIDecoder
modules/libpr0n/public/imgidecoder.idlscriptable base class for a decoder that reads an image from an input stream and sends it to an imgiloader object. inherits from: nsisupports last changed in gecko 1.7 this interface is the base class for decoders for specific image formats. method overview void close(); void flush(); void init(in imgiload aload); unsigned long writefrom(in nsiinputstream instr, in unsigned long count); methods close() closes the stream. void close(); parameters none. flush() flushes the stream. void flush(); parameters none. init() initializes an image decoder. void init( in imgiload aload ); parameters aload an imgiload object to receive the decoded image data. this object also implements the imgidec...
...you should always pass null as the first two parameters of the notification apis. writefrom() writes data into the stream from an input stream. ...
... output stream efficiently copy the data from the input stream into its internal buffer (if any). if this method was provided as an external facility, a separate char * buffer would need to be used in order to call the output stream's other write() method. ...
... order to call the output stream's other write() method. unsigned long writefrom( in nsiinputstream instr, in unsigned long count ); parameters instr the stream from which to read the encoded image data. ...
Finding the code for a feature
but here is how i find out. there are two key tools that you need. ...
...uiry, and i decided to follow my usual path and document what i do: hello i would like to add colours and tags to specific emails...by using nsimsgtagservice, can this be done? here is my (edited) response: nsimsgtagservice is used to store the list of valid tags, so it is not the correct way to tag messages. tags are applied using the message database property "keyword". i know the underlying code, but i don't remember the user interface level function to do it. but here is how i find out. there are two key tools that you need. the first is the dom inspector extension which i have routinely installed in all of my thunderbird installations. (for debug builds, you can make it appear by default using "ac_add_options --enable-extensions=default,venkman,inspector" which is part of my standard ...
... function to do it. but here is how i find out. there are two key tools that you need. the first is the dom inspector extension which i have routinely installed in all of my thunderbird installations. (for debug builds, you can make it appear by default using "ac_add_options --enable-extensions=default,venkman,inspector" which is part of my standard configuration). the second is mozilla's source code search tool mxr. i keep two prominent links to this on my firefox toolbar, one to comm-central string search, and one to comm-central file search. so, how did i use those to figure out how to do this? i know there is a menu command "tag" to tag the message - how does it do it? using dom inspector, i find the tag menu item, and i see that it uses command "cmd_tag". then i use mxr and look for "cm...
...ok at the last occurrence, and see it is just an enable item with no real action involved. oops, i guess i need to get the submenu instead. repeating this process, i see that the submenu items all call a function togglemessagetagmenu. looking that up in mxr, its underlying function uses a very strange call prevhdrfolder[toggler](messages, key) to change the key. trying to figure that out from the code, i see that is just a clever way to do the addkeywordstomessages or removekeywordsfrommessages method call. (please don't do that guys, it really makes code search difficult!) so the answer the your question is, use the nsimsgfolder method "addkeywordstomessages" (and now i remember that i knew that!). if you want examples, scan mxr for addkeywordstomessages. you'll find that the only decent ex...
MediaError.code - Web APIs
Web › API › MediaError › code
the read-only property mediaerror.code returns a numeric value which represents the kind of error that occurred on a media element. to get a text string with specific diagnostic information, see mediaerror.message. syntax var myerror = mediaerror.code; value a numeric value indicating the general type of error which occurred. the possible values are described below, in media error code constants. media error code constants name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. ...
... media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. ...
... media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting in an error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. example this example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video resource to present in the element. the error handler sim...
... (such as a mediastream) has been found to be unsuitable. example this example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video resource to present in the element. the error handler simply outputs a message var obj = document.createelement('video'); obj.onerror = function() {console.log("error with media: " + obj.error.code);} obj.src="https://example.com/blahblah.mp4"; specifications specification status comment html living standardthe definition of 'mediaerror.code' in that specification. living standard initial definition ...
RTCRtpCodecParameters - Web APIs
the rtcrtpcodecparameters dictionary, part of the webrtc api, is used to describe the configuration parameters for a single media codec. in addition to being the type of the rtcrtpparameters.codecs property, it's used when calling rtcrtptransceiver.setcodecpreferences() to configure a transceiver's codecs before beginning the offer/answer process to establish a webrtc peer connection. most of the fields in this property take values which are defined and maintained by the internet assigned numbers authority (iana). references to relevant iana documents are provided in the see also section at the end of this article. properties payloadtype optional the rtp payload type used to identify this codec. ...
...nswer process to establish a webrtc peer connection. most of the fields in this property take values which are defined and maintained by the internet assigned numbers authority (iana). references to relevant iana documents are provided in the see also section at the end of this article. properties payloadtype optional the rtp payload type used to identify this codec. ...
...evant iana documents are provided in the see also section at the end of this article. properties payloadtype optional the rtp payload type used to identify this codec. mimetype optional the codec's mime media type and subtype specified as a domstring of the form "type/subtype". iana maintains a registry of valid mime types. clockrate optional an unsigned long integer value specifying the codec's clock rate in hertz (hz). the clock rate is the rate at which the codec's rtp timestamp advances. most codecs have specific values or ranges of values they permit; see the iana payload format media type registry for details. ...
...lid mime types. clockrate optional an unsigned long integer value specifying the codec's clock rate in hertz (hz). the clock rate is the rate at which the codec's rtp timestamp advances. most codecs have specific values or ranges of values they permit; see the iana payload format media type registry for details. channels optional an unsigned short integer indicating the number of channels the codec should support. for example, for audio codecs, a value of 1 specifies monaural sound while 2 indicates stereo. sdpfmtpline optional a domstring containing the format-specific parameters field from the "a=fmtp" line in the codec's sdp, if one is present; see section 5.8 of the ietf specification for jsep. note: on an rtcrtpreceiver, the format-specific parameters come from the sdp sent by the ...
decodeURI() - JavaScript
the decodeuri() function decodes a uniform resource identifier (uri) previously created by encodeuri() or by a similar routine. the source for this interactive example is stored in a github repository. if 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 decodeuri(encodeduri) parameters encodeduri a complete, encoded uniform resource identifier. return value a new string representing the unencoded version of the given encoded uniform resource identifier (uri). exceptions throws an urierror ("malformed uri sequence") exception when encodeduri contains invalid character sequences. ...
...ntax decodeuri(encodeduri) parameters encodeduri a complete, encoded uniform resource identifier. return value a new string representing the unencoded version of the given encoded uniform resource identifier (uri). exceptions throws an urierror ("malformed uri sequence") exception when encodeduri contains invalid character sequences. description replaces each escape sequence in the encoded uri with the character that it represents, but does not decode escape sequences that could not have been introduced by encodeuri. the character “#” is not decoded from escape sequences. ...
...s throws an urierror ("malformed uri sequence") exception when encodeduri contains invalid character sequences. description replaces each escape sequence in the encoded uri with the character that it represents, but does not decode escape sequences that could not have been introduced by encodeuri. the character “#” is not decoded from escape sequences. ...
... that it represents, but does not decode escape sequences that could not have been introduced by encodeuri. the character “#” is not decoded from escape sequences. examples decoding a cyrillic url decodeuri('https://developer.mozilla.org/ru/docs/javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "https://developer.mozilla.org/ru/docs/javascript_шеллы" catching errors try { var a = decodeuri('%e0%a4%a'); } catch(e) { console.error(e); } // urierror: malformed uri sequence specifications specification ecmascript (ecma-262)the definition of 'decodeuri' in that specification. ...
Static Analysis for Windows Code under Linux - Archive of obsolete content
we highly recommend you to read the cross compiling manual and the dehydra build manual before you start the following reading. build gcc corss-compiler with plugin support by default gcc does not support plugins. dehydra requires patching gcc such that it can load plugins as shared libraries: # prepare a directory mkdir $home/dehydra cd $home/dehydra #obtain gcc 4.3 sources wget ftp://mirrors.kernel.org/gnu/gcc/gcc...-4.3.0.tar.bz2 tar jxvf gcc-4.3.0.tar.bz2 # get the patches which enable plugins cd gcc-4.3.0/ # create an hg repository. ...
...ect shared library. so, we should make a linux native compiler with plugin support to make treehydra! this sound crazy, but it may be the only right way to do this. just follow this and this to compile both dehydra and treehydra shared libraries. and these libraries can be used directly with our cross compiler. ...
...dra! ...
Using the DOM File API in chrome code - Extensions
if you want to use the dom file api in chrome code, you can do so without restriction. in fact, you get one bonus feature: you can create file objects specifying the path of the file on the user's computer. this only works from privileged code, so web content can't do it. this protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. if you pass a path to the file constructor from unprivileged code (such as web content), an exception will be thrown. scope availability in the jsm scope file is available without needing to do anything special. ...
...llowing web content free access to the contents of their disks. if you pass a path to the file constructor from unprivileged code (such as web content), an exception will be thrown. scope availability in the jsm scope file is available without needing to do anything special. in bootstrap scope, this must be imported in like so: cu.importglobalproperties( [ "file" ] ) accessing a file by hard-coded pathname to reference a file by its path, you can simply use a string literal: var file = file.createfromfilename("path/to/some/file"); cross platform note: however using hard-coded paths raises cross platform issues since it uses a platform-dependent path separator (here "/"). in the xul/mozilla platform there isn't sadly an equivalent to java file.pathseparator (the system-dependent path-s...
... ...
Measuring performance using the PerfMeasurement.jsm code module
the first thing you need to do is to import the module into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") you can then create a perfmeasurement object. you give the constructor a bit-mask of events you're interested in; see note: at present, perfmeasurement.jsm is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. ...
... perfmeasurement.cache_references | perfmeasurement.cache_misses); this creates a new perfmeasurement object, configured to record the specified event types. it doesn't, however, start to record data. ...
...tty fast (but not fast enough), so we run it several thousand times: for (let i = 0; i < 10000; i++) { set_up_some_state(); monitor.start(); code_to_be_benchmarked(); monitor.stop(); clean_up_afterward(); } we call the perfmeasurement object's start() method when we want to start recording, and stop() when we want to stop recording. this lets us record information only for the specific code section we want to measure. since we enable monitoring immediately before calling code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured. the monitor object automatically accumulates counts over start/stop cycles (that is, it doesn't automatically zero the counters each time you start recording). when you're done...
NSS Sample Code sample6
the symmetric keys can then be used * without ever exposing them in the clear. * * to encrypt, you need the id of the key to use. * to decrypt, you need the ciphertext and the id of the key that was used * to encrypt * * before running this example, create the nss database * certutil -n -d . * (enter "test" when prompted for password) */ #include "nss.h" #include "pk11pub.h" /* the key id can be any sequence of bytes. this example happens to use an * integer */ void genkey(int id); /* this callback is responsible for returning the password to the nss * key database. ...
...e running this example, create the nss database * certutil -n -d . * (enter "test" when prompted for password) */ #include "nss.h" #include "pk11pub.h" /* the key id can be any sequence of bytes. this example happens to use an * integer */ void genkey(int id); /* this callback is responsible for returning the password to the nss * key database. for example purposes, this function hardcodes the password. * in a real app, this function should obtain the password using secure means * such as prompting an operator, or retrieving it over a secure communication * channel */ char *passwdcb(pk11slotinfo *info, prbool retry, void *arg); int main(int argc, char **argv) { secstatus rv; /* initialize nss */ pk11_setpasswordfunc(passwdcb); /* the nss db must be initialized read...
...* already exists */ genkey(1); } void genkey(int id) { pk11slotinfo* slot = null; pk11symkey* key = null; secitem keyiditem; int keyid[1]; ck_mechanism_type ciphermech; /* using ckm_aes_cbc_pad mechanism for example */ ciphermech = ckm_aes_cbc_pad; slot = pk11_getinternalkeyslot(); /* slot = pk11_getbestslot(ciphermech, null); didn't work. * error code: token is read-only. ?? */ if (slot == null) { fprintf(stderr, "unable to find security device (err %d)\n", pr_geterror()); return; } keyid[0] = id; keyiditem.type = sibuffer; keyiditem.data = (void *)keyid; keyiditem.len = sizeof(keyid[0]); /* note: keysize must be 0 for fixed key-length algorithms like des. * since we're using aes in this exampl...
JSPrincipalsTranscoder
jsprincipalstranscoder is the type of a security callback that can be configured using js_setprincipalstranscoderjsapi 1.8 and earlier or js_setruntimesecuritycallbacksadded in spidermonkey 1.8.1. callback syntax typedef jsbool (*jsprincipalstranscoder)(jsxdrstate *xdr, jsprincipals **principalsp); name type description xdr jsxdrstate * the xdr reader/writer. principalsp jsprincipals ** if xdr->mode == jsxdr_decode, this is an out parameter: on success, *principalsp receives the deserialized principals. otherwise xdr->mode == jsxdr_encode, and *principalsp points to the jsprincipals object to be serialized. description the javascript engine uses this callback to serialize and deserialize p...
...d principals. otherwise xdr->mode == jsxdr_encode, and *principalsp points to the jsprincipals object to be serialized. description the javascript engine uses this callback to serialize and deserialize principals. each script function is associated with principals, which poses a problem for xdr. the application provides the jsprincipals objects, so it must also provide a jsprincipalstranscoder if it intends to serialize or deserialize principals. the callback xdr-encodes or -decodes a principals instance, based on whether xdr->mode is jsxdr_encode, in which case *principalsp should be encoded; or jsxdr_decode, in which case implementations must return a held (via jsprincipals_hold), non-null *principalsp out parameter. return js_true on success, js_false on any error, which the imple...
...ack xdr-encodes or -decodes a principals instance, based on whether xdr->mode is jsxdr_encode, in which case *principalsp should be encoded; or jsxdr_decode, in which case implementations must return a held (via jsprincipals_hold), non-null *principalsp out parameter. return js_true on success, js_false on any error, which the implementation must have reported. ...
Components.returnCode
components.returncode is a property which can hold an xpcom return code additionally to the value returned by the return statement. note that components.returncode is currently non-functional due to bug 287107. this problem was introduced in mozilla 1.4. usage components.returncode is a property that can be used to indicate to an xpcom caller of the javascript method that the method is returning a specific nsresult code. generally, xpconnect does a fine job of making it unnecessary for javascript code to worry about nsresult codes. by default the successful completion of the javascript method will cause xpconnect to return a result code of ns_ok to the caller. if the javascript code needs to signal failure then that is done by throwing an exception. however, there are a very few xpcom i...
...erally, xpconnect does a fine job of making it unnecessary for javascript code to worry about nsresult codes. by default the successful completion of the javascript method will cause xpconnect to return a result code of ns_ok to the caller. if the javascript code needs to signal failure then that is done by throwing an exception. however, there are a very few xpcom interfaces that specify success code return values. components.returncode exists in order to make it possible to implement these rare interfaces in javascript. ...
...ode of ns_ok to the caller. if the javascript code needs to signal failure then that is done by throwing an exception. however, there are a very few xpcom interfaces that specify success code return values. components.returncode exists in order to make it possible to implement these rare interfaces in javascript. ...
Testing Mozilla code
asan nightly projectthe asan nightly project involves building a firefox nightly browser with the popular addresssanitizer tool and enhancing it with remote crash reporting capabilities for any errors detected.clang static analysisthis document is split in two parts. ...
...r that detects use-after-free and out-of-bound bugs in c/c++ programs. it uses a compile-time instrumentation to check all reads and writes during the execution. in addition, the runtime part replaces the malloc and free functions to check dynamically allocated memory. more information on how asan works can be found on the address sanitizer wiki. fuzzing interfacethe fuzzing interface is glue code living in mozilla-central in order to make it easier for developers and security researchers to test c/c++ code with either libfuzzer or afl-fuzz.measuring code coverage on firefoxcode coverage essentially is about measuring how often certain lines are hit, branches taken or conditions met in a program, given some test that you run on it. there are different types of coverage metrics (see also th...
...this type of coverage is only concerned with hit counts for lines and branches.the valgrind test jobthe valgrind test job builds the browser and runs it under valgrind, which can detect various common memory-related errors. ...
Step through code - Firefox Developer Tools
the thinking here is that if you've got your devtools open in a separate window, as many people do, it can be easier to have the buttons available righ...
...from a function, returning execution to the caller split console when paused, you can press the esc key to open and close the split console to gain more insight into errors and variables: pause on breakpoints overlay since firefox 70, when your code is paused on a breakpoint an overlay appears on the viewport of the tab you are debugging. this lets you know what kind of breakpoint the code is paused on (breakpoint, event breakpoint, etc.), and also provides a step button and a play button. the thinking here is that if you've got your devtools open in a separate window, as many people do, it can be easier to have the buttons available right there to move the code forward while you are looking at the result. if you want to turn this feature off, since firefox 71 you can do so by goi...
...right there to move the code forward while you are looking at the result. if you want to turn this feature off, since firefox 71 you can do so by going to about:config in a new tab, setting the devtools.debugger.features.overlay pref to false, and restarting the browser. inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
BasicCardResponse.cardSecurityCode - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow. request.show().then(function(instrumentresponse) { // do something with the response from the ui. console.log(instrumentresponse.details); }) .catch(function(err) { // do something with the error from request.show(). ...
...s successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr. dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'cardsecuritycode' in that specification. working draft initial definition. browser compatibility the compatibili...
... browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
KeyboardEvent.keyCode - Web APIs
the deprecated keyboardevent.keycode read-only property represents a system and implementation dependent numerical code identifying the unmodified value of the pressed key. this is usually the decimal ascii (rfc 20) or windows 1252 code corresponding to the key. if the key can't be identified, this value is 0. you should avoid using this if possible; it's been deprecated for some time. instead, you should use keyboardevent.code, if it's implemented. unfortunately, some browsers still don't have it, so you'll have to be careful to make sure you use one which is supported on all target browsers. web developers shouldn't use the keycode attribute for printable characters when handling keydown and keyup events. ...
...when implementing a shortcut key handler, the keypress event is usually better (at least when gecko is the runtime in use). see gecko keypress event for details. ...
...ast when gecko is the runtime in use). see gecko keypress event for details. example window.addeventlistener("keydown", function (event) { if (event.defaultprevented) { return; // should do nothing if the default action has been cancelled } var handled = false; if (event.key !== undefined) { // handle the event with keyboardevent.key and set handled true. } else if (event.keycode !== undefined) { // handle the event with keyboardevent.keycode and set handled true. } if (handled) { // suppress "double action" if event handled event.preventdefault(); } }, true); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'keyboardevent.keycode' in that specification. ...
RTCRtpCodecCapability - Web APIs
the webrtc api's rtcrtpcodeccapability dictionary provides information describing the capabilities of a single media codec. properties channels optional an unsigned integer value indicating the maximum number of channels supported by the codec; for example, a codec that supports only mono sound would have a value of 1; stereo codecs would have a 2, etc. clockrate an unsigned long integer specifying the codec's clock rate in hertz (hz). the iana maintains a list of codecs and their parameters, including their clock rates. mimetype a domstring indicating the codec's mime media type and subtype. see codecs used by webrtc for details about potential codecs that might be referenced here. sdpfmtpline optional a domstring giving the format specific parameters field from the a=fmtp line in...
...rtz (hz). the iana maintains a list of codecs and their parameters, including their clock rates. mimetype a domstring indicating the codec's mime media type and subtype. see codecs used by webrtc for details about potential codecs that might be referenced here. sdpfmtpline optional a domstring giving the format specific parameters field from the a=fmtp line in the sdp which corresponds to the codec, if such a line exists. if there is no parameters field, this property is left out. description rtcrtpcodeccapabilities describes the basic parameters for a single codec supported by the user's device. ...
... sdpfmtpline optional a domstring giving the format specific parameters field from the a=fmtp line in the sdp which corresponds to the codec, if such a line exists. if there is no parameters field, this property is left out. description rtcrtpcodeccapabilities describes the basic parameters for a single codec supported by the user's device. an array of objects of this type is returned in the codecs property of the rtcrtpcapabilities object returned in response to a call to either of the static functions rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities(). examples tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpcodeccapability' in that specification. candidate recomme...
unicode - SVG: Scalable Vector Graphics
Web › SVG › Attribute › unicode
the unicode attribute specifies one or more unicode characters indicating the sequence of unicode characters which corresponds to a glyph. if a character is provided, then this glyph corresponds to the given unicode character. if multiple characters are provided, then this glyph corresponds to the given sequence of unicode characters. one use of a sequence of characters is ligatures. for example, if unicode="ffl", then the given glyph will be used to render the sequence of characters "f", "f", and "l". it is often useful to refer to characters using xml character references expressed in hexadecimal notation or decimal notation. ...
...rovided, then this glyph corresponds to the given sequence of unicode characters. one use of a sequence of characters is ligatures. for example, if unicode="ffl", then the given glyph will be used to render the sequence of characters "f", "f", and "l". it is often useful to refer to characters using xml character references expressed in hexadecimal notation or decimal notation. for example, unicode="ffl" could be expressed as xml character references in hexadecimal notation as unicode="&#x66;&#x66;&#x6c;" or in decimal notation as unicode="&#102;&#102;&#108;". the unicode attribute contributes to the process for deciding which glyph(s) are used to represent which character(s). if the attribute is not provided for a given <glyph>, then the only way to use this glyph is via an <altglyph> r...
...for deciding which glyph(s) are used to represent which character(s). if the attribute is not provided for a given <glyph>, then the only way to use this glyph is via an <altglyph> reference. only one element is using this attribute: <glyph> context notes value <string> default value none animatable no <string> this value specifies one or more unicode characters corresponding to a glyph. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'unicode' in that specification. recommendation initial definition ...
Debug.setNonUserCodeExceptions - Archive of obsolete content
the debug.setnonusercodeexceptions property determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled. exceptions can be classified as thrown, user-unhandled or unhandled. syntax debug.setnonusercodeexceptions [= bool]; remarks if this property is set to true within a given scope, the debugger can then choose whether to take some specified action on exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled exceptions. setting this property to false is the same as never having set the property. for more information on debugging, see the active script debugging overview. example the following code shows how to set this property. ...
... to take some specified action on exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled exceptions. setting this property to false is the same as never having set the property. for more information on debugging, see the active script debugging overview. example the following code shows how to set this property. (function () { debug.setnonusercodeexceptions = true; try{ var x = null; x.y(); } catch (e) { // catch the exception. } })(); requirements supported in the following document modes: internet explorer 10 standards and internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). not supported in the following document modes: quirks, internet explorer 6 standards, i...
Code splitting - MDN Web Docs Glossary: Definitions of Web-related terms
code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel. as an application grows in complexity or is simply maintained, css and javascripts files or bundles grow in byte size, especially as the number and size of included third-party libraries increases. to prevent the requirement of downloading ginormous files, scripts can be split into multiple smaller files. then features required at page load can be downloaded immediately with additional scripts being lazy loaded after the page or application is interactive, thus improving performance. while the total amount of code is the same (and perhaps even a few bytes larger), the amount of code needed during initial load can be reduced. ...
...ading ginormous files, scripts can be split into multiple smaller files. then features required at page load can be downloaded immediately with additional scripts being lazy loaded after the page or application is interactive, thus improving performance. while the total amount of code is the same (and perhaps even a few bytes larger), the amount of code needed during initial load can be reduced. code splitting is a feature supported by bundlers like webpack and browserify which can create multiple bundles that can be dynamically loaded at runtime. see also bundling lazy loading http/2 tree shaking ...
privileged code - MDN Web Docs Glossary: Definitions of Web-related terms
non-privileged - javascript on web-page. ...
... non-privileged - javascript on web-page. ...
NSS Sample Code Sample_2_Initialization of NSS
nss sample code 2: initializing nss this example program demonstrates how to initialize the nss database. this program illustrates password handling. ...
... nss sample code 2: initializing nss this example program demonstrates how to initialize the nss database. this program illustrates password handling. ...
NSS Sample Code sample2
* 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. ...
... ciphermech; pk11slotinfo* slot = null; pk11symkey* symkey = null; secitem* secparam = null; pk11context* enccontext = null; secitem keyitem, ivitem; secstatus rv, rv1, rv2; unsigned char data[1024], buf1[1024], buf2[1024]; int i, result_len, tmp1_outlen, tmp2_outlen; /* initialize nss * if your application code has already initialized nss, you can skip it * here. * this code uses the simplest of the init functions, which does not * require a nss database to exist */ rv = nss_nodb_init("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_geterror()); goto out; } /* choose mechanism: ckm_des_cbc_pad, ckm_des3_ecb, ckm_des3_cbc.
NSS Sample Code sample3
sample code 3: hashing, mac /* * demonstration program for hashing and macs */ #include <iostream.h> #include "pk11pub.h" #include "nss.h" static void printdigest(unsigned char *digest, unsigned int len) { int i; cout << "length: " << len << endl; for(i = 0;i < len;i++) printf("%02x ", digest[i]); cout << endl; } /* * main */ int main(int argc, const char *argv[]) { int status = 0; pk11slotinfo *slot = 0; pk11symkey *key = 0; pk11context *context = 0; unsigned char data[80]; unsigned char digest[20]; /*is there a way to tell how large the output is?*/ unsigned int len; secstatus s; /* initialize nss * if your application code has already initialized nss, you can skip it * here. ...
...n */ int main(int argc, const char *argv[]) { int status = 0; pk11slotinfo *slot = 0; pk11symkey *key = 0; pk11context *context = 0; unsigned char data[80]; unsigned char digest[20]; /*is there a way to tell how large the output is?*/ unsigned int len; secstatus s; /* initialize nss * if your application code has already initialized nss, you can skip it * here. ...
NSS Sample Code sample4
the db password should be "test" and the cert * nickname should be "testca" * here is one way of doing it: * # create ca cert db, if -f not provided, prompts for passwd * $ certutil -n -d . * # create ca cert, self-signed, generates key-pair, prompts for key * # type, cert type etc * # answers for prompts: 5,9,n,y,-1,n,5,6,7,9,n * $ certutil -s -s "cn=test ca, o=bogus inc, l=mtn view, st=ca, c=us" \ * -n testca -t ctu,ctu,ctu -v 60 -x -d . ...
...any ways to setup a public/private key to use - this * example shows one of them. * * this example does not do any padding. it simply encrypts/decrypts a block * of length equal to modulus length of the public/private key. */ #include "nss.h" #include "pk11pub.h" /* this callback is responsible for returning the password to the nss * key database. for example purposes, this function hardcodes the password. * in a real app, this function should obtain the password using secure means * such as prompting an operator, or retrieving it over a secure communication * channel */ char *passwdcb(pk11slotinfo *info, prbool retry, void *arg); int main(int argc, char **argv) { secstatus rv; certcertificate *cert = null; seckeypublickey *pubkey = null; seckeyprivatekey ...
JS_SetPrincipalsTranscoder
set the runtime-wide principals transcoder callback. this function is deprecated. in spidermonkey 1.8.1 or later, use js_setruntimesecuritycallbacks instead. syntax jsprincipalstranscoder js_setprincipalstranscoder(jsruntime *rt, jsprincipalstranscoder px); name type description rt jsruntime * the runtime to configure. px jsprincipalstranscoder the new principals transcoder. description js_setprincipalstranscoder sets a runtime-wide callback which the javascript engine uses to serialize and deserialize principals. this callback is described at jsprincipalstranscoder. js_setprincipalstranscoder returns the previous principals transcoder. ...
...me * the runtime to configure. px jsprincipalstranscoder the new principals transcoder. description js_setprincipalstranscoder sets a runtime-wide callback which the javascript engine uses to serialize and deserialize principals. this callback is described at jsprincipalstranscoder. js_setprincipalstranscoder returns the previous principals transcoder. ...
Using Mozilla code in other projects
mozilla provides a development platform for desktop applications, called xul, atop which you can build applications. various components of the platform, such as the spidermonkey javascript engine, can be used in your own projects without the rest of the platform. there are also modules that aren't used in firefox but are available for use by other applications; an example of this is rhino, the javascript engine written in java. you can embed gecko, the layout engine used by firefox to process web pages, as a browser within your own application. ...
...ilding xul applications the joy of xul an introduction to xul; a must read for new developers. xul reference the complete reference to xul. xulrunner a mozilla runtime package that can be used to bootstrap xul and xpcom applications with ease. mozilla toolkit information about the mozilla toolkit api. signing mozilla apps for mac os x how to code-sign applications based on mozilla code for mac os x's application security model. using mozilla components spidermonkey spidermonkey is the javascript runtime engine used by mozilla projects. nspr the netscape portable runtime provides a platform-neutral api for system level and libc-type functions. necko the mozilla networking library provide...
AddressErrors.languageCode - Web APIs
an object based on addresserrors includes a languagecode property when the address's languagecode property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. syntax var languageerror = addresserrors.languagecode; value if the value specified in the paymentaddress object's languagecode property could not be validated, this property contains a domstring offering a human-readable explanation of the validation error and offers suggestions for correcting it. this validation might be as simple as ensuring the text of the string is compliant with the syntax defined in bcp-47, or as detailed as actually verifying that the specified string matches a value from a database. ...
...perty could not be validated, this property contains a domstring offering a human-readable explanation of the validation error and offers suggestions for correcting it. this validation might be as simple as ensuring the text of the string is compliant with the syntax defined in bcp-47, or as detailed as actually verifying that the specified string matches a value from a database. if the languagecode value was validated successfully, this property is not included in the addresserrors object. specifications specification status comment payment request apithe definition of 'addresserrors.languagecode' in that specification. candidate recommendation initial definition. ...
AddressErrors.regionCode - Web APIs
an object based on addresserrors includes a regioncode property when the address's regioncode property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. syntax var regioncodeerror = addresserrors.regioncode; value if the value specified in the paymentaddress object's regioncode property could not be validated, this property contains a domstring offering a human-readable explanation of the validation error and offers suggestions for correcting it. if the regioncode value was validated successfully, this property is not included in the addresserrors object. usage notes the region code is derived from the iso 3166-2 country subdivision name standard. specifications specification status comment paymen...
... the validation error and offers suggestions for correcting it. if the regioncode value was validated successfully, this property is not included in the addresserrors object. usage notes the region code is derived from the iso 3166-2 country subdivision name standard. specifications specification status comment payment request apithe definition of 'addresserrors.regioncode' in that specification. candidate recommendation initial definition. ...
GeolocationPositionError.code - Web APIs
the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because one or several internal sources of position returned an internal error. ...
... recommendation initial definition ...
PaymentAddress.postalCode - Web APIs
the postalcode read-only property of the paymentaddress interface returns a string containing a code used by a jurisdiction for mail routing, for example, the zip code in the united states or the postal index number (pin code) in india. syntax var paymentpostalcode = paymentaddress.postalcode; value a domstring which contains the postal code portion of the address. a postal code is a string (either numeric or alphanumeric) which is used by a postal service to optimize mail routing and delivery. various countries use different terms for this. in most of the world, it's known as the "post code" or "postal code." in the united states, the zip code is used. india uses pin codes. specifications specification status comment payment request apithe definition of 'paymen...
...lphanumeric) which is used by a postal service to optimize mail routing and delivery. various countries use different terms for this. in most of the world, it's known as the "post code" or "postal code." in the united states, the zip code is used. india uses pin codes. specifications specification status comment payment request apithe definition of 'paymentaddress.postalcode' in that specification. candidate recommendation initial definition. ...
PaymentAddress.regionCode - Web APIs
the regioncode read-only attribute of the paymentaddress interface returns a one-, two-, or three-alphanumeric code (domstring) representing the region of the address (e.g., "ca" for california, or "11" for lisbon, portugal). the code is derived from the iso 3166-2 standard, which defines codes for identifying the subdivisions (e.g., states, provinces, autonomous regions, etc.) of all countries in the world. if the browser can't determine the region code, or the country doesn't use regions for postal addresses, it returns an empty string. syntax var regioncode = paymentaddress.regioncode; value a domstring indicating the one to three character alphanumeric code representing the region portion of the address. this should correspond to region, but should be the iso 3166--2 standard's re...
...world. if the browser can't determine the region code, or the country doesn't use regions for postal addresses, it returns an empty string. syntax var regioncode = paymentaddress.regioncode; value a domstring indicating the one to three character alphanumeric code representing the region portion of the address. this should correspond to region, but should be the iso 3166--2 standard's region code. the string is empty if the region code couldn't be determined, isn't needed for the address's country, or was not provided. ...
TextDecoder.prototype.encoding - Web APIs
it can be one of the following values: the recommended encoding for the web: 'utf-8'. the legacy single-byte encodings: 'ibm866', 'iso-8859-2', 'iso-8859-3', 'iso-8859-4', 'iso-8859-5', 'iso-8859-6', 'iso-8859-7', 'iso-8859-8'', 'iso-8859-8i', 'iso-8859-10', 'iso-8859-13', 'iso-8859-14', 'iso-8859-15', 'iso-8859-16', 'koi8-r', 'koi8-u', 'macintosh', 'windows-874', 'windows-1250', 'windows-1251', 'windows-1252', 'windows-1253', 'windows-1254', 'windows-1255', 'windows-1256', 'windows-1257', 'windows-1258', or 'x-mac-cyrillic'. the legacy multi-byte chinese (simplified) encodings: 'gbk', 'gb18030', and 'hz-gb-2312'. ...
...18030', and 'hz-gb-2312'. the legacy multi-byte chinese (traditional) encoding: 'big5'. the legacy multi-byte japanese encodings: 'euc-jp', 'iso-2022-jp', and 'shift-jis'. the legacy multi-byte korean encodings: 'euc-kr', and 'iso-2022-kr'. the legacy miscelleanous encodings: 'utf-16be', 'utf-16le', and 'x-user-defined'. a special encoding, 'replacement', which only emits an error and an eof code point. it is used to prevent attacks that mismatch encodings between the client and server. it can happen with iso-2022-cn and iso-2022-cn-ext. syntax var b = decoder.decoding; specifications specification status comment encodingthe definition of 'textdecoder.encoding' in that specification. living standard initial definition. ...
TextEncoder() - Web APIs
the textencoder() constructor returns a newly created utf-8 textencoder object. syntax encoder = new textencoder(); parameters textencoder() takes no parameters since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53, an encoding type label was accepted as a paramer to the textencoder object, since then both browers have removed support for any encoder type other than utf-8, to match the spec. any type label passed into the textencoder constructor will now be ignored and a utf-8 textencoder will be created. exceptions textencoder() throws no exceptions since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53 an exception would be thrown for an unknown encoding type. specifications specification status comment encodi...
... label passed into the textencoder constructor will now be ignored and a utf-8 textencoder will be created. exceptions textencoder() throws no exceptions since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53 an exception would be thrown for an unknown encoding type. specifications specification status comment encodingthe definition of 'textencoder()' in that specification. living standard initial definition ...
Textures from code - Web APIs
« previousnext » this webgl example provides a simple demonstration of procedural texturing with fragment shaders. that is, using code to generate textures for use in shading webgl objects. drawing textures with code texturing a point sprite with calculations done per-pixel in the fragment shader. <p>texture from code. simple demonstration of procedural texturing</p> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } <script type="x-shader/x-vertex" id="vertex-shader"> #version 100 precis...
... « previousnext » ...
XPathException.code - Web APIs
specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexception' in that specification. ...
... specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexception' in that specification. ...
RegExp.prototype.unicode - JavaScript
the unicode property indicates whether or not the "u" flag is used with a regular expression. unicode is a read-only property of an individual regular expression instance. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of regexp.prototype.unicode writable no enumerable no configurable yes description the value of unicode is a boolean and true if the "u" flag was used; otherwise false. the "u" flag enables various unicode-related features. ...
...es and send us a pull request. property attributes of regexp.prototype.unicode writable no enumerable no configurable yes description the value of unicode is a boolean and true if the "u" flag was used; otherwise false. the "u" flag enables various unicode-related features. with the "u" flag, any unicode code point escapes will be interpreted as such, for example. you cannot change this property directly. it is read-only. examples using the unicode property var regex = new regexp('\u{61}', 'u'); console.log(regex.unicode); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.unicode' in that specification. ...
unicode-bidi - SVG: Scalable Vector Graphics
the unicode-bidi attribute specifies how the accumulation of the background image is managed. note: as a presentation attribute, unicode-bidi can be used as a css property. see the css unicode-bidi property for more information. as a presentation attribute, it can be applied to any element but it has effect only on the following eleven elements: <altglyph>, <textpath>, <text>, <tref>, and <tspan> context notes value normal | embed | isolate | bidi-override | isolate-override | plaintext default value normal animatable no for a description of the values, please refer to the css unicode-bidi property. ...
...<tref>, and <tspan> context notes value normal | embed | isolate | bidi-override | isolate-override | plaintext default value normal animatable no for a description of the values, please refer to the css unicode-bidi property. specifications specification status comment css writing modes module level 3the definition of 'unicode-bidi' in that specification. proposed recommendation svg 2 only refers to css writing modes. introduced isolate, isolate-override, and plaintext keywords. scalable vector graphics (svg) 1.1 (second edition)the definition of 'unicode-bidi' in that specification. recommendation initial definition ...
Finding the code to modify - Archive of obsolete content
again, the dom inspector makes this easy. the "document - dom nodes" pane on the left-hand side of the inspector window displays a tree representation of the browser window's xul file. when you select a node in the tree, a red border flashes for several seconds around the visual representation of that node in the browser window. scroll down the tree to the statusbar node and select it. notice the flashing red border around the horizontal status bar at the bottom of the browser window. ...
Return Codes - Archive of obsolete content
reboot_needed 999 the files were installed, but one or more components were in use. restart the computer and the application to complete the installation process. on windows nt, you may only need to restart the application as long as you did not replace operating system files. ...
keycode - Archive of obsolete content
« xul reference home keycode type: string key code for keys that do not have displayable characters, such as the enter key or function keys, use this attribute instead of the key attribute. valid keys are listed at keyboard shortcuts. ...
Pseudocode - MDN Web Docs Glossary: Definitions of Web-related terms
pseudocode refers to code-like syntax that is generally used to indicate to humans how some code syntax works, or illustrate the design of an item of code architecture. it won't work if you try to run it as code. learn more general knowledge pseudocode on wikipedia. ...
Code Samples
simply replace yourextensionid with your add-on's id. ...
Using workers in JavaScript code modules
te since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. note: as of gecko 8.0, the nsiworkerfactory interface has been removed starting in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), you can use workers in javascript code modules (jsms). this lets you run code in a separate thread from your jsm. to create a chromeworker for this purpose, you need to use the nsiworkerfactory interface: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); var worker = workerfactory.newchromeworker('script_url.js'); th...
L10n testing with xcode
setting up your l10n testing environment once you have your l10n testing environment set up in xcode, testing your firefox on ios localization is a breeze. follow the cloning and building instructions for firefox on ios. open the client.xcodeproj file in xcode. select the client project in the left pane and choose editor > import localizations from the toolbar and select your localized xliff file. a window will then appear showing the diff between the imported xliff file and the existing resources in the project folder. click the import button. xcode will import your translated strings into the project by adding them to the project folder and replacing the existing strings. next, you need to configure the ios app simulator to run the app in your locale. choose produc...
PRErrorCode
type for error codes that can be retrieved with pr_geterror. you can also set your own errors using pr_seterror. syntax #include <prerror.h> typedef print32 prerrorcode description the service nspr offers in this area is the ability to associate a thread-specific condition with an error number. the error number namespace is not well managed. nspr assumes error numbers starting at -6000 (decimal) and progressing towards zero. at present less than 100 error codes have been defined. if nspr's error handling is adopted by calling clients, then some sort of partitioning of the namespace will have to be employed. nspr does not attempt to address this issue. for nspr errors, see error codes. ...
NSS Code Coverage
if file was tested, link points to annotated source file (in tcov directory), otherwise to original source file (cvs directory). colors green: 70-100% of blocks tested. yellow: 40-70% of blocks tested. orange: 0-40% of blocks tested. red: file not tested. file is not part of any binary or library used by test suite. numbers in tested files example: 72.69% (165/227/731) 72.69% - ratio of tested blocks and total blocks in file (generated by tcov). 165 - tested blocks in file (generated by tcov). 227 - total blocks in file (generated by tcov). 31 - total lines in file (by wc -l command). ...
NSS Sample Code Sample_1_Hashing
nss sample code 1: hashing a file. this is an example program that demonstrates how to compute the hash of a file and save it to another file. this program illustrates the use of nss message apis. sample code 1 /* nspr headers */ #include <prprf.h> #include <prtypes.h> #include <plgetopt.h> #include <prio.h> /* nss headers */ #include <secoid.h> #include <secmodt.h> #include <sechash.h> typedef struct { const char *hashname; secoidtag oid; } nametagpair; /* the hash algorithms supported */ static const nametagpair hash_names[] = { { "md2", sec_oid_md2 }, { "md5", sec_oid_md5 }, { "sha1", sec_oid_sha1 }, { "sha256", sec_oid_sha256 }, { "sha384", sec_oid_sha384 }, { "sha512", sec_oid_sha512 } }; /* * maps a hash name to a secoidtag. * returns nul...
NSS Sample Code Utilities_1
nss sample code common: utilities this is a library of utilities used by many of the samples. this code shows the following: extract seed from noise file read der encoding from a file extract the password from a text file get the module password print as ascii or hexadecimal sample code #include <prlog.h> #include <termios.h> #include <base64.h> #include <unistd.h> #include <sys/stat.h> #include <prprf.h> #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. */ /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printasascii */ void printasascii(prfiledesc* out, const unsigned char *data, unsigned int len) { ch...
NSS Sample Code
nss sample code the collection of sample code here demonstrates how nss can be used for cryptographic operations, certificate handling, ssl, etc. it also demonstrates some best practices in the application of cryptography. old samples in the process of being replaced. sample code 1: key generation and transport between servers sample code 2: symmetric encryption sample code 3: hashing, mac sample code 4: pki encryption sample code 5: pki encryption with a raw public & private key in der format sample code 6: persistent symmetric keys in nss database these are very old examples in need of replacement. see https://bugzilla.mozilla.org/show_bug.cgi?id=490238 you are welcome to download the new samples via: hg clone https://hg.mozilla.org/projects/nss; cd nss; hg update sam...
Viewing and searching Mozilla source code online
uxp source code can be found at the pale moon repository. ...
Measuring Code Coverage on Firefox
documentation moved in-tree: https://firefox-source-docs.mozilla.org/tools/code-coverage/index.html ...
Using JS in Mozilla code
js language features that are implemented in the mozilla js engine are ordinarily safe to use in mozilla code. however, there are a few exceptions, listed here. js language features proper tail calls are not implemented. js standard library features feature standard can be used in code new proxy(target, handler) es2015 yes, but getprototypeof and setprototypeof handlers are not yet implemented. arraybuffer.transfer() proposed for es2016 no, nightly-only for now sharedarraybuffer, sharedint8array..., atomics proposed for es2016 no, nightly-only for now typedobject proposed for es2016 no, nightly-only for now simd proposed for es2016 no, nightly-only for now ...
AddressErrors.postalCode - Web APIs
an object based on addresserrors includes a postalcode property when the address's postalcode property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. syntax var postcodeerror = addresserrors.postcode; value if the value specified in the paymentaddress object's postalcode property could not be validated, this property contains a domstring offering a human-readable explanation of the validation error and offers suggestions for correcting it. if the postalcode value was validated successfully, this property is not included in the addresserrors object. specifications specification status comment payment request apithe definition of 'addresserrors.postalcode' in that specification. candidate recomm...
AddressErrors.sortingCode - Web APIs
an object based on addresserrors includes a sortingcode property when the address's sortingcode property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. syntax var sortingcodeerror = addresserrors.sortingcode; value if the value specified in the paymentaddress object's sortingcode property could not be validated, this property contains a domstring offering a human-readable explanation of the validation error and offers suggestions for correcting it. if the sortingcode value was validated successfully, this property is not included in the addresserrors object. specifications specification status comment payment request apithe definition of 'addresserrors.sortingcode' in that specification. candi...
FontFace.unicodeRange - Web APIs
the unicoderange property of the fontface interface retrieves or sets the range of unicode codepoints encompassing the font. it is equivalent to the unicode-range descriptor. syntax var unicoderangedescriptor = fontface.unicoderange; fontface.unicoderange = unicoderangedescriptor; value a cssomstring containing a descriptor as it would appear in a style sheet's @font-face rule. specifications specification status comment css font loading module level 3the definition of 'unicoderange' in that specification. working draft initial definition. ...
msExtendedCode - Web APIs
this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. in the event of an error, the media element's error event will be fired. the element's error property will then contain an msextendedcode read-only property with platform-specific error code information. msextendedcode is a read-only proprietary property specific to internet explorer and microsoft edge. value type: long; the platform specific error code. example var video1 = object.getelementbyid("video1"); video1.addeventlistener('error', function () { var error = video1.error.msextendedcode; //... }, false); video.adde...
NavigatorID.appCodeName - Web APIs
the value of the navigatorid.appcodename property is always "mozilla", in any browser. this property is kept only for compatibility purposes. note: do not rely on this property to return a real product name. all browsers return "mozilla" as the value of this property. syntax codename = navigator.appcodename value the string "mozilla". specifications specification status comment html living standardthe definition of 'navigatorid.appcodename' in that specification. living standard initial definition ...
PaymentAddress.languageCode - Web APIs
the languagecode read-only property of the paymentaddress interface returns a string containing the bcp-47 language code for the address. this is used while localizing the displayy of the address, allowing the determination of the field separators and the order of fields when formatting the address. syntax var paymentlanguagecode = paymentaddress.languagecode; value a domstring providing the bcp-47 format language code indicating the language the address was written in, such as "en-us", "pt-br", or "ja-jp". ...
PaymentAddress.sortingCode - Web APIs
the sortingcode read-only property of the paymentaddress interface returns a string containing a postal sorting code such as is used in france. syntax var sortingcode = paymentaddress.sortingcode; value a domstring containing the sorting code portion of the address. specifications specification status comment payment request apithe definition of 'paymentaddress.sortingcode' in that specification. candidate recommendation initial definition. ...
RTCInboundRtpStreamStats.framesDecoded - Web APIs
the framesdecoded property of the rtcinboundrtpstreamstats dictionary indicates the total number of frames which have been decoded successfully for this media source. syntax var framesdecoded = rtcinboundrtpstreamstats.framesdecoded; value an integer value indicating the total number of video frames which have been decoded for this stream so far. this represents the number of frames that would have been displayed assuming no frames were skipped. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.framesdecoded' in that specification. candidate recommendation initial definition. ...
RTCOutboundRtpStreamStats.framesEncoded - Web APIs
the framesencoded property of the rtcoutboundrtpstreamstats dictionary indicates the total number of frames that have been encoded by this rtcrtpsender for this media source. syntax var framesencoded = rtcoutboundrtpstreamstats.framesencoded; value an integer value indicating the total number of video frames that this sender has encoded so far for this stream. note: this property is only valid for video streams. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.framesencoded' in that specification. candidate recommendation initial definition. ...
RTCRtpStreamStats.codecId - Web APIs
the rtcrtpstreamstats dictionary's codecid property is a string which uniquely identifies the object that was inspected to produce the data in the rtccodecstats for the rtp stream. syntax var codecid = rtcrtpstreamstats.codecid; value a domstring which uniquely identifies the object from which the contents of the stream's rtccodecstats are derived. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcrtpstreamstats.codecid' in that specification. candidate recommendation initial definition. ...
SVGImageElement.decode - Web APIs
the decode() method of the svgimageelement interface initiates asynchronous decoding of an image, returning a promise that resolves once the image data is ready for use. syntax var promise = svgimageelement.decode(); parameters none. return value a promise which resolves once the image data is ready to be used, such as by appending it to the dom, replacing an existing image, and so forth. exceptions none. specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation initial definition. html living standardthe definition of 'decode()' in that specification. living standard ...
SecurityPolicyViolationEvent.statusCode - Web APIs
the statuscode read-only property of the securitypolicyviolationevent interface is a number representing the http status code of the document or worker in which the violation occurred. syntax let status = violationeventinstance.statuscode; value a number representing the status code of the document or worker in which the violation occurred. example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.statuscode); }); specifications specification status comment content security policy level 3the definition of 'statuscode' in that specification. working draft initial definition ...
TextEncoder.encoding - Web APIs
the textencoder.encoding read-only property returns a domstring containing the name of the encoding algorithm used by the specific encoder. it can only have the following value utf-8. syntax b = encoder.encoding; specifications specification status comment encodingthe definition of 'textencoder.encoding' in that specification. living standard initial definition. ...
Warning: unreachable code after return statement - JavaScript
the javascript warning "unreachable code after return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after. message warning: unreachable code after return statement (firefox) error type warning what went wrong? unreachable code after a return statement might occur in these situations: when using an expression after a return 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...
unicode-range - SVG: Scalable Vector Graphics
the unicode-range attribute defines the range of iso 10646 characters possibly covered by the glyphs in a font. only one element is using this attribute: <font-face> usage notes value <urange># default value none animatable no <urange># this value is a comma-separated list of iso 10646 characters possibly covered by the glyphs in the font. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'unicode-range' in that specification. recommendation initial definition ...
Index - Web APIs
Web › API › Index
below is a list of all the apis and interfaces (object types) that you may be able to use while developing your web app or site. 2 angle_instanced_arrays api, reference, webgl, webgl extension the angle_instanced_arrays extension is part of the webgl api and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. ...
...dresserrors, error, locality, payment request, payment request api, property, read-only, reference, dependentlocality, payment an object based on addresserrors includes a dependentlocality property when the address's dependentlocality property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. 34 addresserrors.languagecode api, address, addresserrors, deprecated, language, languagecode, locale, payment request, payment request api, property, reference, payment an object based on addresserrors includes a languagecode property when the address's languagecode property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. 35 addresserrors.
...esserrors, payment request, payment request api, phone, phone number, property, read-only, reference, telephone number, téléphone, validation, payment an object based on addresserrors includes a phone property when the address's phone property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. 37 addresserrors.postalcode api, address, addresserrors, payment request, payment request api, post code, postal code, property, read-only, reference, validation, zip, zip code, payment, postalcode an object based on addresserrors includes a postalcode property when the address's postalcode property couldn't be validated. the returned string explains the error and should offer suggestions for how to correct it. ...
...And 178 more matches
Key Values - Web APIs
the tables below list the standard key values in various categories of key, with an explanation of what the key is typically used for. corresponding virtual keycodes for common platforms are included where available. learn how to use these key values in javascript using keyboardevent.key special values | modifier keys | whitespace keys | navigation keys | editing keys | ui keys | device keys | ime and composition keys | function keys | phone keys | multimedia keys | audio control keys | tv control keys | media controller keys | speech recognition keys | document keys | application selector keys | browser control keys | numeric keypad keys special values values of key which have special meanings other than identifying a specific key or character. keyboardevent.key value ...
... | function keys | phone keys | multimedia keys | audio control keys | tv control keys | media controller keys | speech recognition keys | document keys | application selector keys | browser control keys | numeric keypad keys special values values of key which have special meanings other than identifying a specific key or character. keyboardevent.key value description virtual keycode windows mac linux android "unidentified" the user agent wasn't able to map the event's virtual keycode to a specific key value. this can happen due to hardware or software constraints, or because of constraints around the platform on which the user agent is running. varies varies varies varies modifier keys modifiers are special ...
...form on which the user agent is running. varies varies varies varies modifier keys modifiers are special keys which are used to generate special characters or cause special actions when used in combination with other keys. examples include the shift and control keys, and lock keys such as caps lock and numlock. ...
...And 123 more matches
Index - Archive of obsolete content
mary! 9 add-ons add-ons, archive, extensions archived add-ons documentation. 10 add-on sdk add-on sdk, jetpack no summary! 11 builder no summary! 12 guides add-on sdk no summary! 13 content scripts add-on sdk many add-ons need to access and modify the content of web pages. but the main add-on code doesn't get direct access to web content. instead, sdk add-ons need to factor the code that gets access to web content into separate scripts that are called content scripts. this page describes how to develop and implement content scripts. 14 communicating with other scripts no summary! 15 communicating using "port" to enable add-on scripts and content...
...scripts. self provides: 23 contributor's guide no summary! 24 classes and inheritance add-on sdk no summary! 25 content processes add-on sdk no summary! 26 getting started add-on sdk learn how to contribute to the add-on sdk. 27 modules add-ons, extensions a module is a self-contained unit of code, which is usually stored in a file, and has a well defined interface. the use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscript...
...eral ways to emulate private properties using existing language features. this article discusses two common techniques: one using prefixes, the other closures. ...
...And 116 more matches
StringView - Archive of obsolete content
the aims of this library are: to create a c-like interface for strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding methods to the object stringview.prototype to create a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction 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...
...numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction 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. however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats...
...thod to read the bytes from the data buffer. however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats). javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently. the stringview constructor is one level above typed arrays. ...
...And 80 more matches
Index
Mozilla › Tech › XPCOM › Index
# page tags and summary 1 xpcom add-ons, extensions, landing, mozilla, xpcom xpcom is a cross platform component object model, similar to microsoft com. it has multiple language bindings, allowing xpcom components to be used and implemented in javascript, java, and python in addition to c++. 2 accessing the windows registry using xpcom add-ons, code snippets, extensions, needsclassification, windows registry when implementing windows-specific functionality, it is often useful to access the windows registry for information about the environment or other installed programs. to this end, there exist xpcom interfaces to read and write registry data. this article will show you how to use the available interfaces in several mozilla products.
...new nsigenericfactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsifactory is needed. here is the interface, and a description of its use.</t> 10 how to pass an xpcom object to a new window needsexample, needshelp if you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method. 11 how to build a binary xpcom component using visual studio add-ons, extensions, xpcom this is a simple tutorial for building xpcom objects in c++ using visual studio. xpcom is mozilla’s cross platform component object model, similar to microsoft’s com technology. xpcom com...
...e classes indexed by cid. 22 components.interfaces xpcom:language bindings, xpconnect components.interfaces is a read-only object whose properties are interfaces indexed by their names. 23 components.interfacesbyid xpcom:language bindings, xpconnect components.interfacesbyid is a read-only array of classes indexed by iid. 24 components.issuccesscode xpcom, xpcom:language bindings, xpconnect determines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively. 25 components.lastresult xpcom:language bindings, xpconnect no summary! 26 components.manager xpcom:language bindings, xpconnect components.man...
...And 59 more matches
HTTP Index - HTTP
Web › HTTP › Index
used by the server to advertise its support of partial requests. the value of this field indicates the unit that can be used to define a range. 55 access-control-allow-credentials access-control-allow-credentials, cors, http, reference, credentials, header the access-control-allow-credentials response header tells browsers whether to expose the response to frontend javascript code when the request's credentials mode (request.credentials) is include. 56 access-control-allow-headers cors, http, reference, response header, header the access-control-allow-headers response header is used in response to a preflight request which includes the access-control-request-headers to indicate which http headers can be used during the actual request. 57 acc...
...hods allowed when accessing the resource in response to a preflight request. 58 access-control-allow-origin access control, access-control-allow-origin, cors, dealing with cors, http, http header, how to fix cors, reference, security, cross-origin issue, header, origin the access-control-allow-origin response header indicates whether the response can be shared with requesting code from the given origin. 59 access-control-expose-headers cors, http, reference, header the access-control-expose-headers response header indicates which headers can be exposed as part of the response by listing their names. 60 access-control-max-age cors, http, reference, header the access-control-max-age response header indicates how long the results of a...
...plies to. the subpart is delimited by the boundary defined in the content-type header. used on the body itself, content-disposition has no effect. 71 content-encoding http, headers, reference the content-encoding entity header is used to compress the media-type. when present, its value indicates which encodings were applied to the entity-body. it lets the client know how to decode in order to obtain the media-type referenced by the content-type header. 72 content-language http, headers, reference the content-language entity header is used to describe the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. 73 content-length http, headers, reference the cont...
...And 58 more matches
Index
2 creating javascript tests automated testing, build documentation, guide, qa, spidermonkey in which test suite does your new test belong? 3 creating javascript jstest reftests ecmascript, guide, javascript, test in the js/src/tests directory, there are a few important subdirectories. ...
...foss guide, spidermonkey feel free to add your own spidermonkey-based open source projects (and if necessary add categories)! 5 future directions guide, mozilla, spidermonkey this article documents future directions in functionality, design, and coding practices for spidermonkey. it can be read as something like an "ideal future state" for the engine. that means the code as it is today won't match this document, and that's ok. whenever practical, new code and changes should move code closer to the ideal future. and of course, the idea of the future is always evolving in time as things change and we learn more. 6 gc rooting guide spidermonkey no summary! 7 gcintegration developing mozilla, firefox, garbage collection, intermedia...
... 6 gc rooting guide spidermonkey no summary! 7 gcintegration developing mozilla, firefox, garbage collection, intermediate, intro, jsapi, needsupdate, spidermonkey, tools, memory the spidermonkey garbage collector (gc) will be changing a lot in the future. this page is intended to explain the changes that are happening, with a focus on how they will affect gecko code that uses jsapi. at a high level, there are three issues to be aware of: 8 getting spidermonkey source code guide, spidermonkey you can get the spidermonkey source code in gzipped form or directly from the mercurial repository. 9 hacking tips spidermonkey this page list a few tips to help you investigate issues related to spidermonkey. all tips listed her...
...And 57 more matches
Index
abase), and nss will then transparently manage the database files. most of the time certificates and keys are supposed to be stored in the nss database. therefore, after initial import or creation, the programmer usually doesn't deal with their raw bytes. instead, the programmer will use lookup functions, and nss will provide an access handle that will be subsequently used by the application's code. those handles are reference counted. nss will usually create an in-memory (ram) presentation of certificates, once a certificate has been received from the network, read from disk, or looked up from the database, and prepare in-memory data structures that contain the certificate's properties, as well as providing a handle for the programmer to use. once the application is done with a handle, it ...
...free the associated resources. when working with handles to private keys it's usually difficult (and undesired) that an application gets access to the raw key data; therefore it may be difficult to extract such data from nss. the usual minimum requirement is that private keys must be wrapped using a protective layer (such as password-based encryption). the intention is to make it easier to review code for security. the less code that has access to raw secret keys, the less code that must be reviewed. nss has only limited functionality to look up raw keys. the preferred approach is to use certificates, and to look up certificates by properties such as the contained subject name (information that describes the owner of the certificate). for example, while nss supports random calculation (crea...
...ion is passed to the parser, which will analyze the asn.1 data stream accordingly. the templates are usually closely aligned to definitions found in rfc documents. a data block described as der is usually in asn.1 format. you must know which data you are expecting, and use the correct template for parsing, based on the context of your software's interaction. data described as pem is a base64 encoded presentation of der, usually wrapped between human readable begin/end lines. nss prefers the binary presentation, but is often capable to use base64 or ascii presentations, especially when importing data from files. a recent development adds support for loading external pem files that contain private keys, in a software library called nss-pem, which is separately available, but should eventually...
...And 56 more matches
Media container formats (file types) - Web media technologies
the format of audio and video media files is defined in two parts (three if a file has both audio and video in it, of course): the audio and/or video codecs used and the media container format (or file type) used. in this guide, we'll look at the container formats used most commonly on the web, covering basics about their specifications as well as their benefits, limitations, and ideal use cases. webrtc does not use a container at all. instead, it streams the encoded audio and video tracks directly from one peer to another using mediastreamtrack objects to represent each track. see codecs used by webrtc for information about codecs commonly used for making webrtc calls, as well as browser compatibility information around codec support in webrtc. common container formats while there are a v...
...hers support both audio and video. the mime types and extensions for each are listed.the most commonly used containers for media on the web are probably mpeg-4 (mp4), quicktime movie (mov), and the wavefile audio file format (wav). however, you may also encounter mp3, ogg, webm, avi, and other formats. ...
...pported by browsers, however; some combinations of container and codec are sometimes given their own file extensions and mime types as a matter of convenience, or because of their ubiquity. for example, an ogg file with only an opus audio track is sometimes referred to as an opus file, and might even have the extension .opus. but it's still actually just an ogg file. in other cases, a particular codec, stored in a certain container type, is so ubiquitous that the pairing is treated in a unique fashion. a good example of this is the mp3 audio file, which is in fact an mpeg-1 container with a single audio track encoded using mpeg-1 audio layer iii encoding. these files use the audio/mp3 mime type and the .mp3 extension, even though their containers are just mpeg. index of media container forma...
...And 52 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
, dictionary, glossary, index, landing, terminology web technologies contain long lists of jargon and abbreviations that are used in documentation and coding. this glossary provides definitions of words and abbreviations you need to know to successfully understand and build for the web. 2 404 glossary, http errors, infrastructure, navigation a 404 is a standard response code meaning that the server cannot find the requested resource. 3 502 502, bad gateway, glossary, http errors, infrastructure, navigation an http error code meaning "bad gateway". 4 alpn alpn, draft, glossary, needscontent, tls application-layer protocol negotiation (alpn) is a tls extension which indicates what application layer protocol is negotiating the e...
...antics and other metadata to html to cater to users of assistive technology. 7 arpa glossary, infrastructure .arpa (address and routing parameter area) is a top-level domain used for internet infrastructure purposes, especially reverse dns lookup (i.e., find the domain name for a given ip address). 8 ascii glossary, infrastructure ascii (american standard code for information interchange) is one of the most popular coding method used by computers for converting letters, numbers, punctuation and control codes into digital form. since 2007, utf-8 superseded it on the web. 9 atag atag, accessibility, authoring tool accessibility guidelines, glossary atag (authoring tool accessibility guidelines) is a w3c recommendation for building ac...
...iding metadata. 26 bandwidth glossary, infrastructure bandwidth is the measure of how much information can pass through a data connection in a given amount of time. it is usually measured in multiples of bits-per-second (bps), for example megabits-per-second (mbps) or gigabits-per-second (gbps). 27 base64 advanced, base64, javascript, typed arrays, uri, url, unicode problem, atob(), btoa() base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ascii string format by translating it into a radix-64 representation. the term base64 originates from a specific mime content transfer encoding. 28 baseline css, glossary, svg, alignment, typography the baseline is a term used in european and west asian ...
...And 51 more matches
Handling common JavaScript problems - Learn web development
ification), things were often implemented in conflicting, incompatible ways, causing developers many nightmares. such incompatibility problems persisted well into the early 2000s, as old browsers were still being used and still needed supporting. this is one of the main reasons why libraries like jquery came into existence — to abstract away differences in browser implementations (e.g. ...
...many nightmares. such incompatibility problems persisted well into the early 2000s, as old browsers were still being used and still needed supporting. this is one of the main reasons why libraries like jquery came into existence — to abstract away differences in browser implementations (e.g. see the code snippet in how to make an http request) so developers only have to write one simple bit of code (see jquery.ajax()). ...
...e the code snippet in how to make an http request) so developers only have to write one simple bit of code (see jquery.ajax()). jquery (or whatever library you are using) will then handle the differences in the background, so you don't have to. things have improved significantly since then; modern browsers do a good job of supporting "classic javascript features", and the requirement to use such code has diminished as the requirement to support older browsers has lessened (although bear in mind that they have not gone away altogether). these days, most cross-browser javascript problems are seen: when poor-quality browser-sniffing code, feature-detection code, and vendor prefix usage block browsers from running code they could otherwise use just fine. when developers make use of new/nasce...
...And 48 more matches
NSS functions
most commonly used by applications to support ssl. the nss home page links to additional ssl documentation. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. ...
...r a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
...he deprecated functions are not supported by the new ssl shared libraries. applications that want to use the ssl shared libraries must convert to calling the new replacement functions listed below. each function name is linked to its entry in the old ssl reference. ...
...And 42 more matches
sslfnc.html
gdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_init opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) in the specified directory. nss_init isnot idempotent, so call it only once. nss_init opens the database files read-only. if you are performing operations that require write permission, for example s/mime operations such as adding a certificate, use nss_initreadwrite instead. before call...
...gdir); parameter this function has the following parameter: configdir a pointer to a string containing the pathname of the directory where the certificate, key, and security module databases reside. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_initreadwrite opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) with both read and write permission in the specified directory. nss_initreadwrite isnot idempotent, so call it only once. use nss_initreadwrite rather than nss_init if you are performing operations that require write permission, such as some s/mime operations. before calling nss_...
... certificate and key database files be opened. syntax #include "nss.h" secstatus nss_nodb_init(char *reserved); parameter this function has the following parameter: reserved should be null.. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_nodb_init opens only the temporary database and the internal pkcs #112 module. unlike nss_init, nss_nodb_init allows applications that do not have access to storage for databases to run raw crypto, hashing, and certificate functions. nss_nodb_init isnot idempotent, so call it only once. before calling nss_nodb_init, your program must call pr_init. the policy flags f...
...And 41 more matches
Migrating from webkitAudioContext - Web APIs
the web audio api went through many iterations before reaching its current state. it was first implemented in webkit, and some of its older parts were not immediately removed as they were replaced in the specification, leading to many sites using non-compatible code. in this article, we cover the differences in web audio api since it was first implemented in webkit and how to update your code to use the modern web audio api. the web audio standard was first implemented in webkit, and the implementation was built in parallel with the work on the specification of the api. as the specification evolved and changes were made to the spec, some of the old implementation pieces were not removed from the webkit (and blink) implementations due to backwards compatibility reasons. new engines im...
...l with the work on the specification of the api. as the specification evolved and changes were made to the spec, some of the old implementation pieces were not removed from the webkit (and blink) implementations due to backwards compatibility reasons. new engines implementing the web audio spec (such as gecko) will only implement the official, final version of the specification, which means that code using webkitaudiocontext or old naming conventions in the web audio specification may not immediately work out of the box in a compliant web audio implementation. this article attempts to summarize the areas where developers are likely to encounter these problems and provide examples on how to port such code to standards based audiocontext, which will work across different browser engines. not...
... in a compliant web audio implementation. this article attempts to summarize the areas where developers are likely to encounter these problems and provide examples on how to port such code to standards based audiocontext, which will work across different browser engines. note: there is a library called webkitaudiocontext monkeypatch, which automatically fixes some of these changes to make most code targetting webkitaudiocontext to work on the standards based audiocontext out of the box, but it currently doesn't handle all of the cases below. please consult the readme file for that library to see a list of apis that are automatically handled by it. changes to the creator methods three of the creator methods on webkitaudiocontext have been renamed in audiocontext. creategainnode() has ...
...And 40 more matches
HTML text fundamentals - Learn web development
ctural markup. active learning: giving our content structure let's jump straight in with a live example. in the example below, add elements to the raw text in the input field so that it appears as a heading and two paragraphs in the output field. if you make a mistake, you can always reset it using the reset button. if you get stuck, press the show solution button to see the answer. playable code <h2>live output</h2> <div class="output" style="min-height: 50px;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="input" style="min-height: 100px; width: 95%">my short story i am a statistician and my name is trish. my legs are made of cardboard and i am married to a fish.</tex...
...</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.queryselector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolu...
...var solution = document.getelementbyid('solution'); var output = document.queryselector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 'show solution') { textarea.value = solutionentry; solution.value = 'hide solution'; } else { textarea.value = userentry; solution.value = 'show solution'; } updatecode(); }); var htmlsolution = '<h1>my short story</h1>\n<p>i am a statistician and my name is trish.</p>\n<p>my legs are made of ca...
...And 39 more matches
Mozilla internal string guide
introduction the string classes are a library of c++ classes which are used to manage buffers of wide (16-bit) and narrow (8-bit) character strings. the headers and implementation are in the xpcom/string directory. all strings are stored as a single contiguous buffer of characters. the 8-bit and 16-bit string classes have completely separate base classes, but share the same apis. as a result, you cannot assign a 8-bit string to a 16-bit string without some kind of conversion helper class or routine. ...
...ust convenient notation for constructing an ns[c]s[ubs]tring with a non-default ownership mode; they should not be thought of as different types. nsliteral[c]string which should rarely be constructed explicitly but usually through the ""_ns and u""_ns user-defined string literals. nsliteral[c]string is trivially constructible and destructible, and therefore does not emit construction/destruction code when stored in statics, as opposed to the other string classes. the major string classes the list below describes the main base classes. once you are familiar with them, see the appendix describing what class to use when. nsastring/nsacstring: the abstract base class for all strings. it provides an api for assignment, individual character access, basic manipulation of characters in the stri...
...by guaranteeing a null-terminated storage. this allows for a method (.get()) to access the underlying character buffer. the remainder of the string classes inherit from either nsastring or nsstring. thus, every string class is compatible with nsastring. since every string derives from nsastring (or nsacstring), they all share a simple api. common read-only methods: .length() - the number of code units (bytes for 8-bit string classes and char16_ts for 16-bit string classes) in the string. .isempty() - the fastest way of determining if the string has any value. use this instead of testing string.length == 0 .equals(string) - true if the given string has the same value as the current string. common methods that modify the string: .assign(string) - assigns a new value to the string. ...
...And 37 more matches
Useful string methods - Learn web development
eturns a number representing the index position of the substring — which character number of the main string the substring starts at. if the substring is not found inside the main string, it returns a value of -1. try this: browsertype.indexof('zilla'); this gives us a result of 2, because the substring "zilla" starts at position 2 (0, 1, 2 — so 3 characters in) inside "mozilla". such code could be used to filter strings. for example, we may have a list of web addresses and only want to print out the ones that contain "mozilla". this can be done in another way, which is possibly even more effective. try the following: browsertype.indexof('vanilla'); this should give you a result of -1 — this is returned when the substring, in this case 'vanilla', is not found in the main ...
... actually update the value of the browsertype variable in a real program, you'd have to set the variable value to be the result of the operation; it doesn't just update the substring value automatically. so you'd have to actually write this: browsertype = browsertype.replace('moz','van'); active learning examples in this section we'll get you to try your hand at writing some string manipulation code. in each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. you don't need to understand arrays or loops right now — these will be explained in future articles. all you need to do in each case is write the code that will output the strings in the format that we want them in. each example comes with a "reset" button...
... an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. you don't need to understand arrays or loops right now — these will be explained in future articles. all you need to do in each case is write the code that will output the strings in the format that we want them in. each example comes with a "reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "show solution" button you can press to see a potential answer if you get really stuck. filtering greeting messages in the first exercise we'll start you off simple — we have an array of greeting card messages, but we want to sort them to list just the christmas messages. we want you to fill in a conditional test inside the if( ... )...
...And 36 more matches
JSAPI User Guide
this document explains how to embed spidermonkey, the mozilla javascript engine, in your c++ program. javascript is widely used for client-side scripts that run in the browser. but mozilla's javascript engine is a library that can be linked into any c++ program, not just a browser. many applications can benefit from scripting. these programs can execute javascript code from c++ using the spidermonkey api. note: the foss wiki page contains a few links to other libraries and programs that can make life easier when using spidermonkey and jsapi. what spidermonkey does the javascript engine compiles and executes scripts containing javascript statements and functions. the engine handles memory allocation for the objects needed to execute scripts, and it cleans up—garbage collects—objects it...
..., window.open, and xmlhttprequest. but in mozilla, all of these features are actually provided by other components, not the spidermonkey engine itself. spidermonkey provides a few core javascript data types—numbers, strings, arrays, objects, and so on—and a few methods, such as array.push. it also makes it easy for each application to expose some of its own objects and functions to javascript code. browsers expose dom objects. your application will expose objects that are relevant for the kind of scripts you want to write. it is up to the application developer to decide what objects and methods are exposed to scripts. hello world using the spidermonkey library to build spidermonkey from source, see spidermonkey build documentation. some systems (such as debian) provide spidermonkey as ...
... kind of scripts you want to write. it is up to the application developer to decide what objects and methods are exposed to scripts. hello world using the spidermonkey library to build spidermonkey from source, see spidermonkey build documentation. some systems (such as debian) provide spidermonkey as a prebuilt package. build it from source instead. your program will be easier to debug. c++ code accesses spidermonkey via the jsapi, by including the header "jsapi.h". an overview of jsapi functionality follows. for more details, see the jsapi reference. the spidermonkey universe in order to run any javascript code in spidermonkey, an application must have three key elements: a jsruntime, a jscontext, and a global object. this section describes what these things are. the next section expl...
...And 35 more matches
Advanced text formatting - Learn web development
previous overview: introduction to html next there are many other elements in html for formatting text, which we didn't get to in the html text fundamentals article. the elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more. prerequisites: basic html familiarity, as covered in getting started with html. html text formatting, as covered in html text fundamentals. objective: to learn how to use lesser-known html elements to mark up advanced semantic features. description lists in html text fundamentals, we walked t...
...t of definitions it's time to try your hand at description lists; add elements to the raw text in the input field so that it appears as a description list in the output field. you could try using your own terms and descriptions if you like. if you make a mistake, you can always reset it using the reset button. if you get really stuck, press the show solution button to see the answer. playable code <h2>live output</h2> <div class="output" style="min-height: 50px;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="input" style="min-height: 100px; width: 95%"> bacon the glue that binds the world together. eggs the glue that binds the cake together. coffee the drink that gets th...
...textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.queryselector('.output'); const code = textarea.value; const userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry ...
...And 34 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
previous overview: asynchronous next this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand asynchronous loops and intervals and what they are useful for. ...
... and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand asynchronous loops and intervals and what they are useful for. introduction for a long time, the web platform has offered javascript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop. these functions are: settimeout() execute a specified block of code once after a specified time has elapsed. setinterval() execute a specified block of code repeatedly with a fixed time delay between each call. requestanimationframe() the modern version of setint...
...sed, and to repeatedly execute a block of code asynchronously until you tell it to stop. these functions are: settimeout() execute a specified block of code once after a specified time has elapsed. setinterval() execute a specified block of code repeatedly with a fixed time delay between each call. requestanimationframe() the modern version of setinterval(). executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable framerate regardless of the environment it is being run in. the asynchronous code set up by these functions runs on the main thread (after their specified timer has elapsed). ...
...And 34 more matches
Document - Web APIs
Web › API › Document
ent set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document. documentorshadowroot.stylesheetsread only returns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. ...
...unlocked, or if the target is in another document. documentorshadowroot.stylesheetsread only returns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. event handlers document.onafterscriptexecute represents the event handling code for the afterscriptexecute event. document.onbeforescriptexecute represents the event handling code for the beforescriptexecute event. ...
...nly returns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. event handlers document.onafterscriptexecute represents the event handling code for the afterscriptexecute event. document.onbeforescriptexecute represents the event handling code for the beforescriptexecute event. document.oncopy represents the event handling code for the copy event. document.oncut represents the event handling code for the cut event. document.onfullscreenchange is an eventhandler representing the code to be called when the fullscreenchange event is raised. document.onfullscreenerror is an eventhandler representing the code to be called when the fullscreenerror event is raised. document.onpaste represents the event handling cod...
...And 33 more matches
WebIDL bindings
all webidl files should be placed in dom/webidl and added to the list in the moz.build file in that directory. ...
...st without the review; it will just annoy the dom peers and they'll make you get the review anyway. the configuration file, dom/bindings/bindings.conf, is basically a python dict that maps interface names to information about the interface, called a descriptor. there are all sorts of possible options here that handle various edge cases, but most descriptors can be very simple. all the generated code is placed in the mozilla::dom namespace. for each interface, a namespace whose name is the name of the interface with binding appended is created, and all the things pertaining to that interface's binding go in that namespace. there are various helper objects and utility methods in dom/bindings that are also all in the mozilla::dom namespace and whose headers are all exported into mozilla/dom (p...
...the idea is that walking the getparentobject chain will eventually get you to a window, so that every webidl object is associated with a particular window. for example, nsinode::getparentobject returns the node's owner document. the return type of getparentobject doesn't matter other than it must either singly...
...And 32 more matches
Graceful asynchronous programming with Promises - Learn web development
them in a lot more depth. essentially, a promise is an object that represents an intermediate state of an operation — in effect, a promise that a result of some kind will be returned at some point in the future. there is no guarantee of exactly when the operation will complete and the result will be returned, but there is a guarantee that when the result is available, or the promise fails, the code you provide will be executed in order to do something else with a successful result, or to gracefully handle a failure case. generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!), and more interested in being able to respond to it being returned, whenever that is. and of course, it's nice that it does...
...ted in order to do something else with a successful result, or to gracefully handle a failure case. generally, you are less interested in the amount of time an async operation will take to return its result (unless of course, it takes far too long!), and more interested in being able to respond to it being returned, whenever that is. and of course, it's nice that it doesn't block the rest of the code execution. one of the most common engagements you'll have with promises is with web apis that return a promise. let's consider a hypothetical video chat application. the application has a window with a list of the user's friends, and clicking on a button next to a user starts a video call to that user. that button's handler calls getusermedia() in order to get access to the user's camera and mi...
...able option; without promises, everything in the browser becomes unusable until the user decides what to do about the camera and microphone. so instead of waiting for the user, getting the chosen devices enabled, and directly returning the mediastream for the stream created from the selected sources, getusermedia() returns a promise which is resolved with the mediastream once it's available. ...
...And 31 more matches
Introducing a complete toolchain - Learn web development
articles in the series we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. we'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on netlify. in this article we'll introduce the case study, set up our development environment, and set up our code transformation tools. prerequisites: familiarity with the core html, css, and javascript languages. objective: to solidify what we've learnt so far by working through a complete toolchain case study. there really are unlimited combinations of tools and ways to use them, what you see in this article and the next is only one way that the featured tools can be used fo...
...ctive: to solidify what we've learnt so far by working through a complete toolchain case study. there really are unlimited combinations of tools and ways to use them, what you see in this article and the next is only one way that the featured tools can be used for a project. note: it's also worth repeating that not all of these tools need to be run on the command line. many of today's code editors (such as vs code and atom) have integration support for a lot of tools via plugins. introducing our case study the toolchain that we are creating in this article will be used to build and deploy a mini site that lists data (taken from one of nasa's open apis) concerning potentially hazardous space objects that threaten our existence on earth! it looks like this: you can see a live v...
...t need to know react to follow this tutorial, but we've included this to give you an idea of how a non-native web language could be integrated into a toolchain. the latest built-in javascript features (at time of writing), such as import. useful development tools such as prettier for formatting and eslint for linting. postcss to provide css nesting capabilities. parcel to build and minify our code, and to write a bunch of configuration file content automatically for us. github to manage our source code control. netlify to automate our deployment process. you may not be familiar with all the above features and tools or what they are doing, but don't panic — we'll explain each part as we move through this article. toolchains and their inherent complexity as with any chain, the more l...
...And 31 more matches
imgIContainer
???????????????????. ...
...erfaces.imgicontainer); method overview void addrestoredata([array, size_is(acount), const] in char data, in unsigned long acount); native code only! obsolete since gecko 2.0 void appendframe(in print32 ax, in print32 ay, in print32 awidth, in print32 aheight, in gfximageformat aformat, [array, size_is(imagelength)] out pruint8 imagedata, out unsigned long imagelength); native code only! obsolete since 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 ge...
...dth, 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, [const] in gfxrect afill, [const] in nsintrect asubimage, [const] in nsintsize aviewportsi...
...And 31 more matches
Digital audio concepts - Web media technologies
sampling audio audio is an inherently analog feature of the natural world. as an object vibrates, it causes the molecules surrounding it to vibrate as well. ...
... sampling audio audio is an inherently analog feature of the natural world. as an object vibrates, it causes the molecules surrounding it to vibrate as well. ...
... sampling audio audio is an inherently analog feature of the natural world. as an object vibrates, it causes the molecules surrounding it to vibrate as well. ...
...And 30 more matches
Python binding for NSS
r will be quite comfortable with python-nss. be "pythonic". the term pythonic means to follow accepted python paradigms and idoms in the python language and libraries. thus when deciding if the nss/nspr api should be rigidly followed or a more pythonic api provided the pythonic implementation wins because python programmers do not want to write c programs in python, rather they want their python code to feel like python code with the richness of full python. identifer names follow the preferred python style instead of the style in the nss/nspr c header files. classes are camel-case. class names always begin with a upper case letter and are then followed by a mix of lower and upper case letters, a upper case letter is used to separate words. acronyms always appear as a contiguous string...
...lso, any "global" values which are set in python-nss are actually thread-local. examples of this are the various callbacks which can be set and their parameters. thus each thread gets it own set of callbacks. many methods/functions provide sane default (keyword) parameters freeing the python programmer from having to specify all parameters yet allowing them to be overriden when necessary. error codes are never returned from methods/functions. python-nss follows the existing python exception mechanism. any error reported by nss/nspr is converted into a python exception and raised. the exact error code, error description, and often contextual error information will be present in the exception object. enumerated constants used in the nss/nspr api's are available in the python module under the ...
...ject. enumerated constants used in the nss/nspr api's are available in the python module under the exact same name as they appear in the c header files of nss/nspr. convenience functions are provided to translate between the numeric value of an enumerated constant and it's string representation and visa versa. python-nss internally supports utf-8. strings may be python str objects or python unicode objects. if a python unicode object is passed to a nss/nspr function it will be encoded as utf-8 first before being passed to nss/nspr. python-nss tries to be flexible when generating a print representation of complex objects. for simplicity you can receive a block of formatted text but if you need more control, such as when building gui elments you can access a list of "lines", each line is pai...
...And 29 more matches
Drawing graphics - Learn web development
cript objects module: around 2006–2007, mozilla started work on an experimental 3d canvas implementation. this became webgl, which gained traction among browser vendors, and was standardized around 2009–2010. webgl allows you to create real 3d graphics inside your web browser; the below example shows a simple rotating webgl cube: this article will focus mainly on 2d canvas, as raw webgl code is very complex. we will however show how to use a webgl library to create a 3d scene more easily, and you can find a tutorial covering raw webgl elsewhere — see getting started with webgl. note: basic canvas functionality is supported well across browsers, with the exception of ie 8 and below for 2d canvas, and ie 11 and below for webgl. active learning: getting started with a <canvas> if...
...g a constantly updating graph of stock prices, the fallback content could be a static image of the latest stock graph, with alt text saying what the prices are in text. creating and sizing our canvas let's start by creating our own canvas that we draw future experiments on to. first make a local copy of our 0_canvas_start.html file, and open it in your text editor. ...
... point (0, 0), the horizontal (x) axis runs from left to right, and the vertical (y) axis runs from top to bottom. drawing shapes tends to be done using the rectangle shape primitive, or by tracing a line along a certain path and then filling in the shape. below we'll show how to do both. simple rectangles let's start with some simple rectangles. first of all, take a copy of your newly coded canvas template (or make a local copy of 1_canvas_template.html if you didn't follow the above steps). next, add the following lines to the bottom of your javascript: ctx.fillstyle = 'rgb(255, 0, 0)'; ctx.fillrect(50, 50, 100, 150); if you save and refresh, you should see a red rectangle has appeared on your canvas. its top left corner is 50 pixels away from the top and left of the c...
...And 28 more matches
GlobalEventHandlers - Web APIs
eate an object of type globaleventhandlers. properties this interface doesn't include any properties except for the event handlers listed below. event handlers these event handlers are defined on the globaleventhandlers mixin, and implemented by htmlelement, document, window, as well as by workerglobalscope for web workers. globaleventhandlers.onabort is an eventhandler representing the code to be called when the abort event is raised. globaleventhandlers.onanimationcancel an eventhandler called when an animationcancel event is sent, indicating that a running css animation has been canceled. globaleventhandlers.onanimationend an eventhandler called when an animationend event is sent, indicating that a css animation has stopped playing. globaleventhandlers.onanimationiteratio...
...andlers.onanimationstart an eventhandler called when an animationstart event is sent, indicating that a css animation has started playing. globaleventhandlers.onauxclick an eventhandler called when an auxclick event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button). ...
...as started playing. globaleventhandlers.onauxclick an eventhandler called when an auxclick event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button). globaleventhandlers.onblur is an eventhandler representing the code to be called when the blur event is raised. globaleventhandlers.onerror is an onerroreventhandler representing the code to be called when the error event is raised. globaleventhandlers.onfocus is an eventhandler representing the code to be called when the focus event is raised. globaleventhandlers.oncancel is an eventhandler representing the code to be called when the cancel event is raised. globaleventhandlers.oncanplay is an eventhandler representing the code to be called when the canplay event is raised. ...
...And 28 more matches
Getting started with HTML - Learn web development
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;width: 95%"> this is my text. </textarea> <div class="controls"> <input id="reset" type="button" value="reset" /> <inpu...
...s"> <input id="reset" type="button" value="reset" /> <input id="solution" type="button" value="show solution" /> </div> html { font-family: 'open sans light',helvetica,arial,sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.queryselector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolu...
...var solution = document.getelementbyid('solution'); var output = document.queryselector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 'show solution') { textarea.value = solutionentry; solution.value = 'hide solution'; } else { textarea.value = userentry; solution.value = 'show solution'; } updatecode(); }); var htmlsolution = '<em>this is my text.</em>'; var solutionentry = htmlsolution; textarea.addeventlistener('input', up...
...And 27 more matches
Index - Learn web development
se you must be familiar with the technique of your craft, but what really matters is what you want to accomplish. yes, it seems obvious, but too many projects fail not from a lack of technical know-how, but from lack of goals and vision. 17 how do i use github pages? beginner, github, guide, web, gh-pages, git, publish github is a "social coding" site. it allows you to upload code repositories for storage in the git version control system. you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it. you can do that with other people's code too! this article provides a basic guide to publishing content using github's gh-pages feature. 18 h...
...r a certain way, or act a certain way. the enclosing tags can make a word or image hyperlink to somewhere else, can italicize words, can make the font bigger or smaller, and so on. for example, take the following line of content: 40 how the web works beginner, client, dns, http, ip, infrastructure, learn, server, tcp, l10n:priority this theory is not essential to writing web code in the short term, but before long you'll really start to benefit from understanding what's happening in the background. 41 installing basic software beginner, browser, learn, setup, tools, webmechanics, l10n:priority, text editor that looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these. in this article...
...mmon pitfalls where appropriate. we'll probably add to this resource as time goes on. 51 cooperative asynchronous javascript: timeouts and intervals animation, beginner, codingscripting, guide, intervals, javascript, loops, asynchronous, requestanimationframe, setinterval, settimeout, timeouts this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. 52 general asynchronous programming concepts javascript, learn, promises, threads, asynchronous, blocking in this article, we'll run through a number of important concepts relating to asyn...
...And 27 more matches
nsIJSON
however, you should use native json instead if at all possible. implemented by: @mozilla.org/dom/json;1. ...
...however, you should use native json instead if at all possible. implemented by: @mozilla.org/dom/json;1. ...
...however, you should use native json instead if at all possible. implemented by: @mozilla.org/dom/json;1. ...
...And 27 more matches
Mozilla
a bird's-eye view of the mozilla framework the purpose of this article is to provide a high-level technical overview of the architecture of the extensible, object-based mozilla application framework. accessibility and mozilla accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. ...
...ozilla strives to make its software accessible; the documents below cover the ways in which we do so. add-ons add-ons allow developers to extend and modify the functionality of firefox. adding a new css property this page describes how to add a new css property to the style system. the style system is the part of the code in gecko that is responsible for producing a computed value for every property for every element. see the gecko overview for more information about the style system. adding a new event this draft document covers how to add a new event to the mozilla (firefox) source code. adding a new word to the en-us dictionary occ...
...nology lets firefox help protect users by comparing the urls the user visits to a list of known scam sites, and presenting a warning to the user when they visit a site on the list. an introduction to hacking mozilla this guide introduces the mozilla project and provides an overview for developers interested in contributing to or exploring the various parts of the codebase. android-specific test suites there are several android-specific test suites that run on the firefox for android codebase: api change rules until further notice, the following rules govern api changes: application cache implementation overview this happens in nshttpchannel::opencacheentry(). all top level document ...
...And 27 more matches
Signing an XPI - Archive of obsolete content
note: these instructions are outdated. for an extension to work in firefox it must be signed by mozilla, not by yourself. see signing and distributing your add-on. note: these instructions are for how to test with a self-signed certificate. see signing an extension for a practical guide. introduction this article describes how to sign your own firefox extensions with a code-signing certificate on a windows platform. it was developed from the linux article so you want to sign your xpi package? by mozdev group's pete collins. this article is a mirror of the original, with minor reformatting, some new info and all links updated in march 2010. get network security services 1. download the latest network security services (nss) package from the mozilla ftp site at https://ftp.mozilla.
...e of these files (e.g. certutil.exe) in the system directory (\windows\system32\) so ensure the new paths are first in the path search list. c:\> set path=c:\apps\nss-3.11.4\bin\;c:\apps\nss-3.11.4\lib\;c:\apps\nspr-4.6\lib\;%path% an easier way is to copy everything from your new directories c:\apps\nss-3.11.4\ and c:\apps\nspr-4.6\ including sub directories to the same directory - fx c:\apps\codesigning\ - and then run every command from that. initialize the certificate database decide which folder to create the certificate database in. use this command to create it (note the trailing dot is required). c:\projects\codesigning\> certutil -n -d . the dot will cause the database to be created in the current directory. you will be prompted for the nss certificate database password - don...
...ry command from that. initialize the certificate database decide which folder to create the certificate database in. use this command to create it (note the trailing dot is required). c:\projects\codesigning\> certutil -n -d . the dot will cause the database to be created in the current directory. you will be prompted for the nss certificate database password - don't forget it! ...
...And 26 more matches
Making asynchronous programming easier with async and await - Learn web development
previous overview: asynchronous next more recent additions to the javascript language are async functions and the await keyword, part of the so-called ecmascript 2017 javascript edition (see ecmascript next support in mozilla). these features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards. they make async code look more like old-school synchronous code, so they're well worth learning. this article gives you what you need to know. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals, an understanding of async code in general and promises. objective: to understand promises and how to use them. the basics of async/await there are two parts to us...
...s code, so they're well worth learning. this article gives you what you need to know. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals, an understanding of async code in general and promises. objective: to understand promises and how to use them. the basics of async/await there are two parts to using async/await in your code. the async keyword first of all we have the async keyword, which you put in front of a function declaration to turn it into an async function. an async function is a function that knows how to expect the possibility of the await keyword being used to invoke asynchronous code. try typing the following lines into your browser's js console: function hello() { return "hello" }; hello(); the func...
... using await. by only adding the necessary handling when the function is declared async, the javascript engine can optimize your program for you. sweet! the await keyword the real advantage of async functions becomes apparent when you combine it with the await keyword — in fact, await only works inside async functions. this can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value. in the meantime, other code that may be waiting for a chance to execute gets to do so. you can use await when calling any function that returns a promise, including web api functions. here is a trivial example: async function hello() { return greeting = await promise.resolve("hello"); }; hello().then(alert); of cours...
...And 26 more matches
Arrays - Learn web development
he list, like loop through it and do the same thing to every value. maybe we've got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice, while totaling all the prices together and printing out the total price at the bottom. if we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item. this would be much longer to write out, less efficient, and more error-prone. if we had 10 items to add to the invoice it would already be annoying, but what about 100 items, or 1000? we'll return to this example later on in the article. as in previous articles, let's learn about the real basics of arrays by entering some examples into ...
...annoying, but what about 100 items, or 1000? we'll return to this example later on in the article. as in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console. creating arrays arrays consist of square brackets and elements that are separated by commas. suppose we want to store a shopping list in an array. paste the following code into the console: let shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles']; shopping; in the above example, each element is a string, but in an array we can store various data types — strings, numbers, objects, and even other arrays. we can also mix data types in a single array — we do not have to limit ourselves to storing only numbers in one array, and in another only strings. f...
...e length property. try the following: shopping.length; // should return 5 this has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array. so for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; for (let i = 0; i < sequence.length; i++) { console.log(sequence[i]); } you'll learn about loops properly later on (in our looping code article), but briefly, this code is saying: start looping at item number 0 in the array. stop looping at the item number equal to the length of the array. this works for an array of any length, but in this case it stops looping at item number 7 (this is good, as the last item — which we want the loop to include — is item 6). for each item, print it out to the browser console with console...
...And 26 more matches
TypeScript support in Svelte - Learn web development
k briefly about the pros and cons of using typescript. even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. if you are not interested at all in typescript, you can skip to the next chapter, where we will look at different options for deploying our svelte applications, further resources, and more. ...
...atic typing for javascript typescript is a superset of javascript that provides features such as optional static typing, classes, interfaces, and generics. the goal of typescript is to help catch mistakes early through its type system and make javascript development more efficient. one of the big benefits is enabling ides to provide a richer environment for spotting common errors as you type the code. ...
...escript is a superset of javascript that provides features such as optional static typing, classes, interfaces, and generics. the goal of typescript is to help catch mistakes early through its type system and make javascript development more efficient. one of the big benefits is enabling ides to provide a richer environment for spotting common errors as you type the code. ...
...And 26 more matches
Hacking Tips
ese tips only apply to debug builds of the js shell; they will not function in a release build. debugging tips getting help (from js shell) use the help function to get the list of all primitive functions of the shell with their description. note that some functions have been moved under an 'os' object, and help(os) will give brief help on just the members of that "namespace". getting the bytecode of a function (from js shell) the shell has a small function named dis to dump the bytecode of a function with its source notes. without arguments, it will dump the bytecode of its caller. js> function f () { return 1; } js> dis(f); flags: loc op ----- -- main: 00000: one 00001: return 00002: stop source notes: ofs line pc delta desc args ---- ---- ----- ------ -------- -...
... some variants of this function such as js::dumpscript etc are convenient for debugging. printing the js stack (from gdb) in jsobj.cpp, a function named js::dumpbacktrace prints a backtrace à la gdb for the js stack. ...
... some variants of this function such as js::dumpscript etc are convenient for debugging. printing the js stack (from gdb) in jsobj.cpp, a function named js::dumpbacktrace prints a backtrace à la gdb for the js stack. ...
...And 26 more matches
Shell global objects
tions always available version([number]) get or force a script compilation version number. options([option ...]) get or toggle javascript options. load(['foo.js' ...]) load files named by string arguments. filename is relative to the current working directory. loadrelativetoscript(['foo.js' ...]) load files named by string arguments. filename is relative to the calling script. evaluate(code[, options]) evaluate code as though it were the contents of a file. options is an optional object that may have these properties: isrunonce use the isrunonce compiler option (default: false) noscriptrval use the no-script-rval compiler option (default: false) filename filename for error messages and debug info linenumber starting line number for error messages and debug info ...
...if the property is omitted or v is null, don't attribute the sour...
...hout an exception value, as for slow scripts or out-of-memory) and return 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the dom element o. if the property is omitted or v is null, don't attribute the source to any dom element. elementattributename if present and not undefined, the name of property of element that holds this code. this is what debugger.source.prototype.elementattributename returns. sourcemapurl if present with value v, convert v to a string, and provide that as the code's source map url. if omitted, attach no source map url to the code (although the code may provide one itself, via a //#sourcemappingurl comment). sourceislazy if present and true, indicates that, after compilation, script source sh...
...And 26 more matches
Strict mode - JavaScript
sometimes you'll see the default, non-strict mode referred to as "sloppy mode". this isn't an official term, but be aware of it, just in case. javascript's strict mode, introduced in ecmascript 5, is a way to opt in to a restricted variant of javascript, thereby implicitly opting-out of "sloppy mode". strict mode isn't just a subset: it intentionally has different semantics from normal code. browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. strict mode makes several changes to normal javascript semantics: eliminates some ...
...support for the relevant aspects of strict mode. strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. strict mode makes several changes to normal javascript semantics: eliminates some javascript silent errors by changing them to throw errors. fixes mistakes that make it difficult for javascript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. prohibits some syntax likely to be defined in future versions of ecmascript. see transitioning to strict mode, if you want to change your code to work in the restricted variant of javascript. invoking strict mode strict mode applies to entire scripts or to individual functions. it doesn't apply to block statement...
...ohibits some syntax likely to be defined in future versions of ecmascript. see transitioning to strict mode, if you want to change your code to work in the restricted variant of javascript. invoking strict mode strict mode applies to entire scripts or to individual functions. it doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, function code, event handler attributes, strings passed to windowtimers.settimeout(), and related functions are entire scripts, and invoking strict mode in them works as expected. strict mode for scripts to invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements. // whole-script strict mode syntax 'use strict'; var v = "hi!
...And 26 more matches
Building accessible custom components in XUL - Archive of obsolete content
r and cell is defined in the value attribute. the flex attributes are simply for layout. note: the row and column headers are denoted by description elements, and individual cells are denoted by label elements. this is not an accessibility requirement; as we'll see in the next section, the actual xul elements are irrelevant because we will define the role of each element in a separate attribute. ...
... <description value="expense"/> <label value="conference fee" flex="1"/> <label value="lodging" flex="1"/> <label value="dinner" flex="1"/> <label value="lodging" flex="1"/> <label value="breakfast" flex="1"/> <label value="lunch" flex="1"/> <label value="dinner" flex="1"/> </column> <-- several columns omitted for brevity --> </columns> </grid> </code> now we can use css to add some minimal styling to make it actually look like a spreadsheet. <code> @namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); grid.spreadsheet { border: thin solid; } grid.spreadsheet label { border-bottom: 1px solid black; border-left: 1px solid black; margin: 0; padding: 3px; } grid.spreadsheet description { color: black; b...
...the final product looks like this: <caption>xul spreadsheet with 7 rows and 5 columns</caption> although this has the visual layout of a spreadsheet, assistive technologies will only see it as a collection of individual, unrelated text labels. if we inspect this with the msaa...
...And 24 more matches
What is JavaScript? - Learn web development
at we use to apply styling to our html content, for example setting background colors and fonts, and laying out our content in multiple columns. javascript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (okay, not everything, but it is amazing what you can achieve with a few lines of javascript code.) the three layers build on top of one another nicely. let's take a simple text label as an example. we can mark it up using html to give it structure and purpose: <p>player 1: chris</p> then we can add some css into the mix to get it looking nice: p { font-family: 'helvetica neue', helvetica, sans-serif; letter-spacing: 1px; text-transform: uppercase; text-align: center; border:...
... so what can it really do? the core client-side javascript language consists of some common programming features that allow you to do things like: store useful values inside variables. in the above example for instance, we ask for a new name to be entered then store that name in a variable called ...
...o do things like: store useful values inside variables. in the above example for instance, we ask for a new name to be entered then store that name in a variable called name. operations on pieces of text (known as "strings" in programming). in the above example we take the string "player 1: " and join it to the name variable to create the complete text label, e.g. ''player 1: chris". running code in response to certain events occurring on a web page. we used a click event in our example above to detect when the button is clicked and then run the code that updates the text label. and much more! what is even more exciting however is the functionality built on top of the client-side javascript language. so-called application programming interfaces (apis) provide you with extra superpowers...
...And 24 more matches
Debugger.Script - Firefox Developer Tools
debugger.script a debugger.script instance may refer to a sequence of bytecode in the debuggee or to a block of webassembly code. for the former, it is the debugger api’s presentation of a jsapi jsscript object. the two cases are distinguished by their format property being "js" or "wasm". debugger.script for jsscripts for debugger.script instances referring to a jsscript, they are distinguished by their format property being "js". each of the following is represented by a single jsscript object: the body of a function—that is, all the code in the function that is not contained within some nested function. the code passed to a single call to eval, excluding the bodies of any functions that code defines. the contents of a <script> element. a dom event han...
...nted by a single jsscript object: the body of a function—that is, all the code in the function that is not contained within some nested function. the code passed to a single call to eval, excluding the bodies of any functions that code defines. the contents of a <script> element. a dom event handler, whether embedded in html or attached to the element by other javascript code. code appearing in a javascript: url. the debugger interface constructs debugger.script objects as scripts of debuggee code are uncovered by the debugger: via the onnewscript handler method; via debugger.frame’s script properties; via the functionscript method of debugger.object instances; and so on. for a given debugger instance, spidermonkey constructs exactly one debugger.script in...
...e debugger interface constructs debugger.script objects as scripts of debuggee code are uncovered by the debugger: via the onnewscript handler method; via debugger.frame’s script properties; via the functionscript method of debugger.object instances; and so on. for a given debugger instance, spidermonkey constructs exactly one debugger.script instance for each underlying script object; debugger code can add its own properties to a script object and expect to find them later, use == to decide whether two expressions refer to the same script, and so on. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.script instance for a given script. ...
...And 24 more matches
Debugger.Object - Firefox Developer Tools
s (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object instance to the debugger each time. this means that the debugger can use the == operator to recognize when two debugger.object instances refer to the same debuggee object, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. ...
...ct instance to the debugger each time. this means that the debugger can use the == operator to recognize when two debugger.object instances refer to the same debuggee object, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. javascript code in different compartments can have different views of the same object. ...
... to the same debuggee object, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. javascript code in different compartments can have different views of the same object. for example, in firefox, code in privileged compartments sees content dom element objects without redefinitions or extensions made to that object's properties by content code. (in firefox terminology, privileged code sees the element through an "xray wrapper".) to ensure that debugger code sees each object just as the debuggee would, each debugger.object instance presents its referent as it would be seen from a particular compartment. this "viewing compartment" is chosen to match the way the debugger came across the referent. as a consequence, a single debugger instan...
...And 24 more matches
A first splash into JavaScript - Learn web development
le "guess the number" game, step by step. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. objective: to have a first bit of experience at writing some javascript, and gain at least a basic understanding of what writing a javascript program involves. ...
......
..., etc. the code syntax looks different, but the concepts are still largely the same. thinking like a programmer one of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real world problems. you need to start thinking like a programmer — this generally involves looking at descriptions of what your program needs to do, working out what code features are needed to achieve those things, and how to make them work together. this requires a mixture of hard work, experience with the programming syntax, and practice — plus a bit of creativity. the more you code, the better you'll get at it. we can't promise that you'll develop "programmer brain" in five minutes, but we will give you plenty of opportunity to practice thinking like a prog...
...And 23 more matches
Signaling and video calling - Web APIs
ted as part of our websocket documentation (this article link is forthcoming; it isn't actually online yet) to support opening a two-way video call between users. you can try out this example on glitch, and you can remix the example to experiment with it as well. you can also look at the full project on github. note: if you try out the example on glitch, please note that any changes made to the code will immediately reset any connections. in addition, there is a short timeout period; the glitch instance is for quick experiments and testing only. the signaling server establishing a webrtc connection between two devices requires the use of a signaling server to resolve how to connect them over the internet. a signaling server's job is to serve as an intermediary to let two peers find and es...
...e signaling server. readying the chat server for signaling our chat server uses the websocket api to send information as json strings between each client and the server. the server supports several message types to handle tasks, such as registering new users, setting usernames, and sending public chat messages. to allow the server to support signaling and ice negotiation, we need to update the code. we'll have to allow directing messages to one specific user instead of broadcasting to all connected users, and ensure unrecognized message types are passed through and delivered, without the server needing to know what they are. this lets us send signaling messages using this same server, instead of needing a separate server. let's take a look which changes we need to make to the chat server s...
...to support doing so. ...
...And 23 more matches
NSS_3.12_release_notes.html
g/nspr/releases/v4.7.1/. ...
...ve the following versions: sqlite3: 3.3.17 nssckbi: 1.70 softokn3 and freebl3: 3.12.0.3 other nss libraries: 3.12.0.3 new in nss 3.12 3 new shared library are shipped with nss 3.12: nssutil sqlite nssdbm 1 new include file is shipped with nss3.12: utilrename.h new functions in the nss shared library: cert_checknamespace (see cert.h) cert_encodecertpoliciesextension (see cert.h) cert_encodeinfoaccessextension (see cert.h) cert_encodeinhibitanyextension (see cert.h) cert_encodenoticereference (see cert.h) cert_encodepolicyconstraintsextension (see cert.h) cert_encodepolicymappingextension (see cert.h) cert_encodesubjectkeyid (see certdb/cert.h) cert_encodeusernotice (see cert.h) cert_findcrlentryreasonexten (see cert.h) cert_findcrlnumberexten (see cert.h) cert_findnameconstraintsext...
....h for details): ckk: keys ckk_camellia ckm: mechanisms ckm_sha224_rsa_pkcs ckm_sha224_rsa_pkcs_pss ckm_sha224 ckm_sha224_hmac ckm_sha224_hmac_general ckm_sha224_key_derivation ckm_camellia_key_gen ckm_camellia_ecb ckm_camellia_cbc ckm_camellia_mac ckm_camellia_mac_general ckm_camellia_cbc_pad ckm_camellia_ecb_encrypt_data ckm_camellia_cbc_encrypt_data ckg: mfgs ckg_mgf1_sha224 new error codes (see secerr.h): sec_error_not_initialized sec_error_token_not_logged_in sec_error_ocsp_responder_cert_invalid sec_error_ocsp_bad_signature sec_error_out_of_search_limits sec_error_invalid_policy_mapping sec_error_policy_validation_failed sec_error_unknown_aia_location_type sec_error_bad_http_response sec_error_bad_ldap_response sec_error_failed_to_encode_data sec_error_bad_info_access_location ...
...And 22 more matches
nss tech note1
how to use the nss asn.1 and quickder decoders nss technical note: 1 nss 3.6 contains several decoders for asn.1 and der.two of them are extensively used and are part of the public nss api : the "classic" asn.1 decoder, written by lisa repka . this was written to be a generic decoder, that includes both der (distinguished encoding rules) and ber (basic encoding rules).† it handles both streaming and non-streaming input. the "quickder" decoder, written by julien pierre for nss 3.6 . this decoder was written when performance issues were discovered with the classic decoder. it can only decode der .† it does not handle streaming input, and requires that all input be present before beginning to decode. despite their differences, the two decoders have a lot in common. quick...
...ritten by julien pierre for nss 3.6 . this decoder was written when performance issues were discovered with the classic decoder. it can only decode der .† it does not handle streaming input, and requires that all input be present before beginning to decode. despite their differences, the two decoders have a lot in common. quickder was written to be as compatible as possible with the classic decoder, in order to ease migration to it in areas of critical performance bottlenecks. for this reason, i will first describe all the common functionality of the two decoders, before outlining their differences. ...
...de. despite their differences, the two decoders have a lot in common. quickder was written to be as compatible as possible with the classic decoder, in order to ease migration to it in areas of critical performance bottlenecks. for this reason, i will first describe all the common functionality of the two decoders, before outlining their differences. ...
...And 22 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
source software (oss) licenses are, what types of licenses exist, and when they’re appropriate. what is an oss license? what are the different kinds of oss licenses and what are their key characteristics? applying an oss license oss licensing today and in the future references what is an oss license? an open-source software license is a statement that anyone is free to use your source code in whatever way they want. the open source definition states what conditions the oss license must satisfy. perhaps surprisingly, these licenses enforce their terms through the exercise of copyright. understanding copyright all software licenses, not just open source, enforce their terms based on copyright. it’s easiest to understand if we think of it as being implemented in terms of the copyr...
...an oss license? so now you’re wondering, what conditions does an oss license place on software? this can be briefly answered by the open source definition, which was determined by the open source initiative (osi). this covers three rights and six conditions. what is important to us now is the following three rights: open source rights: a user can create and distribute copies of the source code; a user can obtain a program’s source code; a user can modify the source code. any oss license will include these rights. the user is free to use (duplicate, distribute, and modify) the source code, following certain conditions. this means that the author is granting users the use of the work in the strong, authorial sense, and when i write “use” in the rest of this document it is gener...
...rce code, following certain conditions. this means that the author is granting users the use of the work in the strong, authorial sense, and when i write “use” in the rest of this document it is generally in that sense. these conditions will vary from one license to the next, but the open source definition stipulates the following minimum conditions: the integrity of the author’s source code must be preserved; no discrimination may be made against individuals or organizations; no discrimination may be made based on field of endeavor; no additional licensing can be required when redistributing; license must not be specific to a product; license must not interfere with other software. the “no discrimination may be made against individuals or organizations” rule means that yo...
...And 21 more matches
Mozilla Crypto FAQ - Archive of obsolete content
c software, particularly for commercial sale or distribution, then you should consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction. i've updated this version of the mozilla crypto faq to discuss the situation now that the rsa public key algorithm is in the public domain and a full open source crypto implementation is being added to the mozilla code base. information in the faq also reflects the new u.s. encryption export regulations published on january 14, 2000, the release on february 11, 2000, of source code for ssl, s/mime, and general pki functionality for use in the mozilla project, and the "bernstein advisory" issued by the bureau of export administration on february 17, 2000. the questions in this faq address mozilla's support for ...
... to mozilla contributors relating to encryption functionality in mozilla, and general questions on u.s. regulation of encryption technology. cryptographic functionality in mozilla have all the issues with mozilla and crypto now been resolved? almost. now that the rsa patent is in the public domain, mozilla crypto development can proceed with minimal restrictions. in the near future the mozilla code base will include a complete open source cryptographic library, and mozilla will include ssl support as a standard feature. after the u.s. government relaxed u.s. export regulations in january 2000 to allow export of source code for open source software implementing encryption, the major remaining legal obstacle to mozilla crypto development was the fact that rsa security, inc., held a u.s. pate...
... after the u.s. government relaxed u.s. export regulations in january 2000 to allow export of source code for open source software implementing encryption, the major remaining legal obstacle to mozilla crypto development was the fact that rsa security, inc., held a u.s. patent on the rsa public key algorithm. in february 2000 iplanet e-commerce solutions (a sun-netscape alliance) released source code through mozilla.org for the personal security manager and network security services software; this source code included support for the ssl protocol, but due to the rsa patent and related legal issues it did not originally contain code for rsa or other cryptographic algorithms. on september 6, 2000, rsa security released the rsa patent into the public domain, two weeks before the patent was sche...
...And 21 more matches
Client-side storage - Learn web development
ics of client-side apis objective: to learn how to use client-side storage apis to store application data. client-side storage? elsewhere in the mdn learning area we talked about the difference between static sites and dynamic sites. most major modern web sites are dynamic — they store data on the server using some kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting html to the client to be displayed by the user's browser. client-side storage works on similar principles, but has different uses. it consists of javascript apis that allow you to store data on the client (i.e. on the user's machine) and then retrieve it when needed. this has many distinct uses, such as: pe...
...ins a simple website with a header, content, and footer, and a form for entering your name. let's build up the example, so you can understand how it works. first, make a local copy of our personal-greeting.html file in a new directory on your computer. next, note how our html references a javascript file called index.js (see line 40). we need to create this and write our javascript code into it. create an index.js file in the same directory as your html file. we'll start off by creating references to all the html features we need to manipulate in this example — we'll create them all as constants, as these references do not need to change in the lifecycle of the app. add the following lines to your javascript file: // create needed constants const rememberdiv = docume...
...#submitname'); const forgetbtn = document.queryselector('#forgetname'); const h1 = document.queryselector('h1'); const personalgreeting = document.queryselector('.personal-greeting'); next up, we need to include a small event listener to stop the form from actually submitting itself when the submit button is pressed, as this is not the behavior we want. add this snippet below your previous code: // stop the form from submitting when a button is pressed form.addeventlistener('submit', function(e) { e.preventdefault(); }); now we need to add an event listener, the handler function of which will run when the "say hello" button is clicked. the comments explain in detail what each bit does, but in essence here we are taking the name the user has entered into the text input box and...
...And 21 more matches
Deploying our app - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages. objective: to finish working through our complete toolchain case study, focusing on deploying the app. ...
...fecycle. as such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible. here's just a few things to consider for this particular project: generating a production build: ensuring files are minimised, chunked, have tree-shaking applied, and that versions are "cache busted". running tests: these can range from "is this code formatted properly?" to "does this thing do what i expect?", and ensuring failing tests prevent deployment. actually deploying the updated code to a live url: or potentially a staging url so it can be reviewed first. note: cache busting is a new term that we haven't met before in the module. this is the strategy of breaking a browser's own caching mechanism, which forces the browser to downlo...
...to "does this thing do what i expect?", and ensuring failing tests prevent deployment. actually deploying the updated code to a live url: or potentially a staging url so it can be reviewed first. note: cache busting is a new term that we haven't met before in the module. this is the strategy of breaking a browser's own caching mechanism, which forces the browser to download a new copy of your code. parcel (and indeed many other tools) will generate filenames that are unique to each new build. this unique filename "busts" your browser's cache, thereby making sure the browser downloads the fresh code each time an update is made to the deployed code. the above tasks also break down into further tasks; note that most web development teams will have their own terms and processes for at least ...
...And 21 more matches
Client-side tooling overview - Learn web development
file for a tool like webpack can be hundreds of lines long, most of which are magical incantations that seem to do the job but which only a master engineer will fully understand! from time to time, even the most experienced of web developers get stuck on a tooling problem; it is possible to waste hours attempting to get a tooling pipeline working before even touching a single line of application code. if you have found yourself struggling in the past, then don’t worry — you are not alone. in these articles, we won’t answer every question about web tooling, but we will provide you with a useful starting point of understanding the fundamentals, which you can then build from. as with any complex topic, it is good to start small, and gradually work your way up to more advanced uses. the m...
...odern tooling ecosystem today's modern developer tooling ecosystem is huge, so it's useful to have a broad idea of what main problems the tools are solving. if you jump on your favourite search engine and look for "front-end developer tools" you're going to hit a huge spectrum of results ranging from text editors, to browsers, to the type of pens you can use to take notes. though your choice of code editor is certainly a tooling choice, this series of articles will go beyond that, focusing on developer tools that help you produce web code more efficiently. from a high-level perspective, you can put client-side tools into the following three broad categories of problems to solve: safety net — tools that are useful during your code development. transformation — tools that transform co...
...-level perspective, you can put client-side tools into the following three broad categories of problems to solve: safety net — tools that are useful during your code development. transformation — tools that transform code in some way, e.g. turning an intermediate language into javascript that a browser can understand. post-development — tools that are useful after you have written your code, such as testing and deployment tools. let's look at each one of these in more detail. safety net these are tools that make the code you write a little better. this part of the tooling should be specific to your own development environment, though it’s not uncommon for companies to have some kind of policy or pre-baked configuration available to install so that all their developers are all...
...And 21 more matches
Tracing JIT
this document is talking about deprecated feature. the tracing jit in spidermonkey consists of a generic, low level component called nanojit which is co-maintained between adobe and mozilla, and a spidermonkey-specific high level component called jstracer. the nanojit component is language agnostic, and contains no knowledge about spidermonkey or any other part of the mozilla codebase. the jstracer component consists of a monitor and a recorder. the monitor watches the executing spidermonkey interpreter. when the monitor determines that the interpreter has entered a region of code that would benefit from native compilation, the monitor activates the recorder. the recorder records the activity of the interpreter, using nanojit to build an efficient, native representation of the execu...
...nitor watches the executing spidermonkey interpreter. when the monitor determines that the interpreter has entered a region of code that would benefit from native compilation, the monitor activates the recorder. the recorder records the activity of the interpreter, using nanojit to build an efficient, native representation of the execution called a fragment. the monitor then calls into the native code stored in the fragment. a schematic diagram of the components of the tracing jit follows: generic low level component: nanojit/* the files in the nanojit directory define the nanojit component. nanojit/lir.* the nanojit/lir.cpp and nanojit/lir.h files define the intermediate representation lir, which is used as input to nanojit. lir is a conventional three-address, linear ssa code. a sing...
...pipeline and assembler transform the lins values into nins values. nanojit/fragmento.* the nanojit/fragment.cpp and nanojit/fragmento.cpp files define the fragment and fragmento classes. a fragmento is a resource-management object that allocates and stores a set of fragments and pages, and manages their lifecycle. a fragmento owns its associated fragments. a fragment represents a single linear code sequence, typically terminating in a jump to another fragment or back to the beginning of the fragment. a fragment's code is stored in a set of associated pages and guardrecords allocated from the fragment's owning fragmento. a fragment initially holds no pages. as the compilation pipeline inserts lir instructions (lins values) into the fragment, it allocates pages to store the lir code. later, w...
...And 21 more matches
SpiderMonkey Internals
this document is talking about partially obsolete things. design walk-through at heart, spidermonkey is a fast interpreter that runs an untyped bytecode and operates on values of type js::value—type-tagged values that represent the full range of javascript values. in addition to the interpreter, spidermonkey contains a just-in-time (jit) compiler, a garbage collector, code implementing the basic behavior of javascript values, a standard library implementing ecma 262-5.1 §15 with various extensions, and a few public apis. ...
... to the interpreter, spidermonkey contains a just-in-time (jit) compiler, a garbage collector, code implementing the basic behavior of javascript values, a standard library implementing ecma 262-5.1 §15 with various extensions, and a few public apis. interpreter like many portable interpreters, spidermonkey's interpreter is mainly a single, tremendously long function that steps through the bytecode one instruction at a time, using a switch statement (or faster alternative, depending on the compiler) to jump to the appropriate chunk of code for the current instruction. a js-to-js function call pushes a javascript stack frame without growing the c stack. ...
...common cases are inlined in the interpreter loop, breaking any abstractions that stand in the way. so optimizations such as dense arrays and the property cache are, alas, not transparently tucked away in the jsarray.* and jsobj.* files. ...
...And 21 more matches
nsIPluginHost
dom/plugins/base/nsipluginhost.idlscriptable please add a summary to this article. ...
... dom/plugins/base/nsipluginhost.idlscriptable please add a summary to this article. ...
...rts last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview nsifile createtempfiletopost(in string apostdataurl); native code only! void createtmpfiletopost(in string apostdataurl, out string atmpfilename); native code only! obsolete since gecko 2.0 void deletepluginnativewindow(in nspluginnativewindowptr apluginnativewindow); native code only! void destroy(); native code only! void findproxyforurl(in string aurl, out string aresult); native code only! nsiplugin getplugin(in string amimetype); native code only! void getplugincount(out unsigned long aplugincount); obsolete since gecko 1.8 nsiplugin getpluginfactory(in string amimetype); native code only! obsolete since gecko 1.9.2 ...
...And 21 more matches
Xray vision
xray vision helps javascript running in a privileged security context safely access objects created by less privileged code, by showing the caller only the native version of the objects. gecko runs javascript from a variety of different sources and at a variety of different privilege levels. the javascript code that along with the c++ core, implements the browser itself is called chrome code and runs using system privileges. if chrome-privileged code is compromised, the attacker can take over the user's computer. javascript loaded from normal web pages is called content code. because this code is being loaded from arbitrary web pages, it is regarded as untrusted and potentially hostile, both to other websites and to the user. as well as these two levels of privilege, chrome cod...
.... because this code is being loaded from arbitrary web pages, it is regarded as untrusted and potentially hostile, both to other websites and to the user. as well as these two levels of privilege, chrome code can create sandboxes. the security principal defined for the sandbox determines its privilege level. if an expanded principal is used, the sandbox is granted certain privileges over content code and is protected from direct access by content code. the security machinery in gecko ensures that there's asymmetric access between code at different privilege levels: so for example, content code can't access objects created by chrome code, but chrome code can access objects created by content. however, even the ability to access content objects can be a security risk for chrome code. javas...
...ts created by chrome code, but chrome code can access objects created by content. however, even the ability to access content objects can be a security risk for chrome code. javascript's a highly malleable language. scripts running in web pages can add extra properties to dom objects (also known as expando properties) and even redefine standard dom objects to do something unexpected. if chrome code relies on such modified objects, it can be tricked into doing things it shouldn't. for example: window.confirm() is a dom api that's supposed to ask the user to confirm an action, and return a boolean depending on whether they clicked "ok" or "cancel". ...
...And 21 more matches
Introduction to events - Learn web development
ts, how they work in browsers, and how events may differ in different programming environments. a series of fortunate events as mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs. for example, in an airport, when the runway 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 ...
...ent. the user chooses a key on the keyboard. the user resizes or closes the browser window. a web page finishes loading. a form is submitted. a video is played, paused, or finishes. an error occurs. you can gather from this (and from glancing at the mdn event reference) that there are a lot of events that can be responded to. each available event has an event handler, which is a block of code (usually a javascript function that you as a programmer create) that runs when the event fires. when such a block of code is defined to run in response to an event, we say we are registering an event handler. note: event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. the listener listens out ...
... note: web events are not part of the core javascript language — they are defined as part of the apis built into the browser. a simple example let's look at a simple example of what we mean here. ...
...And 20 more matches
Setting up your own test automation environment - Learn web development
specific configuration options for browsers to be tested, for example you can set a specific version and os to test in the forbrowser() method: let driver = new webdriver.builder() .forbrowser('firefox', '46', 'mac') .build(); you could also set these options using an environment variable, for example: selenium_browser=firefox:46:mac let's create a new test to allow us to explore this code as we talk about it. inside your selenium test project directory, create a new file called quick_test.js, and add the following code to it: var webdriver = require('selenium-webdriver'), by = webdriver.by, until = webdriver.until; var driver = new webdriver.builder() .forbrowser('firefox') .build(); getting the document you want to test to load the page you actually want to te...
... features in this section and the ones below it. you can use any url to point to your resource, including a file:// url to test a local document: driver.get('file:///users/chrismills/git/learning-area/tools-testing/cross-browser-testing/accessibility/fake-div-buttons.html'); or driver.get('http://localhost:8888/fake-div-buttons.html'); but it is better to use a remote server location so the code is more flexible — when you start using a remote server to run your tests (see later on), your code will break if you try to use local paths. add this line to the bottom of quick_test.js now: driver.get('http://mdn.github.io/learning-area/tools-testing/cross-browser-testing/accessibility/native-keyboard-accessibility.html'); interacting with the document now we've got a document to test, w...
...etc. the actual selection is done by the findelement() method, which accepts as a parameter a selection method. for example, to select an element by id: const element = driver.findelement(by.id('myelementid')); one of the most useful ways to find an element by css — the by.css method allows you to select an element using a css selector enter the following at the bottom of your quick_test.js code now: const button = driver.findelement(by.css('button:nth-of-type(1)')); testing your element there are many ways to interact with your web documents and elements on them. you can see useful common examples starting at getting text values on the webdriver docs. if we wanted to get the text inside our button, we could do this: button.gettext().then(function(text) { console.log('button text ...
...And 20 more matches
XPIDL
array<t> const nstarray<t>& nstarray<t>& array the c++-exposed type t will be an owned variant. (e.g. ns[c]string, refptr<t>, or uint32_t) string, wstring, [ptr] native and [ref] native ar...
...nt to use this type but autf8string or acstring unsigned long uint32_t uint32_t* number unsigned long long uint64_t uint64_t* number unsigned short uint16_t uint16_t* number wchar char16_t char16_t* string full unicode set permitted wstring const char16_t* char16_t** string full unicode set permitted most of the time you don't want to use this type but astring. array<t> const nstarray<t>& nstarray<t>& array the c++-exposed type t will be an owned variant. (e.g. ns[c]string, refptr<t>, or uint32_t) string, wstring, [ptr] native and [ref] native are unsupported as element types. in addition to this list, nearly every idl file incl...
... ? nscidptr const nscid* nscid** ? nsiid const nsiid nsiid* ? nsid const nsid nsid* ? nscid const nscid nscid* ? ...
...And 20 more matches
Debugger.Frame - Firefox Developer Tools
al environment in which the execution is taking place, and so on. for a given debugger instance, spidermonkey creates only one debugger.frame instance for a given visible frame. every handler method called while the debuggee is running in a given frame is given the same frame object. similarly, walking the stack back to a previously accessed frame yields the same frame object as before. ...
...debuggee is running in a given frame is given the same frame object. similarly, walking the stack back to a previously accessed frame yields the same frame object as before. debugger code can add its own properties to a frame object and expect to find them later, use == to decide whether two expressions refer to the same frame, and so on. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.frame instance for a given frame. ...
...ck back to a previously accessed frame yields the same frame object as before. debugger code can add its own properties to a frame object and expect to find them later, use == to decide whether two expressions refer to the same frame, and so on. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.frame instance for a given frame. ...
...And 20 more matches
sslerr.html
this page is part of the ssl reference that we are migrating into the format described in the mdn style guide. if you are inclined to help with this migration, your help would be very much appreciated. upgraded documentation may be found in the current nss reference nss and ssl error codes chapter 8 nss and ssl error codes nss error codes are retrieved using the nspr function pr_geterror. in addition to the error codes defined by nspr, pr_geterror retrieves the error codes described in this chapter. ssl error codes sec error codes ssl error codes table 8.1 error codes defined in sslerr.h constant value description ssl_error_export_only_server -12288 "unable to communicate securely. peer does not support high-grade encryption." ...
...284 "unable to communicate securely with peer: peers's certificate was rejected." a certificate was received from the remote system and was passed to the certificate authentication callback function provided by the local application. that callback function returned secfailure, and the bad certificate callback function either was not configured or did not choose to override the error code returned by the certificate authentication callback function. -12283 (unused) ssl_error_bad_client -12282 "the server has encountered bad data from the client." this error code should occur only on sockets that are acting as servers. it is a generic error, used when none of the other more specific error codes defined in this file applies. ...
...error_bad_client -12282 "the server has encountered bad data from the client." this error code should occur only on sockets that are acting as servers. it is a generic error, used when none of the other more specific error codes defined in this file applies. ssl_error_bad_server -12281 "the client has encountered bad data from the server." this error code should occur only on sockets that are acting as clients. it is a generic error, used when none of the other more specific error codes defined in this file applies. ssl_error_unsupported_certificate_type -12280 "unsupported certificate type." the operation encountered a certificate that was not one of the well known certificate types handled by the certificate library...
...And 19 more matches
mozIStorageStatement
boolean step(); void execute(); attributes attribute type description columncount unsigned long number of columns returned. read only. parametercount unsigned long number of parameters. read only. params mozistoragestatementparams the current list of named parameters, which may be set. only available to javascript code. read only. row mozistoragestatementrow the current row, with access to all data members by name. available only to javascript code. read only. state long the current state defined by mozistoragestatement.moz_storage_statement_invalid, mozistoragestatement.moz_storage_statement_ready, or mozistoragestatement.moz_storage_statement_executing. read only. statem...
...istoragestatement clone(); return value a mozistoragestatement that is a copy of the current statement. getparametername() obtains the name of the parameter for the specified index. autf8string getparametername( in unsigned long aparamindex ); parameters aparamindex the zero-based numerical index for the parameter to be bound. this will be one less than the number used in the sql (<code>?1</code> maps to <code>0</code>, and so on). return value an autf8string representing the parameter name for the specified index. getparameterindex() obtains the index of the parameter with the specified name. this method was added in 1.9.0. in 1.8.1 you had to use getparameterindexes(). see bug 388048 for details. unsigned long getparameterindex( in autf8string aname ); parameters ...
...meterindex( in autf8string aname ); parameters aname name of the parameter to get the index for. for parameter 'foo', name's format is ':foo' in 1.9.0 and 1.9.1. in 1.9.2 the ':' was dropped and name's value should be just 'foo'. see bug 528166 for details. return value the zero-based numerical index for the parameter to be bound. this will be one less than the number used in the sql (<code>?1</code> maps to <code>0</code>, and so on). getcolumnname() obtains the name of the column for the specified index. autf8string getcolumnname( in unsigned long acolumnindex ); parameters acolumnindex the zero-based numerical index for the column to get data from. return value an autf8string with the of the column name for the specified index. getcolumnindex() obtains the ind...
...And 19 more matches
nsITextInputProcessor
lizes dom events from minimum information, and doesn't dispatch some events if they are not necessary. this means that even when gecko changes the dom event behavior, it may not be necessary that the users of this interface need to be updated, i.e., the implementation of this class can be a cushion from the impact of gecko's change. you can create an instance of this interface with the following code: var tip = components.classes["@mozilla.org/text-input-processor;1"]. createinstance(components.interfaces.nsitextinputprocessor); next, you need to get the rights to create composition or dispatch keyboard events with begininputtransaction() or begininputtransactionfortests(): if (!tip.begininputtransaction(window, callback)) { return; } if begininputtransaction() or begininp...
... commit string with its argument: tip.commitcompositionwith("foo-bar-buzz"); when you cancel composition, just do this: tip.cancelcomposition(); when you dispatch keydown event (and one or more keypress events), just do this: var keyevent = new keyboardevent("", // type attribute value should be empty. { key: "enter", // required. code: "enter", // optional. keycode: keyboardevent.dom_vk_return, // required if printable key, but optional if non-printable key. location: keyboardevent.dom_vk_standard, // optional, may be computed from code attribute value. repeat: false, // optional. }); // the other attributes are ...
...le key. location: keyboardevent.dom_vk_standard, // optional, may be computed from code attribute value. repeat: false, // optional. }); // the other attributes are always ignored. var dodefault = tip.keydown(keyevent); when you dispatch keyup event, just do this: var keyevent = new keyboardevent("", { key: "a", code: "keya", keycode: keyboardevent.dom_vk_a }); var dodefault = tip.keyup(keyevent); startcomposition(), flushpendingcomposition(), commitcomposition(), commitcompositionwith(), and cancelcomposition() can take a keyboardevent which causes modifying the composition state. specifying a keyboard event is strongly recommended if the textinputprocessor emulates input from keyboard. for example: tip.
...And 19 more matches
Debugger - Firefox Developer Tools
value indicating whether this debugger instance’s handlers, breakpoints, and the like are currently enabled. it is an accessor property with a getter and setter: assigning to it enables or disables this debugger instance; reading it produces true if the instance is enabled, or false otherwise. this property is initially true in a freshly created debugger instance. this property gives debugger code a single point of control for disentangling itself from the debuggee, regardless of what sort of events or handlers or “points” we add to the interface. allowunobservedasmjs a boolean value indicating whether asm.js code running inside this debugger instance’s debuggee globals is invisible to debugger api handlers and breakpoints. setting this to false inhibits the ahead-of-time asm.j...
...this is an accessor property with a getter and setter. it is initially false in a freshly created debugger instance. ...
.... setting this flag to true is intended for uses of subsystems of the debugger api (e.g, debugger.source) for purposes other than step debugging a target javascript program. allowwasmbinarysource a boolean value indicating whether webassembly sources will be available in binary form. the webassembly text generation will be disabled. ...
...And 19 more matches
eval() - JavaScript
warning: executing javascript from a string is an enormous security risk. it is far too easy for a bad actor to run arbitrary code when you use eval(). see never use eval()!, below. the eval() function evaluates javascript code represented as a string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax eval(string) parameters string a string representing a javascript expression, statement, or sequence of statements. the expression can include variables and properties of existing objects. return value the completion value of evaluating the given code. if the completion value is empty, undefined is ret...
...tation in a generic fashion by using tostring(). var expression = new string('2 + 2'); eval(expression.tostring()); // returns 4 if you use the eval function indirectly, by invoking it via a reference other than eval, as of ecmascript 5 it works in the global scope rather than the local scope. this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called. function test() { var x = 2, y = 4; console.log(eval('x + y')); // direct call, uses local scope, result is 6 var geval = eval; // equivalent to calling eval in the global scope console.log(geval('x + y')); // indirect call, uses global scope, throws referenceerror because `x` is undefined ...
... = 4; console.log(eval('x + y')); // direct call, uses local scope, result is 6 var geval = eval; // equivalent to calling eval in the global scope console.log(geval('x + y')); // indirect call, uses global scope, throws referenceerror because `x` is undefined (0, eval)('x + y'); // another example of indirect call } never use eval()! ...
...And 19 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
draft this page is not complete. « previousnext » fixme: we should include a link to the mdc list of snippets fixme: we need to add a part about 'why and how to create your own component' c++/js this document was authored by hiroshi shimoda of clear code inc. 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. introduction javascript lacks functions for opening files and character-code conversion, among other things. a different mechanism is needed to perform these functions. internet explorer handles this using activex; in firefox, we use the cross-platform component ob...
... extension will be packaged with a special xpcom component developed specifically for it. note: if you're developing components in c++ or other compiled languages, be sure to include binaries for every platform. reference materials to get an idea of what kinds of functions embedded xpcom can handle, take a look at the api reference and the interface definitions from xpidl in the actual source code. note: interface definition language (idl) is a language for giving standard definitions of objects, methods, and so forth. the xpidl (cross-platform idl) used by mozilla is a partial extension to the corba idl. you can perform a full-text search of the firefox source code in mozilla cross-reference using character strings, filenames, etc as search keys. if you’re having trouble with any of ...
...g standard definitions of objects, methods, and so forth. the xpidl (cross-platform idl) used by mozilla is a partial extension to the corba idl. you can perform a full-text search of the firefox source code in mozilla cross-reference using character strings, filenames, etc as search keys. if you’re having trouble with any of the details of the interface, it is helpful to search on the source code for usage examples within firefox. note: to look at the firefox 3 source code, choose "firefox 3" in the starting points list. for firefox 3.5 choose "mozilla 1.9.1." for the current development trunk of firefox, choose "mozilla central" and for thunderbird, choose "comm. central". calling xpcom from xpconnect use the xpconnect technology to use xpcom in javascript. listing 1 shows how you c...
...And 18 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
ference file is located in $install_dir_moz_app/defaults/pref, for example in thunderbird this would be repectively for windows/linux: c:\program files\mozilla thunderbird\defaults\pref /usr/lib/thunderbird/default/pref ( it used to be in /usr/lib/thunderbird-version#/default/pref as in /usr/lib/thunderbird-5/default/pref ) for the record/history purpose ... the old netscape 4.x the file is encoded (byte-shift/rotary is 7), and the presence of the file (netscape.cfg) in the mozilla_home directory suffices for it to be read and executed. for mozilla 1.x.x, firefox, thunderbird or netscape 7 it is still a javascript file, the byte-shift is 13 by default, but can be removed using the pref("general.config.obscure_value", 0); preference in any appropriate .js file dedicated to autoconfig (here ...
...up: # cat /usr/lib/thunderbird/defaults/pref/tb-autoconf.js // 20100526 - modification autoconfig jehan. // pref("general.config.obscure_value", 0); // for mcd .cfg files pref('general.config.filename', 'thunderbird.cfg'); // for mcd .cfg files it used to be in previous releases (up until 7.0) in /usr/lib/thunderbird-x.0/default/pref/autoconf.js the first pref just tells us that we won't encode the file (no more rotary 13 or 7 cf below), the second pref is the name of the file to be read: /usr/lib/thunderbird/thunderbird.cfg. (or firefox.cfg if for firefox...) file encoding if needed, the encoding can be done with the perl script: moz-byteshift.pl available at http://www.alain.knaff.lu/howto/mozi...z-byteshift.pl. for netscape 4.x the convert function from the client customization ki...
...mail.smtpserver.smtp1.username", ""); lockpref("mail.smtpservers", "smtp1"); lockpref("mail.startup.enabledmailcheckonce", true); lockpref("mailnews.quotingprefs.version", 1); lockpref("mailnews.ui.threadpane.version", 5); /* 3) define here (because if set after "4)" below it doesn't work!) processldapvalues which is eventually called by getldapattributes() just below, check getldapattributes() code from $mozilla_home/defaults/autoconfig/prefcalls.js to see the inside call to "user defined" processldapvalues */ function processldapvalues(values) { if(values) { // set the global var with the values returned from the ldap query ldap_values = values; var uid = getldapvalue(values, "uid"); var cn = getldapvalue(values, "cn"); var mail = getldapvalue(values, "mail"); var...
...And 18 more matches
LiveConnect Overview - Archive of obsolete content
the chapter assumes you are familiar with java programming. working with wrappers in javascript, a wrapper is an object of the target language data type that encloses an object of the source language. when programming in javascript, you can use a wrapper object to access methods and fields of the java object; calling a method or accessing a property on the wrapper results in a call on the java object. on the java side, javascript objects are wrapped in an instance of the class netscape.javascript.jsobject and passed to java. ...
...a communication when you refer to a java package or class, or work with a java object or array, you use one of the special liveconnect objects. all javascript access to java takes place with these objects, which are summarized in the following table. table 9.1 the liveconnect objects object description javaarray a wrapped java array, accessed from within javascript code. javaclass a javascript reference to a java class. javaobject a wrapped java object, accessed from within javascript code. javapackage a javascript reference to a java package. note: because java is a strongly typed language and javascript is weakly typed, the javascript runtime engine converts argument values into the appropriate data types for the other...
...de shortcuts for commonly used java packages. for example, you can use the following: var mystring = new java.lang.string("hello world"); instead of the longer version: var mystring = new packages.java.lang.string("hello world"); working with java arrays when any java method creates an array and you reference that array in javascript, you are working with a javaarray. for example, the following code creates the javaarray x with ten elements of type int: var x = java.lang.reflect.array.newinstance(java.lang.integer, 10); like the javascript array object, javaarray has a length property which returns the number of elements in the array. unlike array.length, javaarray.length is a read-only property, because the number of elements in a java array are fixed at the time of creation. package and c...
...And 18 more matches
Server-side web frameworks - Learn web development
nses, and what a server-side web application needs to do in order to respond to requests from a web browser. with this knowledge under our belt, it's time to explore how web frameworks can simplify these tasks, and give you an idea of how you'd choose a framework for your first server-side web application. prerequisites: basic computer literacy. basic understanding of how server-side code handles and responds to http requests (see client-server overview). objective: to understand how web frameworks can simplify development/maintenance of server-side code and to get readers thinking about selecting a framework for their own development. the following sections illustrate some points using code fragments taken from real web frameworks. don't be concerned if it does...
... overview server-side web frameworks (a.k.a. "web application frameworks") are software frameworks that make it easier to write, maintain and scale web applications. ...
...meworks (not every framework will necessarily provide all of these features!). work directly with http requests and responses as we saw in the last article, web servers and browsers communicate via the http protocol — servers wait for http requests from the browser and then return information in http responses. web frameworks allow you to write simplified syntax that will generate server-side code to work with these requests and responses. this means that you will have an easier job, interacting with easier, higher-level code rather than lower level networking primitives. the example below shows how this works in the django (python) web framework. every "view" function (a request handler) receives an httprequest object containing request information, and is required to return an httprespo...
...And 18 more matches
OS.File for the main thread
this page details how to use file i/o from the main thread. for other uses of os.file, please see the corresponding page. using os.file from a jsm to import os.file into your chrome code, add the following line at the start of your script: components.utils.import("resource://gre/modules/osfile.jsm") promises before using os.file from the main thread, you need some understanding of the promise library. see the promise object documentation for details. also, os.file plays very nicely with task.jsm. ...
...he main thread, you need some understanding of the promise library. see the promise object documentation for details. also, os.file plays very nicely with task.jsm. example: read the contents of a file as text the following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8). the content is read asynchronously. the result is a promise. let decoder = new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version. example: write a string to a file the followi...
...or a more recent version. example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8). ...
...And 18 more matches
NSS API Guidelines
nss api guidelines newsgroup: mozilla.dev.tech.crypto introduction this document describes how the nss code is organized, the libraries that get built from the nss sources, and guidelines for writing nss code. these guidelines will familiarize you with some of the ways things can be done in the nss code. this will help you understand existing nss code. it should also help you understand how to write new code, and where to place it. some of the guidelines in this document, are more forward-looking than documentary. these rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. nss api structure this section explains the structure and relationships of the nss libraries. the layering section explains h...
...the libraries section descibes the nss libraries, the functionality each provides, and the layer in which the library (mostly) operates. layering each separate component of the api should live in its own layer. the functions in these apis should never call api layers above them. ...
...apis may be completely opaque to higher level layers. that is, access to these functions should only be provided by the api directly above them. the nss apis are layered, as shown in this diagram: the boxes in the gray section, towards the center, are exported only through pkcs #11. 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 dia...
...And 18 more matches
nsIFile
e state of any file or directory at the position represented by the nsifile and create, move or copy items in the filesystem. an nsifile can be retrieved by either instantiating an nsilocalfile using a platform specific path string or by using cross-platform locations retrieved from the directory service. all methods with string parameters have two forms. the preferred form operates on utf-16 encoded characters strings. an alternate form operates on characters strings encoded in the "native" charset. a string containing characters encoded in the native charset cannot be safely passed to javascript via xpconnect. therefore, the utf-16 forms are scriptable, but the "native methods" are not. in addition, the native form cannot deal with files whose name contains characters outside the default s...
...therefore, you must not use the native form unless it is guaranteed that the path passed to a native form function is always ascii. ...
...therefore, you must not use the native form unless it is guaranteed that the path passed to a native form function is always ascii. ...
...And 18 more matches
nsIPrincipal
urity context. on the web, for example, a typical principal is comprised of an url scheme, host, and port. inherits from: nsiserializable last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for details on principals, how they work, and how to get the appropriate one, see security check basics. ...
... 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for details on principals, how they work, and how to get the appropriate one, see security check basics. ...
...how to get the appropriate one, see security check basics. ...
...And 18 more matches
Writing WebSocket servers - Web APIs
erver. a websocket server is explained on a very low level here. websocket servers are often separate and specialized servers (for load-balancing or other practical reasons), so you will often use a reverse proxy (such as a regular http server) to detect websocket handshakes, pre-process them, and send those clients to a real websocket server. this means that you don't have to bloat your server code with cookie and authentication handlers (for example). the websocket handshake first, the server must listen for incoming socket connections using a standard tcp socket. depending on your platform, this may be handled for you automatically. for example, let's assume that your server is listening on example.com, port 8000, and your socket server responds to get requests at example.com/chat. wa...
...ge may never be displayed (browsers do not display it). if the server doesn't understand that version of websockets, it should send a sec-websocket-version header back that contains the version(s) it does understand. in the example above, it indicates version 13 of the websocket protocol. the most interesting header here is sec-websocket-key. let's look at that next. note: regular http status codes can be used only before the handshake. after the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec). server handshake response when the server receives the handshake request, it should send back a special response that indicates that the protocol will be changing from http to websocket. that header looks something like the following (remember eac...
... websockets connection but interprets the data as a http request. so if the key was "dghlihnhbxbszsbub25jzq==", the sec-websocket-accept header's value is "s3pplmbitxaq9kygzzhzrbk+xoo=". once the server sends these headers, the handshake is complete and you can start swapping data! note: the server can send other headers like set-cookie, or ask for authentication or redirects via other status codes, before sending the reply handshake. keeping track of clients this doesn't directly relate to the websocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have already completed the handshake. the same client ip address can try to connect multiple times. however, the server can deny them if they at...
...And 18 more matches
Functions - JavaScript
ng functions function declarations a function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: the name of the function. a list of parameters to the function, enclosed in parentheses and separated by commas. the javascript statements that define the function, enclosed in curly brackets, {...}. for example, the following code defines a simple function named square: function square(number) { return number * number; } the function square takes one parameter, called number. the function consists of one statement that says to return the parameter of the function (that is, number) multiplied by itself. the statement return specifies the value returned by the function: return number * number; primitive parameters (s...
...pressions are convenient when passing a function as an argument to another function. the following example shows a map function that should receive a function as first argument and an array as second argument. function map(f, a) { let result = []; // create a new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } in the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument. function map(f, a) { let result = []; // create a new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } const f = function(x) { return x * x * x; } let numbers = [0, 1, 2, 5, 10]; let ...
...s the specified actions with the indicated parameters. for example, if you define the function square, you could call it as follows: square(5); the preceding statement calls the function with an argument of 5. the function executes its statements and returns the value 25. functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code), as in this example: console.log(square(5)); /* ... */ function square(n) { return n * n } the scope of a function is the function in which it is declared (or the entire program, if it is declared at the top level). note: this works only when defining the function using the above syntax (i.e. function funcname(){}). the code below will not work. this means that function hoisting only works...
...And 18 more matches
JavaScript Daemons Management - Archive of obsolete content
the following daemons management framework is the major version of setinterval – a little framework. introduction sometimes a page uses dozens and dozens of animations. ...
...ally a clone of it. the architecture of the daemon constructor explicitly avoids the use of closures. it also offers an alternative way to pass the this object to the callback functions (see the "this" problem for details). ...
...ne of it. the architecture of the daemon constructor explicitly avoids the use of closures. it also offers an alternative way to pass the this object to the callback functions (see the "this" problem for details). advantages of this approch: abstraction passage of this object to javascript timers (both setinterval and settimeout) optimisation (avoiding closures) modularity the code the code of this framework is split into three files: daemon.js (the core) daemon-safe.js (an extension of the core which adds a replacement of setinterval with a recursive invocation of settimeout) daemon-methods.js (a wide and highly scalable collection of methods) the only independent module is daemon.js: both the daemon-safe.js module and the daemon-methods.js module require daemon.js to work. ...
...And 17 more matches
Tabbed browser - Archive of obsolete content
multiple meanings for the word 'browser' the word 'browser' is used several ways. of course the entire application firefox is called "a browser". ...
... multiple meanings for the word 'browser' the word 'browser' is used several ways. of course the entire application firefox is called "a browser". ...
... multiple meanings for the word 'browser' the word 'browser' is used several ways. of course the entire application firefox is called "a browser". ...
...And 17 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
mended mechanism to invoke plugins. its use is subject to a few caveats that this section outlines. traditionally, the object element has been used differently by microsoft internet explorer and by mozilla-based browsers such as netscape 7. in ie, the object element is used to invoke a plugin that is built on the activex architecture. ...
...s that this section outlines. traditionally, the object element has been used differently by microsoft internet explorer and by mozilla-based browsers such as netscape 7. in ie, the object element is used to invoke a plugin that is built on the activex architecture. ...
...ove example, the classid attribute that goes along with the object element points to a "clsid:" urn followed by the unique identifier of an activex control (in the above example, the string beginning with "d27..."). this is, in fact, the unique identifier of macromedia's flash plugin, and developers are expected to know such unique identifiers in order to invoke the component of their choice. the codebase attribute used above points to a location that houses the cab file containing the activex control. in this context, the codebase attribute is used as an obtainment mechanism -- that is to say, a way to obtain a control if it isn't present. if the flash activex control is not installed, ie will then go to the url referenced by the codebase attribute and retrieve the activex control. additional...
...And 17 more matches
Images in HTML - Learn web development
pyright violations are illegal and unethical. in addition, never point your src attribute at an image hosted on someone else's website that you don't have permission to link to. this is called "hotlinking". again, stealing someone's bandwidth is illegal. it also slows down your page, leaving you with no control over whether the image is removed or replaced with something embarrassing. ...
...ing. our above code would give us the following result: note: elements like <img> and <video> are sometimes referred to as replaced elements. this is because the element's content and size are defined by an external resource (like an image or video file), not by the contents of the element itself. note: you can find the finished example from this section running on github (see the source code too.) alternative text the next attribute we'll look at is alt. its value is supposed to be a textual description of the image, for use in situations where the image cannot be seen/displayed or takes a long time to render because of a slow internet connection. ...
...ment itself. note: you can find the finished example from this section running on github (see the source code too.) alternative text the next attribute we'll look at is alt. its value is supposed to be a textual description of the image, for use in situations where the image cannot be seen/displayed or takes a long time to render because of a slow internet connection. for example, our above code could be modified like so: <img src="images/dinosaur.jpg" alt="the head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"> the easiest way to test your alt text is to purposely misspell your filename. if for example our image name was spelled dinosooooor.jpg, the browser wouldn't display the image, and would display the alt text instead: so, why woul...
...And 17 more matches
Choosing the right approach - Learn web development
een completed, so that the callback can in turn do something with the result. this is the precursor to promises; it's not as efficient or flexible. use only when necessary. useful for... ...
...g asynchronous javascript, in particular async callbacks settimeout() settimeout() is a method that allows you to run a function after an arbitrary amount of time has passed. useful for... ...
...assed. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations yes yes (recursive timeouts) yes (nested timeouts) no code example here the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr. ...
...And 17 more matches
Build your own function - Learn web development
the essential theory dealt with in the previous article, this article provides practical experience. here you will get some practice building your own, custom function. along the way, we'll also explain some useful details of dealing with functions. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code. objective: to provide some practice in building a custom function, and explain a few more useful associated details. active learning: let's build a function the custom function we are going to build will be called displaymessage(). it will display a custom message box on a web page and will act as a customized replacement for a browser's built-in alert() function. we've seen ...
...pt> element to put our javascript in. next, add the following inside the <script> element: function displaymessage() { } we start off with the keyword function, which means we are defining a function. this is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. ...
...ion displaymessage() { } we start off with the keyword function, which means we are defining a function. this is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the curly braces. ...
...And 17 more matches
Introduction to client-side frameworks - Learn web development
ptimized javascript instructions. angular uses typescript, a superset of javascript that we’ll look at in a little more detail in the next chapter. vue evan you first released vue in 2014, after working on and learning from the original angularjs project. vue is the youngest of the big four, but has enjoyed a recent uptick in popularity. vue, like angularjs, extends html with some of its own code. apart from that, it mainly relies on modern, standard javascript. start learning vue react facebook released react in 2013. by this point, it had already been using react to solve many of its problems internally. react itself is not technically a framework; it's a library for rendering ui components. react is used in combination with other libraries to make applications — react and react na...
... cracks start to show. the real problem is this: every time we change our application’s state, we need to update the ui to match. we can examine the difficulty of this problem by looking at just one feature of our todo list app: rendering a list of tasks. the verbosity of dom changes building html elements and rendering them in the browser at the appropriate time takes a surprising amount of code. let's say that our state is an array of objects structured like this: const state = [ { id: 'todo-0', name: 'learn some frameworks!' } ] how do we show one of those tasks to our user? we want to represent each task as a list item – an html <li> element inside of an unordered list element (a <ul>). how do we make it? that could look something like this: function buildtodoitemel(i...
... the tenth line of this snippet references another build function: builddeletebuttonel(). it follows a similar pattern to the one we used to build a list item element: function builddeletebuttonel(id) { const button = document.createelement('button'); const textcontent = document.createtextnode('delete'); button.setattribute('type', 'button'...
...And 17 more matches
Handling common HTML and CSS problems - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross browser testing. ...
... prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high level principles of cross browser testing. ...
...gh level principles of cross browser testing. objective: to be able to diagnose common html and css cross browser problems, and use appropriate tools and techniques to fix them. the trouble with html and css some of the trouble with html and css lies with the fact that both languages are fairly simple, and often developers don't take them seriously, in terms of making sure the code is well-crafted, efficient, and semantically describes the purpose of the features on the page. in the worst cases, javascript is used to generate the entire web page content and style, which makes your pages inaccessible, and less performant (generating dom elements is expensive). in other cases, nascent features are not supported consistently across browsers, which can make some features and st...
...And 17 more matches
Eclipse CDT Manual Setup
etup most people should be reading the eclipse cdt page instead of this one, now that mach ide eclipse is a thing. this page contains the content that used to live on the eclipse cdt page that most people will likely just consider noise. there is valuable information here that should be integrated back into that page, but a large amount of it is now taken care of by the mach project generation code. for now it's stored here until that integration happens in order that the eclipse cdt page isn't hugely cluttered with mostly redundant information, make setting up eclipse look much more complicated than it is nowadays. setup time some points in the rest of this document below are old and taken care of by the mach commands described above (although some of the project configuration is not d...
...these instructions if you're doing so for the first time. (this assumes that you already have a copy of the mozilla source, and that you have also built the source so that you have a pre-existing object directory. if that is not the case, then get your build going now so that it can be running while you continue with the instructions below. faq: wait, why does eclipse need an object directory?) code assistance out of the box, eclipse can provide some code assistance for the mozilla source, but it will be incomplete and often just plain broken. if you set up eclipse as detailed below, you will experience much better results. important background to help you make sense of the instructions that follow (and so that you can modify them to meet your own needs if necessary), this section provide...
...ance for the mozilla source, but it will be incomplete and often just plain broken. if you set up eclipse as detailed below, you will experience much better results. ...
...And 17 more matches
Using XPCOM Utilities to Make Things Easier
xpcom macros the xpcom framework includes a number of macros for making c++ development easier. ...
... xpcom macros the xpcom framework includes a number of macros for making c++ development easier. ...
... xpcom macros the xpcom framework includes a number of macros for making c++ development easier. though they overlap somewhat (e.g., high-level macros expand to other macros), they fall into the following general categories. ...
...And 17 more matches
Debugger.Object - Firefox Developer Tools
s (perhaps two functions are called on the same object), spidermonkey presents the same debugger.object instance to the debugger each time. this means that the debugger can use the == operator to recognize when two debugger.object instances refer to the same debuggee object, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. ...
...ct instance to the debugger each time. this means that the debugger can use the == operator to recognize when two debugger.object instances refer to the same debuggee object, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. javascript code in different compartments can have different views of the same object. ...
...o the same debuggee object, and place its own properties on a debugger.object instance to store metadata about particular debuggee objects. javascript code in different compartments can have different views of the same object. for example, in firefox, code in privileged compartments sees content dom element objects without redefinitions or extensions made to that object’s properties by content code. (in firefox terminology, privileged code sees the element through an “xray wrapper”.) to ensure that debugger code sees each object just as the debuggee would, each debugger.object instance presents its referent as it would be seen from a particular compartment. this “viewing compartment” is chosen to match the way the debugger came across the referent. as a consequence, a single debugge...
...And 17 more matches
Debugger.Source - Firefox Developer Tools
debugger.source a debugger.source instance represents either a piece of javascript source code or the serialized text of a block of webassembly code. the two cases are distinguished by the latter having its introductiontype property always being "wasm" and the former having its introductiontype property never being "wasm". each debugger instance has a separate collection of debugger.source instances representing the source code that has been presented to the system. a debugger may place its own properties on debugger.source instances, to store metadata about particular pieces of source code. ...
...ver being "wasm". each debugger instance has a separate collection of debugger.source instances representing the source code that has been presented to the system. a debugger may place its own properties on debugger.source instances, to store metadata about particular pieces of source code. debugger.source for javascript for a debugger.source instance representing a piece of javascript source code, its properties provide the source code itself as a string, and describe where it came from. each debugger.script instance refers to the debugger.source instance holding the source code from which it was produced. ...
...each script indicates the substring of the overall source to which it corresponds. a debugger.source instance may represent only a portion of a larger source document. ...
...And 17 more matches
Index - Firefox Developer Tools
e, and edit the document object model of documents - usually web pages or xul windows. the dom hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within. 7 dom inspector faq dom_inspector the file menu contains approaches which will allow you to inspect a document. 8 dom inspector internals code, tools, internals, organisation, source there are three main facets to dom inspector. the one you are likely to be most familiar with is its inspector.xul-based primary ui. this is the two-pane inspector that appears when ctrl+shift+i (or cmd+shift+i) is pressed from one of the applications for which dom inspector has explicit support (i.e., menuitems placed via overlay). 9 intro...
...refox devtools application panel. 14 browser console browser, debugging, tools, web development, webdevelopment:tools the browser console is like the web console, but applied to the whole browser rather than a single content tab. 15 browser toolbox debug, firefox, javascript the browser toolbox enables you to debug add-ons and the browser's own javascript code rather than just web pages like the normal toolbox. the browser toolbox's context is the whole browser rather than just single page on a single tab. 16 dom property viewer dom, tools, web development the dom property viewer lets you inspect the properties of the dom as an expandable tree structure, starting from the window object of the current page or the selected iframe. ...
...s, web development the dom property viewer lets you inspect the properties of the dom as an expandable tree structure, starting from the window object of the current page or the selected iframe. 17 debugger-api debugger, intermediate, intro, javascript, tools mozilla’s javascript engine, spidermonkey, provides a debugging interface named debugger which lets javascript code observe and manipulate the execution of other javascript code. both firefox’s built-in developer tools and the firebug add-on use debugger to implement their javascript debuggers. however, debugger is quite general, and can be used to implement other kinds of tools like tracers, coverage analysis, patch-and-continue, and so on. 18 debugger when called as a constructor, the...
...And 17 more matches
Background Tasks API - Web APIs
the cooperative scheduling of background tasks api (also referred to as the background tasks api or simply the requestidlecallback() api) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so. concepts and usage the main thread of a web browser is centered around its event loop. ...
...red to as the background tasks api or simply the requestidlecallback() api) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so. concepts and usage the main thread of a web browser is centered around its event loop. this code draws any pending updates to the document currently being displayed, runs any javascript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. in addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. it's an extremely busy chunk of code, and your main javascript code may run right inside this thread along with all of this. certainly m...
... to run, accepts events from input devices, and dispatches those events to the elements that should receive them. in addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. it's an extremely busy chunk of code, and your main javascript code may run right inside this thread along with all of this. certainly most if not all code that is capable of making changes to the dom is running in the main thread, since it's common for user interface changes to only be available to the main thread. because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the web and help to prevent stalls in the execution of the event loop. in t...
...And 17 more matches
JavaScript Object Management - Archive of obsolete content
namespace declaration is best located in a file of its own, so that you have this one js file that should be included in all of your xul files. ...
...namespace declaration is best located in a file of its own, so that you have this one js file that should be included in all of your xul files. ...
...namespace declaration is best located in a file of its own, so that you have this one js file that should be included in all of your xul files. we'll be using the placeholder 〈namespace〉 below. this needs to be replaced with an identifier name which is unique to your add-on. ...
...And 16 more matches
Client-Server Overview - Learn web development
previous overview: first steps next now that you know the purpose and potential benefits of server-side programming we're going to examine in detail what happens when a server receives a "dynamic request" from a browser. as most website server-side code handles requests and responses in similar ways, this will help you understand what you need to do when writing most of your own code. prerequisites: basic computer literacy. a basic understanding of what a web server is. ...
...de code handles requests and responses in similar ways, this will help you understand what you need to do when writing most of your own code. prerequisites: basic computer literacy. a basic understanding of what a web server is. objective: to understand client-server interactions in a dynamic website, and in particular what operations need to be performed by server-side code. there is no real code in the discussion because we haven't yet chosen a web framework to use to write our code! this discussion is however still very relevant, because the described behaviour must be implemented by your server-side code, irrespective of which programming language or web framework you select. web servers and http (a primer) web browsers communicate with web servers using...
...t time a resource was updated, and then only use the (more "expensive") get request to download the resource if it has changed. put: update an existing resource (or create a new one if it doesn't exist). delete: delete the specified resource. trace, options, connect, patch: these verbs are for less common/advanced tasks, so we won't cover them here. additional information can be encoded with the request (for example, html form data). information can be encoded as: url parameters: get requests encode data in the url sent to the server by adding name/value pairs onto the end of it — for example http://mysite.com?name=fred&age=11. you always have a question mark (?) separating the rest of the url from the url parameters, an equals sign (=) separating each name from its ass...
...And 16 more matches
Starting WebLock
somewhat indirect. the only way to register directly for a notification via the observer service is to instantiate an nsiobserver object. this works for most cases, but consider the case when you have this notification create a component. since the component hasn't been created yet, there are no instantiated nsiobserver objects that can be passed into the nsiobserverservice, nor can the component code do anything until it is loaded. registering for notifications the nsiobserverservice interface has methods for registering and unregistering an nsiobserver object. these two methods are used to dynamically add or remove an observer to a notification topic. but weblock needs to be instantiated and added to the observer service automatically, which also implies some sort of persistent data (after...
...o be started up. the category name also maps nicely onto the notion of a notification "topic." the topic name could be something like "xpcom-startup", for instance, and the name-value pair could contain the contract ids required to create the components requesting startup. in fact, this is exactly how categories are used to handle registration with xpcom for startup notification. ...
...the inverse of this function is the unregistration callback, where it's a good idea to undo whatever the registration function did. ...
...And 16 more matches
nsIVariant
ypes. we mark the interface [scriptable] so that js can use methods that refer to this interface. but we mark all the methods and attributes [noscript] since any nsivariant object will be automatically converted to a js type anyway. ...
...erted to a js type anyway. ...
...ged in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview acstring getasacstring(); native code only! nsresult getasarray(out pruint16 type, out nsiid iid, out pruint32 count, out voidptr ptr); violates the xpcom interface guidelines astring getasastring(); native code only! autf8string getasautf8string(); native code only! prbool getasbool(); native code only! char getaschar(); native code only! domstring getasdomstring(); native code only! double getasdouble(); native code only! float getasfloat(); native code only! nsresult getasid(out nsid retval); violates the xpcom interface guidelines print16 ...
...And 16 more matches
nsIWindowMediator
nsisimpleenumerat...
... out nsiwidget outbelow); native code only! nsisimpleenumerator getenumerator(in wstring awindowtype); nsidomwindow getmostrecentwindow(in wstring awindowtype); nsidomwindow getouterwindowwithid(in unsigned long long aouterwindowid); nsisimpleenumerator getxulwindowenumerator(in wstring awindowtype); pruint32 getzlevel(in nsixulwindow awindow); native code only! nsisimpleenumerator getzorderdomwindowenumerator(in wstring awindowtype, in boolean afronttoback); nsisimpleenumerator getzorderxulwindowenumerator(in wstring awindowtype, in boolean afronttoback); void registerwindow(in nsixulwindow awindow); native code only! void removelistener(in nsiwindowmediatorlistener alistener); void setzlevel(in nsixulw...
...rdomwindowenumerator(in wstring awindowtype, in boolean afronttoback); nsisimpleenumerator getzorderxulwindowenumerator(in wstring awindowtype, in boolean afronttoback); void registerwindow(in nsixulwindow awindow); native code only! void removelistener(in nsiwindowmediatorlistener alistener); void setzlevel(in nsixulwindow awindow, in pruint32 azlevel); native code only! void setzposition(in nsixulwindow inwindow, in unsigned long inposition, in nsixulwindow inbelow); native code only! void unregisterwindow(in nsixulwindow awindow); native code only! void updatewindowtimestamp(in nsixulwindow awindow); native code only! void updatewindowtitle(in nsixulwindow awindow, in wstring intitle ); native code only! constant...
...And 16 more matches
nsIXPConnect
js/src/xpconnect/idl/nsixpconnect.idlnot scriptable provides the xpconnect service. ...
...its from: nsisupports last 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); vo...
... obsolete since gecko 2.0 ...
...And 16 more matches
SubtleCrypto.importKey() - Web APIs
the pkcs #8 format is defined in rfc 5208., using the asn.1 notation: privatekeyinfo ::= sequence { version version, privatekeyalgorithm privatekeyalgorithmidentifier, privatekey privatekey, attributes [0] implicit attributes optional } the importkey() method expects to receive this object as an arraybuffer containing the der-encoded form of the privatekeyinfo. der is a set of rules for encoding asn.1 structures into a binary form. you are most likely to encounter this object in pem format. pem format is a way to encode binary data in ascii. it consists of a header and a footer, and in between, the base64-encoded binary data. a pem-encoded privatekeyinfo looks like this: -----begin private key----- mig2ageambagbyqgsm49ageg...
... convert the resulting string into an arraybuffer. see the examples section for more concrete guidance. subjectpublickeyinfo you can use this format to import or export rsa or elliptic curve public keys. subjectpublickey is defined in rfc 5280, section 4.1 using the asn.1 notation: subjectpublickeyinfo ::= sequence { algorithm ...
...o you can use this format to import or export rsa or elliptic curve public keys. ...
...And 16 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
. the chrome manifest plays two important roles: it registers the contents of the chrome packages, and invokes the cross-package overlay. developing a simple extension: hello world in this section, we will write an extremely simple “hello world” extension that only displays the time.3 phase 1: test install our first step will be to perform a test installation consisting of the minimum code needed to add a new menu item to the tools menu (figure 3). fixme: figure 3: menu after phase 1 complete source file structure first set up the work folders you’ll use to organize your extension’s source files. the folder can be wherever you want, but for the purposes of this guide, we’ll assume it’s at c:\extensions\helloworld . create folders and files in your work folder as shown in...
.../description> </em:targetapplication> </description> </rdf> create the chrome manifest fill in the chrome.manifest file as shown in listing 2. listing 2: content for chrome.manifest content helloworld content/ overlay chrome://browser/content/browser.xul chrome://helloworld/content/overlay.xul register the content package (content instruction) line 1, beginning content, contains the code used to register the chrome’s content package. here, helloworld is a package name, and content/ is a relative path to the folder where the source file is stored. registering the content package makes it so that the overlay.xul file in the content folder can be accessed using the chrome url, chrome://helloworld/content/overlay.xul. xul cross-package overlay (overlay instruction) line 2, beginn...
...me’s content package. here, helloworld is a package name, and content/ is a relative path to the folder where the source file is stored. registering the content package makes it so that the overlay.xul file in the content folder can be accessed using the chrome url, chrome://helloworld/content/overlay.xul. xul cross-package overlay (overlay instruction) line 2, beginning overlay, contains the code used to invoke the cross-package overlay, overlaying the firefox browser window, at chrome://browser/content/browser.xul with chrome://helloworld/content/overlay.xul. finding overlay merge points the next step is to find the “merge points” where the overlay document will insert its content into the base document. there are a number of ways to go about this; here, we’ll use the dom inspect...
...And 15 more matches
Appendix D: Loading Scripts - Archive of obsolete content
because there are such a diverse array of add-ons, and because the needs of developers have grown organically over time, the gecko runtime provides a number of means to dynamically load and execute javascript files. each of these means has its own advantages and disadvantages, as well as its own quirks which may trap the unwary. below is an overview of the more common means of loading scripts, along with some of their primary advantages, disadvantages, quirks, and use cases. ...
...utomatically loaded into the context of the xul window in question and executed immediately and synchronously. advantages familiarity: these tags are very similar to the html script tags familiar to most web developers. simplicity: the simple, declarative nature of these tags make them easy to find and understand at a glance. speed: script tags may or may not be loaded from pre-compiled bytecode in the fastload cache (gecko 1.x) or startup cache (gecko 2), which means they don't necessarily need to read as source and compiled with each restart. flexibility: script tags provide a means to specify the character set and javascript version of the scripts to be loaded, which many other methods do not. debuggable: development tools support debugging javascript loaded by script tags disadva...
...oaded by script tags disadvantages scoping: scripts loaded via script tags share the global scope with all other scripts loaded into the same window. these tags provide no means to load scripts into a private or otherwise specific scope. speed: even if these scripts are loaded from a cache, only read and compile time are reduced. the scripts still need to execute all of their initialization code and allocate and initialize all of their data structures each time the script is loaded. loading: script loaded via script tags run in partially loaded documents. problems can ensue if the script immediately attempts to access dom nodes. this is easily resolved by deferring the work to a dynamically added onload hander. (a standalone xul window can use an onload attribute.) example the follow...
...And 15 more matches
JXON - Archive of obsolete content
onvention. it is very similar to the previous one, except that nodes which do not contain other recognizable nodes than text or cdatasection are not treated as objects, but directly as booleans, strings, numbers or date objects (see the parker convention). empty nodes (i.e. which do not contain other element nodes, text nodes, cdatasection nodes or attr nodes) have the default value true (see the code considerations). also, this time we use a function instead of a constructor. the function's argument can be the entire xml document, a documentfragment, or simply an element node within it. nodeattributes have the “@” prefix, as suggested by the badgerfish convention. in many cases, this is the most practical conversion method. /*\ |*| |*| jxon snippet #3 mdndeveloper network |*| |*| https...
...ar myobject = { "employee": new string("john smith"), "manager": "lisa carlucci" }; myobject.employee["@type"] = "usher"; // test alert(myobject.manager); // "lisa carlucci" alert(myobject.employee["@type"]); // "usher" alert(myobject.employee); // "john smith" note: this algorithm represents a special case of conversion. the generated javascript object tree is not stringifyable (see the code considerations). it is very practical for internal javascript access, but don't use it if you want to transfer the tree via json string! as for the third algorithm, nodes which do not contain other recognizable nodes than text or cdatasection are not treated as objects, but directly as booleans, strings, numbers (primitive values) or date objects; and empty nodes (i.e. which do not contain other...
... this is a good solution if you want to automate the creation of an xml document. it is a bad choic...
...And 15 more matches
Building up a basic demo with the PlayCanvas engine - Game development
there is one helpe...
...n-canvas"); /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element that playcanvas will use to 100% so that it will fill the entire available viewport space. the first <script> element includes the playcanvas library in the page; we will write our example code in the second one. there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update loop.
... there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update loop. add the following code to the bottom of your second <script> element: var app = new pc.application(canvas); app.start(); the pc global object contains all the playcanvas functions available in the engine. next, we'll set the canvas to fill the window, and automatically change its resolution to be the same as the canvas size. again, add the following lines at the bottom of your script. app.setcanvasfillmode(pc.fill...
...And 15 more matches
Desktop mouse and keyboard controls - Game development
enabled devices, it would be good to add mouse and keyboard support, so the game can be playable also on desktop. that way we can broaden the list of supported platforms. we'll look at this below. it's also easier to test control-independent features like gameplay on desktop if you develop it there, so you don't have to push the files to a mobile device every time you make a change in the source code. note: the captain rogers: battle at andromeda is built with phaser and managing the controls is phaser-based, but it could also be done in pure javascript. the good thing about using phaser is that it offers helper variables and functions for easier and faster development, but it's totally up to you which approach you chose. pure javascript approach let's think about implementing pure javascr...
...uting the keyuphandler function, so we know when it's no longer pressed. to do that we'll hold the information on whether the keys we are interested in are pressed or not: var rightpressed = false; var leftpressed = false; var uppressed = false; var downpressed = false; then we will listen for the keydown and keyup events and act accordingly in both handler functions. ...
...hen it's no longer pressed. to do that we'll hold the information on whether the keys we are interested in are pressed or not: var rightpressed = false; var leftpressed = false; var uppressed = false; var downpressed = false; then we will listen for the keydown and keyup events and act accordingly in both handler functions. ...
...And 15 more matches
Adding vector graphics to the Web - Learn web development
s. svg is for marking up graphics, not content. at the simplest end of the spectrum, you've got elements for creating simple shapes, like <circle> and <rect>. ...
...for creating svg images, most people use a vector graphics editor like inkscape or illustrator. ...
...for creating svg images, most people use a vector graphics editor like inkscape or illustrator. ...
...And 15 more matches
Debugging on Mac OS X
if you want to debug from the terminal see debugging mozilla with lldb. for specific information on a way to debug hangs, see debugging a hang on os x. creating a debuggable build first, you need to build the application you're going to debug using --disable-optimize--enable-debug-symbols in your .mozconfig (also add --enable-debug if you want assertions etc. compiled in). see building firefox for macos if you need help creating your own build. ...
...tended attribute from the downloaded nightly: $ xattr -r -d com.apple.quarantine /path/to/nightly.app local builds local builds of mozilla-central do not enable hardened runtime and hence do not have debugging restrictions. as a result, some functionality will be permitted on local builds, but blocked on production builds which have hardened runtime enabled. bug 1522409 was filed to automate codesigning local builds to enable hardened runtime by default and eliminate this discrepancy. to obtain a hardened runtime build without using try infrastructure, a developer can manually codesign builds using the macos codesign(1) command with the developer.entitlements.xml file from the tree. this requires creating a codesigning identity. disabling system integrity protection (sip) if debugging ...
...oduction build is required, follow apple's documented steps for disabling system integrity protection (sip). note that disabling sip bypasses hardened runtime restrictions which can mask some bugs that only occur with hardened runtime so it is recommended to test fixes with sip enabled. disabling sip has system security implications that should be understood before taking this step. creating an xcode project if you try to create a new xcode project in an existing directory then xcode will delete its existing contents (xcode will warn you beforehand). to work around that, the steps below have you initialize the project outside the mozilla source tree, close the project, copy the .xcodeproj project "file" into the source tree, and then reopen the project to finish setting it up. note also th...
...And 15 more matches
Creating localizable web applications
an important step of developing a web application or creating web content is making sure that it can be localized. listed below are good practices and recommendations that should be followed in order to make your content easily localizable. note: most of the code snippets used in the examples below come from an early version of the getpersonas.com website. in some cases, the code snippets were slightly changed to better illustrate the recommendations or for clarity. cheatsheet don't hardcode english text, formats (numbers, dates, addresses, etc.), word order or sentence structure. don't put text or numbers in images. don't forget about right-to-left locales. take advantage of printf() (or equivalents) and use variables in the english strings. write semantic code (e.g. don't ...
...rity. cheatsheet don't hardcode english text, formats (numbers, dates, addresses, etc.), word order or sentence structure. don't put text or numbers in images. don't forget about right-to-left locales. take advantage of printf() (or equivalents) and use variables in the english strings. write semantic code (e.g. don't use text and <img/> for decorations; instead, use css). document your code so that localizers know what they're translating (e.g. in gettext use comments and contexts). app logic detect the locale correctly be smart about detecting the user's locale correctly. you can use one or more of the following techniques: http accept-language headers, the ua string, ip geolocation. ...
...ecorations; instead, use css). document your code so that localizers know what they're translating (e.g. in gettext use comments and contexts). app logic detect the locale correctly be smart about detecting the user's locale correctly. you can use one or more of the following techniques: http accept-language headers, the ua string, ip geolocation. see examples of the addons.mozillaorg code at /addons/trunk/site/app/config/language.php and /addons/trunk/site/app/config/language.inc.php. the language_config class expects arrays of valid languages & supported languages. always give the user a possibility to change the locale (e.g. by adding locale dropdown menu at bottom of page) and remember this choice for the future visits. ...
...And 15 more matches
Using the clipboard
l the application has decided what it needs. this allows the clipboard to be used by another application right away. let's break down the steps needed to copy data to the clipboard. first, we need to create an xpcom object to wrap what we want to copy. we'll assume that we want to copy some text. we will use the interface nsisupportsstring which can be used to represent strings (specifically, unicode strings). the following boilerplate utility functions will be used in all later code examples. // import the services module for future use, if we're not in // a browser window where it's already loaded. components.utils.import('resource://gre/modules/services.jsm'); // create a constructor for the built-in supports-string class. const nssupportsstring = components.constructor("@mozilla.org/su...
... .getinterface(ci.nsiwebnavigation); res.init(source); } return res; } here, the string "text to copy" will be copied but you can replace this with the text string that you want to copy. now that we have the object to copy, a transferring object needs to be created: var str = "text to copy"; var trans = transferable(sourcewindow); trans.adddataflavor("text/unicode"); // 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 c...
...t 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 tell the transferable what type of data we want to use. the type of data is referred to as a data flavor. the function adddataflavor is used to tell the transferable that it needs to transfer data of a certain flavor. ...
...And 15 more matches
MIME types (IANA media types) - HTTP
ated with a slash (/) between them, comprise a mime type. no whitespace is allowed in a mime type: type/subtype the type represents the general category into which the data type falls, such as video or text. the subtype identifies the exact kind of data of the specified type the mime type represents. for example, for the mime type text, the subtype might be plain (plain text), html (html source code), or calendar (for icalendar/.ics) files. each type has its own set of possible subtypes, and a mime type always has both a type and a subtype, never just one or the other. an optional parameter can be added to provide additional details: type/subtype;parameter=value for example, for any mime type whose main type is text, the optional charset parameter can be used to specify the character set...
...e. generic binary data (or binary data whose true type is unknown) is application/octet-stream. other common examples include application/pdf, application/pkcs8, and application/zip. audio list at iana audio or music data. examples include audio/mpeg, audio/vorbis. example reserved for use as a placeholder in examples showing how to use mime types. these should never be used outside of sample code listings and documentation. example can also be used as a subtype; for instance, in an example related to working with audio on the web, the mime type audio/example can be used to indicate that the type is a placeholder and should be replaced with an appropriate one when using the code in the real world. font list at iana font/typeface data. common examples include font/woff, font/ttf, and font...
...iana image or graphical data including both bitmap and vector still images as well as animated versions of still image formats such as animated gif or apng. common examples are image/jpeg, image/png, and image/svg+xml. model list at iana model data for a 3d object or scene. examples include model/3mf and model/vml. text list at iana text-only data including any human-readable content, source code, or textual data such as comma-separated value (csv) formatted data. examples include text/plain, text/csv, and text/html. video list at iana video data or files, such as mp4 movies (video/mp4). for text documents without a specific subtype, text/plain should be used. similarly, for binary documents without a specific or known subtype, application/octet-stream should be used. multipart types...
...And 15 more matches
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. ...
...ly does not have an explicit specification. note: although there is a specification document, its markup is based on implementations and markup as of 2001, and current xul differs from it in many aspects. for the latest xul specifications, please see the xul reference on mdc and the xul page in the mozilla wiki. for each element that i explain in this chapter, i will illustrate it with a source code example. you can type these examples up and open them in firefox to see how they behave and appear. you can download a file with all the source code examples from: fixme: attache the translated tarball - paul task !. xul display methods xul is used almost exclusively in mozilla applications like firefox and thunderbird, and extensions for them, but other web browsers based on firefox or the gec...
...xul is used almost exclusively in mozilla applications like firefox and thunderbird, and extensions for them, but other web browsers based on firefox or the gecko engine, and even web-based content also used xul. for example, there is the mozilla amazon browser, which helps with shopping at amazon, and the presentation method in xul, a tool for writing and displaying presentations to try out the code samples in this chapter, save them as text files with .xul extensions and drag and drop them into the firefox browser window. fixme: explain how setting this option and use next listings if we want to run firefox displaying none of its gui and only the contents of a certain xul file, we can launch firefox and set the option: -chrome file_url.xul another way, as shown in listing 1, is to use th...
...And 14 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
browsers, like internet explorer 4, that were built before the conception of w3c standards inherited many quirks. ...
...is and have never added extensive support for the w3c-compliant ones. before i go into the differences between mozilla and internet explorer, i'll cover some basic ways you can make a web application extensible in order to add new browser support later. ...
...liant ones. before i go into the differences between mozilla and internet explorer, i'll cover some basic ways you can make a web application extensible in order to add new browser support later. since different browsers sometimes use different apis for the same functionality, you can often find multiple if() else() blocks throughout the code to differentiate between the browsers. the following code shows blocks designated for internet explorer: . . . var elm; if (ns4) elm = document.layers["myid"]; else if (ie4) elm = document.all["myid"] the above code isn't extensible, so if you want it to support a new browser, you must update these blocks throughout the web application. the easiest way to eliminate the need to recode for a new browser is to abstract out functionality. rather t...
...And 14 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
ke a look at various ssjs implementations and some examples of putting them to use. server-side javascript (ssjs) via embedded javascript engines the extension of javascript to the server is made possible via embedded javascript engines. the two most well established engines are spidermonkey and rhino, both currently maintained by the mozilla foundation. spidermonkey is the code name for the first ever javascript engine, an open source c implementation which can be found embedded in leading software products such as mozilla firefox, adobe acrobat, and aptana jaxer. rhino is a java implementation of javascript which is commonly embedded in java applications to expose scripting capability. the helma web application framework is an example of rhino in use. the dojo toolkit ...
...s querying a mysql database for some employee contact information. it is assumed that you have already downloaded, extracted, and consumed the necessary documentation to get up and running with some basic rhino scripts. if you don’t already have it, you’ll need to also download the jdbc driver for mysql, extract the class files, and include the path in your classpath environment variable. the code in listing 1 is a sample javascript script which incorporates java classes to handle the database query. listing 1 - querying a mysql database from rhino // import the java sql packages importpackage( java.sql ); // load the mysql driver java.lang.class.forname( "com.mysql.jdbc.driver" ); // create connection to the database var conn = drivermanager.getconnection( "jd...
...here, we’re including all the classes in the java.sql namespace in the script. the appropriate database driver for mysql is loaded and the connection string to a database named rhino on my local machine is configured using the user account urhino with the password of prhino. the sql s...
...And 14 more matches
Windows Media in Netscape - Archive of obsolete content
control is supported and available for use. javascript will dynamically write out what browser you are running, and what kind of windows media player technology you may have. ...
...media player technology you may have. example 1: client-side detection scripts browser architecture supports: netscapeplugin windows media player installed: true windows media scriptable: false windows media version: pluginversion a complete source code listing showing how that detection was done can be found here (devedge-temp). ...
...vexobject and activexobject work very similarly, with one key difference: both take a programmatic id (progid) and use it to create a reference to the windows media player. the progid of windows media player is mediaplayer.mediaplayer.1. while the progid cannot be used to create a windows media player object that exposes all its properties and methods, it is useful for rapid detections. ...
...And 14 more matches
JavaScript basics - Learn web development
with javascript is more challenging than getting comfortable with html and css. you may have to start small, and progress gradually. to begin, let's examine how to add javascript to your page for creating a hello world! example. (hello world! is the standard for introductory programming examples.) important: if you haven't been following along with the rest of our course, download this example code and use it as a starting point. go to your test site and create a new folder named scripts. within the scripts folder, create a new file called main.js, and save it. in your index.html file, enter this code on a new line, just before the closing </body> tag: <script src="scripts/main.js"></script> this is doing the same job as the <link> element for css. it applies the javascript to the...
... scripts folder, create a new file called main.js, and save it. in your index.html file, enter this code on a new line, just before the closing </body> tag: <script src="scripts/main.js"></script> this is doing the same job as the <link> element for css. it applies the javascript to the page, so it can have an effect on the html (along with the css, and anything else on the page). add this code to the main.js file: const myheading = document.queryselector('h1'); myheading.textcontent = 'hello world!'; make sure the html and javascript files are saved. then load index.html in your browser. ...
... if the javascript loads first and it is supposed to affect the html that hasn't loaded yet, there could be problems. placing javascript near the bottom of an html page is one way to accommodate this dependency. to learn more about alternative approaches, see script loading strategies. ...
...And 14 more matches
Inheritance in JavaScript - Learn web development
y the properties inside the constructor: function person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; }; the methods are all defined on the constructor's prototype. for example: person.prototype.greeting = function() { alert('hi! i\'m ' + this.name.first + '.'); }; note: in the source code, you'll also see bio() and farewell() methods defined. later you'll see how these can be inherited by other constructors. say we wanted to create a teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from person, but also includes: a new property, subject — this will contain the subject the teacher teaches. an updated greeting...
...: a new property, subject — this will contain the subject the teacher teaches. an updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school. defining a teacher() constructor function the first thing we need to do is create a teacher() constructor — add the following below the existing code: function teacher(first, last, age, gender, interests, subject) { person.call(this, first, last, age, gender, interests); this.subject = subject; } this looks similar to the person constructor in many ways, but there is something strange here that we've not seen before — the call() function. this function basically allows you to call a function defined somewhere else, but in the current ...
...uld have simply done this: function teacher(first, last, age, gender, interests, subject) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; this.subject = subject; } but this is just redefining the properties anew, not inheriting them from person(), so it defeats the point of what we are trying to do. it also takes more lines of code. inheriting from a constructor with no parameters note that if the constructor you are inheriting from doesn't take its property values from parameters, you don't need to specify them as additional arguments in call(). so, for example, if you had something really simple like this: function brick() { this.width = 10; this.height = 20; } you could inherit the width and height properties by ...
...And 14 more matches
Introduction to the server side - Learn web development
ng this article you'll understand the additional power available to websites through server-side coding. prerequisites: basic computer literacy. a basic understanding of what a web server is. objective: to gain familiarity with what server-side programming is, what it can do, and how it differs from client-side programming. most large-scale websites use server-side code to dynamically display different data when needed, generally pulled out of a database stored on a server and sent to the client to be displayed via some code (e.g. html and javascript). perhaps the most significant benefit of server-side code is that it allows you to tailor website content for individual users. dynamic sites can highlight content that is more relevant based on user preferences ...
...icate with web servers using the hypertext transfer protocol (http). when you click a link on a web page, submit a form, or run a search, an http request is sent from your browser to the target server. the request includes a url identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include additional information encoded in url parameters (the field-value pairs sent via a query string), as post data (data sent by the http post method), or in associated cookies. web servers wait for client request messages, process them when they arrive, and reply to the web browser with an http response message. the response contains a status line indicating whether or not the request succeeded (e.g. "http/1.1 200 ok" for succe...
...ating whether or not the request succeeded (e.g. "http/1.1 200 ok" for success). the body of a successful response to a request would contain the requested resource (e.g. a new html page, or an image, etc...), which could then be displayed by the web browser. static sites the diagram below shows a basic web server architecture for a static site (a static site is one that returns the same hard-coded content from the server whenever a particular resource is requested). when a user wants to navigate to a page, the browser sends an http "get" request specifying its url. the server retrieves the requested document from its file system and returns an http response containing the document and a success status (usually 200 ok). if the file cannot be retrieved for some reason, an error status is r...
...And 14 more matches
mozIStorageBindingParams
bindingparams objects by calling the mozistoragebindingparamsarray.newbindingparams(). ...
...hod overview void bindbyindex(in unsigned long aindex, in nsivariant avalue); void bindblobbyindex(in unsigned long aindex, [array, const, size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); void binddoublebyindex(in unsigned long aindex, in double avalue); native code only! void bindint32byindex(in unsigned long aindex, in long avalue); native code only! void bindint64byindex(in unsigned long aindex, in long long avalue); native code only! void bindnullbyindex(in unsigned long aindex); native code only! void bindstringbyindex(in unsigned long aindex, in astring avalue); native code only! void bindutf8stringbyindex(in unsigned long aindex, in autf8string avalue); native code only! void bindbyname(...
...ve code only! void bindutf8stringbyindex(in unsigned long aindex, in autf8string avalue); native code only! void bindbyname(in autf8string aname, in nsivariant avalue); void bindblobbyname(in autf8string aname, [array, const, size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); void binddoublebyname(in autf8string aname, in double avalue); native code only! void bindint32byname(in autf8string aname, in long avalue); native code only! void bindint64byname(in autf8string aname, in long long avalue); native code only! void bindnullbyname(in autf8string aname); native code only! void bindstringbyname(in autf8string aname, in astring avalue); native code only! void bindutf8stringbyname(in autf8string ana...
...And 14 more matches
nsILocalFileMac
xpcom/io/nsilocalfilemac.idlscriptable please add a summary to this article. ...
... xpcom/io/nsilocalfilemac.idlscriptable please add a summary to this article. ...
... xpcom/io/nsilocalfilemac.idlscriptable please add a summary to this article. ...
...And 14 more matches
Index
up wizard. 3 account examples extensions, thunderbird this article provides examples on accessing and manipulating thunderbird accounts. account interfaces provides an overview of the related interfaces. see an overview of thunderbird components for a general description of the thunderbird user interface and related programmatic interfaces. 4 account interfaces code snippets, extension development, thunderbird this page contains a list of the interfaces that you'll will most likely use when writing extensions that work with email or other accounts. see account examples for examples and code snippets. 5 activity manager thunderbird 3, thunderbird the activity manager is a simple component that understands how to display a combinatio...
...ve status bar to give the user notifications concerning what thunderbird is doing and how thunderbird has handled user requests. 6 activity manager interfaces thunderbird this page describes the programmatic interfaces behind the activity manager component. the functionality of the component is described on the activity manager page, and the activity manager examples page has code snippets. see nsiactivitymanager.idl and nsiactivity.idl files for source documentation. 7 address book interfaces mailnews, mozilla, seamonkey, thunderbird this page contains a list of the interfaces that you'll will most likely hit when writing patches for the address book or writing extensions. the complete list of interfaces for the address book can be found here. address...
...es for source documentation. 7 address book interfaces mailnews, mozilla, seamonkey, thunderbird this page contains a list of the interfaces that you'll will most likely hit when writing patches for the address book or writing extensions. the complete list of interfaces for the address book can be found here. address book examples show how to perform various tasks and provide code snippets. 8 address book examples mailnews, seamonkey, thunderbird this article provides examples on accessing and manipulating thunderbird address books. address book interfaces provides an overview of the related interfaces. see an overview of thunderbird components for a general description of the thunderbird user interface and related programmatic interfaces. 9 ...
...And 14 more matches
Using Objective-C from js-ctypes
it uses the default system voice and waits until the speaking is done. ...
...it uses the default system voice and waits until the speaking is done. ...
...it uses the default system voice and waits until the speaking is done. ...
...And 14 more matches
EventTarget.addEventListener() - Web APIs
true, indicates that the function specified by listener will never call preventdefault(). if a passive listener does call preventdefault(), the user agent will do nothing other than generate a console warning. see improving scrolling performance with passive listeners to learn more. mozsystemgroup a boolean indicating that the listener should be added to the system group. available only in code running in xbl or in the chrome of the firefox browser. usecapture optional a boolean indicating whether events of this type will be dispatched to the registered listener before being dispatched to any eventtarget beneath it in the dom tree. events that are bubbling upward through the tree will not trigger a listener designated to use capture. event bubbling and capturing are two ways of pr...
...ardless of the usecapture parameter. note: usecapture has not always been optional. ideally, you should include it for the widest possible browser compatibility. wantsuntrusted a firefox (gecko)-specific parameter. if true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). this parameter is useful for code found in add-ons, as well as the browser itself. return value undefined usage notes the event listener callback the event listener can be specified as either a callback function or an object that implements eventlistener, whose handleevent() method serves as the callback function. the callback function itself has the same parameters and return value as the handleevent() method; that is, th...
...re 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 third parameter is a boolean, you need to build your code to handle this scenario intelligently. you can do this by using feature detection for each of the options you're interested in. for example, if you want to check for the passive option: let passivesupported = false; try { const options = { get passive() { // this function will be called when the browser // attempts to access the passive property. passivesuppor...
...And 14 more matches
WebAssembly Concepts - WebAssembly
this article explains the concepts behind how webassembly works including its goals, the problems it solves, and how it runs inside the web browser's rendering engine. what is webassembly? ...
... what is webassembly? webassembly is a new type of code that can be run in modern web browsers and provides new features and major gains in performance. it is not primarily intended to be written by hand, rather it is designed to be an effective compilation target for low-level source languages like c, c++, rust, etc. this has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn’t have done so. what’s more, you don’t even have to know how to create webassembly code to take advantage of it. webassembly modules can be imported into a web (or node.js) app, exposing webassembly functions for use via javascript. javascript frameworks could make use ...
...ctions for use via javascript. javascript frameworks could make use of webassembly to confer massive performance advantages and new features while still making functionality easily available to web developers. webassembly goals webassembly is being created as an open standard inside the w3c webassembly community group with the following goals: be fast, efficient, and portable — webassembly code can be executed at near-native speed across different platforms by taking advantage of common hardware capabilities. be readable and debuggable — webassembly is a low-level assembly language, but it does have a human-readable text format (the specification for which is still being finalized) that allows code to be written, viewed, and debugged by hand. keep secure — webassembly is specified...
...And 14 more matches
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. ...
... // work with returned nsilocalfile... } return path; } hash function firefox has built-in support for hash functions, exposed via the nsicryptohash xpcom interface the documentation page for that interface includes an example of calculating an md5 hash of a file's contents, given its path. ...
... } return path; } hash function firefox has built-in support for hash functions, exposed via the nsicryptohash xpcom interface the documentation page for that interface includes an example of calculating an md5 hash of a file's contents, given its path. ...
...And 13 more matches
The Essentials of an Extension - Archive of obsolete content
you can open it with any text editor. the file is formatted in a special flavor of xml called rdf. rdf used to be the central storage mechanism for firefox, but it is now being replaced for a simpler database system. we'll discuss both of these storage systems further ahead in the tutorial. now let's look at the important parts of the file. <em:id>helloworld@xulschool.com</em:id> this is the unique identifier for the extension. ...
...lled, that you can see in the add-ons manager. there are many other tags that can be added, for contributors and translators. the full specification of the install.rdf file has all the details. since extensions can be translated to multiple languages, it is often necessary to translate the extension's description, or even its name. a localized description and name can be added with the following code: <em:localized> <description> <em:locale>es-es</em:locale> <em:name>xul school hola mundo</em:name> <em:description>bienvenido a xul school!</em:description> </description> </em:localized> the es-es locale string indicates that this is the spanish (es) localization for spain (es). you can add as many <em:localized> sections as you need. for firefox 2, localizing this file is...
...indow title bars are all examples of elements that are typically part of the chrome. taken from chrome registration. in other words, the chrome is everything you see in firefox. all firefox windows can be seen as having two parts: (1) the chrome and (2) possibly a content area, like the one that displays web pages in a firefox tab. windows like the downloads window are pure chrome. most of the code for an extension resides in the chrome folder, just like in the hello world example. as we saw in the directory structure of the unpacked extension, the chrome is composed of 3 sections: content, locale and skin. the 3 are necessary for most extensions. if we open the chrome.manifest file (again, any text editor will do), we see that the same 3 sections are mentioned: content xulschoolhello...
...And 13 more matches
Install script template - Archive of obsolete content
x = "my"; var suffix_description = "my plugin files"; var company_name = "mypluginco"; var plugin_description = "my exemplary plugin mine all mine"; // registry constant paths // these will be used when the win32 registry keys are written var hkey_local_machine = "hkey_local_machine"; var hkey_current_user = "hkey_current_user"; var reg_moz_path = "software\\mozillaplugins"; // my own error code in case secondary installation fails var nosecondaryinstall = 1; // error return codes need some memory var err; // error return codes when we try and install to the current browser var errblock1; // error return codes when we try and do a secondary installation var errblock2 = 0; // global variable containing our secondary install location var secondaryfolder; //special error values use...
...lid, qualifiedsecondaryfolderdll, qualifiedsecondaryfolderxpt, plugin_description, company_name, software_name, version, mimetype, suffix, suffix_description); logcomment("first install installation: registerplid("+hkey_current_user+") returned, status "+hklm_status); if (hkcu_status != 0) { logcomment("could not write to the registry. errorcode="+hkcu_status); return hkcu_status; } } return 0; } /** * function for preinstallation of plugin (firstinstall). * you should not stop the install process because the function failed, * you still have a chance to install the plugin for the already * installed gecko browsers. * * @param dirpath directory path from getfolder * @param spacerequired required space in kil...
...erplid: registry key not writable"); return registrykeynotwritableerror; } // if we can't find the plidpath create the key if (!winreg.keyexists(plidpath)) { logcomment("moz registerplid: creating missing key "+plidpath+"."); myregstatus = winreg.createkey(plidpath, ""); if (myregstatus != 0) { logcomment("moz registerplid: could not create the key, "+plidpath+"as expected. errorcode="+myregstatus); return myregstatus; } } // ok were done, let's write info about our plugin, path, productname, etc // write a subkey to mozillaplugins with our plid //var mysetstrrc = winreg.setvaluestring(plidpath, plidid, dllabsolutepath); mymozillapluginpath = plidpath+"\\"+plidid; // for instance. software\mozillaplugins\@cycore.com/cult3dviewer myregstatus = winreg.createkey(p...
...And 13 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
rms that mozilla and netscape browsers based on mozilla (such as netscape 7) are deployed. it can be a way to ensure a smooth user-experience when obtaining plugins, without obliging the user to exit the browsing environment to launch a binary installer (the classic setup.exe experience on windows) or obliging the user to restart their browser. for plugin vendors who have already written a native code (e.g. exe) installer, xpinstall can wrap this native installer and run it so that the user never has to leave the browsing environment and click on the exe to run it. this article presents a guideline for improving the plugin installation experience for netscape gecko browsers using xpinstall. a definition of terms xpinstall is an installer technology, and the name itself stands for "cross pla...
...t file called install.js, which is the install logic that drives the installation. this includes instructions on where to install the software, and what messages to feed to the user. you can create an xpinstall file by first zipping all the items you want installed with winzip (create a zip archive) and then renaming it with the xpi file extension instead of the zip file extension. unlike native code installers (for example, files called setup.exe), the programming language for install operations in xpi is javascript. since the file format that contains the software and the install.js javascript file is a cross-platform file (zip) and since javascript is understood by mozilla browsers on all platforms, often one single xpi package can be deployed on all platforms. this is, in fact, how skins ...
...lla browsers on all platforms, often one single xpi package can be deployed on all platforms. this is, in fact, how skins and themes are installed to mozilla browsers, changing their look and feel. this article focuses on how to install plugins. which browsers support xpinstall? currently, all mozilla browsers released by mozilla.org support xpinstall, and a family of browsers based on mozilla code support xpinstall. in particular, this includes: recent netscape browsers such as netscape 6.2.x and netscape 7.0, which are both based on netscape gecko, which is at the core of the mozilla browser recent beta-only versions of the aol software based on netscape gecko, the layout engine of the mozilla project. caveats: aol time warner's compuserve browser, also based on netscape gecko, does...
...And 13 more matches
Examples - Archive of obsolete content
ideally, upload the file to a web server and you're done. please note that the examples 4, 5 and 6 require a file named style.css to exist in the same directory as the example. you can get the contents of style.css at the bottom of this page. ...
...ideally, upload the file to a web server and you're done. please note that the examples 4, 5 and 6 require a file named style.css to exist in the same directory as the example. you can get the contents of style.css at the bottom of this page. ...
... </p> <dl> <dt>mozilla 1.1+/opera 7</dt> <dd>do not apply css or execute the javascript.</dd> <dt>netscape 7.0x/mozilla 1.0.x</dt> <dd>do ...
...And 13 more matches
How to build custom form controls - Learn web development
you may consider building your own controls. in this article, we will discuss how to build a custom control. to that end, we will work with an example: rebuilding the <select> element. we will also discuss how, when, and whether building your own control makes sense, and what to consider when building a control is a requirement. note: we'll focus on building the control, not on how to make the code generic and reusable; that would involve some non-trival javascript code and dom manipulation in an unknown context, and that is out of the scope of this article. design, structure, and semantics before building a custom control, you should start by figuring out exactly what you want. this will save you some precious time. in particular, it's important to clearly define all the states of your ...
...ss="option">banana</li> <li class="option">strawberry</li> <li class="option">apple</li> </ul> </div> note the use of class names; these identify each relevant part regardless of the actual underlying html elements used. this is important to make sure that we don't bind our css and javascript to a strong html structure, so that we can make implementation changes later without breaking code that uses the control. for example, what if you wish to implement the equivalent of the <optgroup> element later on? class names, however, provide no semantic value. in this current state, the screen reader user only "sees" an unordered list. we will add aria semantics in a bit. creating the look and feel using css now that we have a structure, we can start designing our control. the whole poi...
... an ellipsis */ display : inline-block; width : 100%; overflow : hidden; white-space : nowrap; text-overflow: ellipsis; vertical-align: top; } we don't need an extra element to design the down arrow; instead, we're using the :after pseudo-element. it could also be implemented using a simple background image on the select class. ...
...And 13 more matches
UI pseudo-classes - Learn web development
ates selection — that could be confusing. having a purely visual indicator solves this problem. note: this also shows how you can combine a pseudo-class and pseudo-element if required. back to our required/optional example from before, this time we'll not alter the appearance of the input itself — we'll use generated content to add an indicating label (see it live here, and see the source code here). first of all, we'll add a paragraph to the top of the form to say what you are looking for: <p>required fields are labelled with "required".</p> screenreader users will get "required" read out as an extra bit of information when they get to each required input, which sighted users will get our label. since form inputs don't directly support having generated content put on them (this is...
...tes are (matched with) :invalid, but also matched by :out-of-range, as you'll see later on. there are some other ways to make an element matched by :valid/:invalid, as you'll see in the client-side form validation article. but we'll keep things simple for now. let's go in and look at a simple example of :valid/:invalid (see valid-invalid.html for the live version, and also check out the source code). as in the previous example, we've got extra <span>s to generate content on, which we'll use to provide indicators of valid/invalid data: <div> <label for="fname">first name *: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> to provide these indicators, we use the following css: input + span { position: relative; } input + span::before { position...
...ass. so why have both? the issue is really one of semantics — out-of-range is a more specific type of invalid communication, so you might want to provide a different message for out-of-range inputs, which will be more helpful to users than just saying "invalid". you might even want to provide both. let's look at an example that does exactly this. our out-of-range.html demo (see also the source code) builds on top of the previous example to provide out-of-range messages for the numeric inputs, as well as saying whether they are required. the numeric input looks like this: <div> <label for="age">age (must be 12+): </label> <input id="age" name="age" type="number" min="12" max="120" required> <span></span> </div> and the css looks like this: input + span { position: relative; } in...
...And 13 more matches
Video and audio content - Learn web development
uch features added, with the <video> and <audio> elements, and some shiny new javascript apis for controlling them. we'll not be looking at javascript here — just the basic foundations that can be achieved with html. we won't be teaching you how to produce audio and video files — that requires a completely different skillset. we have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own. note: before you begin here, you should also know that there are quite a few ovps (online video providers) like youtube, dailymotion, and vimeo, and online audio providers like soundcloud. such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth co...
... unable to get hold of your own. note: before you begin here, you should also know that there are quite a few ovps (online video providers) like youtube, dailymotion, and vimeo, and online audio providers like soundcloud. such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. ovps even usually offer ready-made code for embedding video/audio in your webpages; if you use that route, you can avoid some of the difficulties we discuss in this article. we'll be discussing this kind of service a bit more in the next article. the <video> element the <video> element allows you to embed a video very easily. a really simple example looks like this: <video src="rabbit320.webm" controls> <p>your browser doesn't su...
...accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. this can be anything you like; in this case, we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using. the embedded video will look something like this: you can try the example live here (see also the source code.) using multiple source formats to improve compatibility there's a problem with the above example, which you may have noticed already if you've tried to access the live link above with an older browser like internet explorer or even an older version of safari. the video won't play, because different browsers support different video (and audio) formats. fortunately, there are things you can do t...
...And 13 more matches
Getting started with Svelte - Learn web development
environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. svelte is a compiler that generates minimal and highly optimized javascript code from our sources; you'll need a terminal with node + npm installed to compile and build your app. objective: to setup a local svelte development environment, create and build a starter app, and understand the basics of how it works. svelte: a new approach to building rich user interfaces svelte provides a different approach to building web apps than some of the other frame...
...t from scratch letting svelte drive your ui or you can incrementally integrate it into an existing application. nevertheless, svelte is particularly appropriate to tackle the following situations: web applications intended for low power devices: applications built with svelte have smaller bundle sizes, which is ideal for devices with slow network connections and limited processing power. less code means less kb to download, parse, execute, and keep hanging around in memory. highly interactive pages or complex visualizations: if you are building data-visualizations that need to display a large number of dom elements, the performance gains that come from a framework with no runtime overhead will ensure that user interactions are snappy and responsive. onboarding people with basic web devel...
...ive. onboarding people with basic web development knowledge: svelte has a shallow learning curve. web developers with basic html, css, and javascript knowledge can easily grasp svelte specifics in a short time and start building web applications. moreover, with the help of sapper (a framework based on svelte), you can also develop applications with advanced features like server-side rendering, code splitting, file-based routing and offline support. and then there's also svelte native, which lets you build native mobile applications. how does svelte work? being a compiler, svelte can extend html, css, and javascript, generating optimal javascript code without any runtime overhead. to achieve this, svelte extends vanilla web technologies in the following ways: it extends html by allowing...
...And 13 more matches
Working with Svelte stores - Learn web development
t shows notifications on screen, which can receive messages from any component. in this case, the alert component is independent from the rest — it is not a parent or child of any other — so the messages don't fit into the component hierarchy. we will also see how to develop our own custom store to persist the todo information to web storage, allowing our todos to persist over page reloads. code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/06-stores or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/06-stores remember to run npm install && npm run dev to start your app in development mode. re...
...with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/06-stores or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/06-stores remember to run npm install && npm run dev to start your app in development mode. repl to code along with us using the repl, start at https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2 dealing with our app state we have already seen how our components can communicate with each other using props, two-way data binding, and events. in all these cases we were dealing with communication between parent and child components. but not all application state belongs inside yo...
... display a message whenever the store is modified. create a new file — stores.js — inside your src directory. give it the following content: import { writable } from 'svelte/store' export const alert = writable('welcome to the to-do list app!') note: stores can be defined and used outside of svelte components, so you can organize them in any way you please. in the above code we import the writable() function from svelte/store and use it to create a new store called alert with an initial value of "welcome to the to-do list app!". we then export the store. creating the actual component let's now create our alert component and see how we can read values from the store. create another new file named src/components/alert.svelte. give it the following content...
...And 13 more matches
Signing Mozilla apps for Mac OS X
mac os x's gatekeeper functionality prevents users from launching applications that haven't been code-signed, in order to help keep their computers secure. firefox and thunderbird releases are both signed before shipping; this article describes the process. signing mozilla apps without the signing server firefox and thunderbird are built using mozilla's release automation infrastructure. on mac os x, part of this infrastructure is automatic signing of the ".app" folder using apple's codesign tool. ...
...s release automation infrastructure. on mac os x, part of this infrastructure is automatic signing of the ".app" folder using apple's codesign tool. for projects that don't use mozilla's release automation and would like to be signed for secure launching on os 10.8 mountain lion and later, this guide should provide some insight into how to make sure applications are signed correctly using apple's codesign tool. apple's code signing guide is also a good resource on the subject. getting a signing certificate in order to code-sign an application, you need a signing certificate. while testing and debugging for test and debug purposes, the easiest way to get a signing certificate is to use apple's keychain feature to create one. there are good instructions available under "to use the certificat...
... creating a private key, certificate signing request, and importing your new developer id into the keychain access application on your mac. if the "developer id" radio button is greyed out you probably have a group account. these types of accounts only allow for the "agent" role to create developer ids. contact the person who created your group apple developer account if you get stuck here. the codesign tool apple provides a tool called codesign; this command-line application is used to add a signature to an application bundle. the man page for codesign is available online, or you can simply type "man codesign" in a terminal window. the main options of note are: -s your-signing-identity lets you specify the signing certificate you want to sign the application with your-signing-identity ...
...And 13 more matches
An Overview of XPCOM
oped and built independently of one another. in order to allow interoperability between components within an application, xpcom separates the implementation of a component from the interface, which we discuss in interfaces. but xpcom also provides several tools and libraries that enable the loading and manipulation of these components, services that help the developer write modular cross-platform code, and versioning support, so that components can be replaced or upgraded without breaking or having to recreate the application. using xpcom, developers create components that can be reused in different applications or that can be replaced to change the functionality of existing applications. xpcom not only supports component software development, it also provides much of the functionality that a...
...libraries (a dll on windows, for example, or a dso on unix), which can include one or more components. when two or more related components are grouped together in a binary library, the library is referred to as a module. modular, component-based programming makes software easier to develop and maintain and has some well-known advantages: benefit description reuse modular code can be reused in other applications and other contexts. updates you can update components without having to recompile the whole application. performance when code is modularized, modules that are not necessary right away can be "lazy loaded", or not loaded at all, which can improve the performance of your application. maintenance even when you are not updating ...
...les that are not necessary right away can be "lazy loaded", or not loaded at all, which can improve the performance of your application. maintenance even when you are not updating a component, designing your application in a modular way can make it easier for you to find and maintain the parts of the application that you are interested in. mozilla has over four million lines of code, and no single individual understands the entire codebase. the best way to tackle a project of this size is to divide it into smaller, more manageable pieces, use a component programming model, and to organize related sets of components into modules. the network library, for example, consists of components for each of the protocols, http, ftp, and others, which are bundled together and linked int...
...And 13 more matches
nsIMimeConverter
the nsimimeconverter service allows you to convert headers into and out of mime format. inherits from: nsisupports implemented by: @mozilla.org/messenger/mimeconverter;1. ...
... the nsimimeconverter service allows you to convert headers into and out of mime format. inherits from: nsisupports implemented by: @mozilla.org/messenger/mimeconverter;1. ...
... the nsimimeconverter service allows you to convert headers into and out of mime format. inherits from: nsisupports implemented by: @mozilla.org/messenger/mimeconverter;1. ...
...And 13 more matches
Plug-in Basics - Plugins
and innovative plug-ins. with the plug-in api, you can create dynamically loaded plug-ins that can: register one or more mime types draw into a part of a browser window receive keyboard and mouse events obtain data from the network using urls post data to urls add hyperlinks or hotspots that link to new urls draw into sections on an html page communicate with javascript/dom from native code you can see which plug-ins are installed on your system and have been properly associated with the browser by consulting the installed plug-ins page. go to the help menu, and click help and then about plug-ins. type "about:plugins" in the location bar. the installed plug-ins page lists each installed plug-in along with its mime type or types, description, file extensions, and the current state ...
...ooks for plugin modules in particular places on the system. for more information about where gecko looks for plugin modules on different systems, see how gecko finds plug-ins. when the user opens a page that contains embedded data of a media type that invokes a plug-in, the browser responds with the following sequence of actions: check for a plug-in with a matching mime type load the plug-in code into memory initialize the plug-in create a new instance of the plug-in gecko can load multiple instances of the same plug-in on a single page, or in several open windows at the same time. if you are browsing a page that has several embedded realaudio clips, for example, the browser will create as many instances of the realplayer plug-in as are needed (though of course playing several realaud...
...are browsing a page that has several embedded realaudio clips, for example, the browser will create as many instances of the realplayer plug-in as are needed (though of course playing several realaudio files at the same time would seldom be a good idea). when the user leaves the page or closes the window, the plug-in instance is deleted. when the last instance of a plug-in is deleted, the plug-in code is unloaded from memory. a plug-in consumes no resources other than disk space when it is not loaded. the next section, understanding the runtime model, describes these stages in more detail. understanding the runtime model plug-ins are dynamic code modules that are associated with one or more mime types. when the browser starts, it enumerates the available plug-ins (this step varies according ...
...And 13 more matches
Capabilities, constraints, and settings - Web APIs
historically, writing scripts for the web that work intimately with web apis has had a well-known challenge: often, your code needs to know whether or not an api exists and if so, what its limitations are on the user agent it's running on. figuring this out has often been difficult, and has usually involved looking at some combination of which user agent (or browser) you're running on, which version it is, looking to see if certain objects exist, trying to see whether various things work or not and determining what errors occur, and so forth. the result has been a lot of very fragile code, or a reliance on libraries which figure this stuff out for you, then implement polyfills to patch the holes in the implementation on your behalf. the twin concepts of constraints and capabilities let the b...
...s desired, with the standard 16:9 aspect ratio. there's no guarantee that the resulting track will match any of these, but the user agent should do its best to match as many as possible. the prioritization of the properties is simple: if two properties' requested values are mutually exclusive, then the one listed first in the constraint set will be used. as an example, if the browser running the code above couldn't provide a 1920x1080 track but could do 1920x900, then that's what would be provided. simple constraints like these, specifying a single value, are always treated as non-required. the user agent will try to provide what you request but will not guarantee that what you get will match. however, if you use simple values for properties when calling mediastreamtrack.applyconstraints(), ...
...mediatracksettings. for example: function whichcamera(track) { return track.getsettings().facingmode; } this function uses getsettings() to obtain the track's currently in-use values for the constrainable properties and returns the value of facingmode. example: constraint exerciser in this example, we create an exerciser which lets you experiment with media constraints by editing the source code describing the constraint sets for audio and video tracks. you can then apply those changes and see the result, including both what the stream looks like and what the actual media settings are set to after applying the new constraints. the html and css for this example are pretty simple, and aren't shown here. you can look at the complete example by clicking here. html content <p>experiment w...
...And 13 more matches
String - JavaScript
ty lookup occurs, javascript will automatically wrap the string primitive and call the method or perform the property lookup. let s_prim = 'foo' let s_obj = new string(s_prim) console.log(typeof s_prim) // logs "string" console.log(typeof s_obj) // logs "object" string primitives and string objects also give different results when using eval(). ...
...imitives passed to eval are treated as source code; string objects are treated as all other objects are, by returning the object. for example: let s1 = '2 + 2' // creates a string primitive let s2 = new string('2 + 2') // creates a string object console.log(eval(s1)) // returns the number 4 console.log(eval(s2)) // returns the string "2 + 2" for these reasons, the code may break when it encounters string objects when it expects a primitive string instead, although generally, authors need not worry about the distinction. a string object can always be converted to its primitive counterpart with the valueof() method. ...
...tring "2 + 2" for these reasons, the code may break when it encounters string objects when it expects a primitive string instead, although generally, authors need not worry about the distinction. a string object can always be converted to its primitive counterpart with the valueof() method. ...
...And 13 more matches
Lexical grammar - JavaScript
t to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or white space. ecmascript also defines certain keywords and literals and has rules for automatic insertion of semicolons to end statements. control characters control characters have no visual representation but are used to control the interpretation of the text. unicode format-control characters code point name abbreviation description u+200c zero width non-joiner <zwnj> placed between characters to prevent being connected into ligatures in certain languages (wikipedia). u+200d zero width joiner <zwj> placed between characters that would not normally be connected in order to cause the characters to be rend...
...acters to prevent being connected into ligatures in certain languages (wikipedia). u+200d zero width joiner <zwj> placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages (wikipedia). ...
... rendered using their connected form in certain languages (wikipedia). u+feff byte order mark <bom> used at the start of the script to mark it as unicode and the text's byte order (wikipedia). white space white space characters improve the readability of source text and separate tokens from each other. these characters are usually unnecessary for the functionality of the code. minification tools are often used to remove whitespace in order to reduce the amount of data that needs to be transferred. ...
...And 13 more matches
Archived Mozilla and build documentation - Archive of obsolete content
you perform queries on the contents of a cvs archive; you can: get a list of checkins, see what checkins have been made by a given person, or on a given cvs branch, or in a particular time period. it also includes tools for looking at checkin logs (and comments); doing diffs between various versions of a file; and finding out which person is responsible for changing a particular line of code ("cvsblame"). bookmark keywords practically every web surfer has bookmarks, of course, and power surfers usually have hundreds stuffed into folders within folders. in addition to being handy pointers to useful resources, bookmarks in mozilla can be used to make the address bar itself a power tool. searches, lookups, package tracking, and even word defin...
...ozilla extension is an installable enhancement to the mozilla browser that provides additional functionality (for example linky, which adds an item to the context menu for opening multiple links in a document or selection). this tutorial walks you through the process of building a mozilla extension that adds an icon to mozilla's status bar showing the current status of the mozilla source code (i.e. whether or not the latest version of the code is compiling successfully and passing tests). the extension will access tinderbox, mozilla.org's webtool for tracking source code status, to get the status of the code. creating a skin for firefox/getting started download the latest version of firefox and install it. be sure to install the dom inspector...
...e. probe data can be collected with scripts written in d (no, not that one). mozilla dtrace support has been added by the sun dtrace team and can be used on solaris 10 and mac os x 10.5. embedding faq embedding mozilla in a java application using javaxpcom xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java is not that much different than doing so in c++. error console the error console is a tool available in most mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. it reports javascript-related ...
...And 12 more matches
From object to iframe — other embedding technologies - Learn web development
familiar with youtube, but many people don't know about some of the sharing facilities it has available. let's look at how youtube allows us to embed a video in any page we like using an <iframe>. first, go to youtube and find a video you like. below the video, you'll find a share button — select this to display the sharing options. select the embed button and you'll be given some <iframe> code — copy this. insert it into the input box below, and see what the result is in the output. for bonus points, you could also try embedding a google map in the example: go to google maps and find a map you like. click on the "hamburger menu" (three horizontal lines) in the top left of the ui. select the share or embed map option. select the embed map option, which will give you some <ifr...
...copy this. insert it into the input box below, and see what the result is in the output. for bonus points, you could also try embedding a google map in the example: go to google maps and find a map you like. click on the "hamburger menu" (three horizontal lines) in the top left of the ui. select the share or embed map option. ...
...ontal lines) in the top left of the ui. select the share or embed map option. select the embed map option, which will give you some <iframe> code — copy this. insert it into the input box below, and see what the result is in the output. if you make a mistake, you can always reset it using the reset button. if you get really stuck, press the show solution button to see an answer. ...
...And 12 more matches
Introducing asynchronous JavaScript - Learn web development
javascript, and what use cases it has. synchronous javascript to allow us to understand what asynchronous javascript is, we ought to start off by making sure we understand what synchronous javascript is. this section recaps some of the information we saw in the previous article. a lot of the functionality we have looked at in previous learning area modules is synchronous — you run some code, and the result is returned as soon as the browser can do so. let's look at a simple example (see it live here, and see the source): const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); in this b...
...button is pressed in the alert box. you can try it for yourself: <button>click me</button> note: it is important to remember that alert(), while being very useful for demonstrating a synchronous blocking operation, is terrible for use in real world applications. asynchronous javascript for reasons illustrated earlier (e.g. related to blocking), many web api features now use asynchronous code to run, especially those that access or fetch some kind of resource from an external device, such as fetching a file from the network, accessing a database and returning data from it, accessing a video stream from a web cam, or broadcasting the display to a vr headset. why is this difficult to get to work using synchronous code? let's look at a quick example. when you fetch an image from a serve...
...let's look at a quick example. when you fetch an image from a server, you can't return the result immediately. ...
...And 12 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: learn and put into practice some basic svelte concepts, like creating components, passing data using props, render javascript expressions into our markup, modify the components state and iterating over lists. ...
...o (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/03-adding-dynamic-behavior or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior remember to run npm install && npm run dev to start your app in development mode. repl to code along with us using the repl, start at https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2 working with todos our todos.svelte component is currently just displaying static markup; let's start making it a bit more dynamic. we'll take the tasks information from the markup and store it in a todos array. we'll also create two variables to keep track of the total number of task...
...ate your first component', completed: true }, { id: 3, name: 'complete the rest of the tutorial', completed: false } ] let totaltodos = todos.length let completedtodos = todos.filter(todo => todo.completed).length </script> now let's do something with that information. let's start by showing a status message. find the <h2> heading with an id of list-heading and replace the hardcoded number of active and completed tasks with dynamic expressions: <h2 id="list-heading">{completedtodos} out of {totaltodos} items completed</h2> go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the todos array. to prove it, go to that array, and try changing some of the todo object's completed property...
...And 12 more matches
Package management basics - Learn web development
t of software that was probably written by someone else and ideally solves a single problem for you. a web project can have any number of dependencies, ranging from none to many, and your dependencies might include sub-dependencies that you didn't explicitly install — your dependencies may have their own dependencies. a simple example of a useful dependency that your project might need is some code to calculate relative dates as human-readable text. you could certainly code this yourself, but there's a strong chance that someone else has already solved this problem — why waste time reinventing the wheel? moreover, a reliable third-party dependency will likely have been tested in a lot of different situations, making it more robust and cross-browser compatible than your own solution. a pr...
... vue — or a very small utility like our human-readable date library, or it can be a command line tool such as prettier or eslint, which we talked about in previous articles. without modern build tools, dependencies like this might be included in your project using a simple <script> element, but this might not work right out of the box and you will likely need some modern tooling to bundle your code and dependencies together when they are released on the web. a bundle is the term that’s generally used to refer to a single file on your web server that contains all the javascript for your software — typically compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors’ browser. in addition, what happens if you find a bet...
...ind a better tool that you want to use instead of the current one, or a new version of your dependency is released that you want to update to? this is not too painful for a couple of dependencies, but in larger projects with many dependencies this kind of thing can become really challenging to keep track of. it makes more sense to use a package manager such as npm, as this will guarantee that the code is added and removed cleanly, as well as a host of other advantages. what exactly is a package manager? we've met npm already, but stepping back from npm itself, a package manager is a system that will manage your project dependencies. the package manager will provide a method to install new dependencies (also referred to as "packages"), manage where packages are stored on your file system, an...
...And 12 more matches
Internationalized Domain Names (IDN) Support in Mozilla Browsers
aracters for user input into a browser's location bar or url's embedded in web pages. at the network protocol level, there is no change in the restriction that only a subset of ascii characters be used in url/uri. ...
... ascii characters be used in url/uri. if end users input non-ascii characters as part of a domain name or if a web page contains a link using a non-ascii domain name, the application must convert such input into a special encoded format using only the usual ascii subset characters. rfc 3490 (internationalizing domain names in applications (idna)) defines characters used in idn to be drawn from unicode standard 3.2. it also defines how an application should process non-ascii characters in such a way to conform to existing host name character restrictions. ...
... the process will convert uppercase characters to lowercase ones (case folding), unify characters with multiple representation, e.g. ...
...And 12 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
... rv = readderfromfile(&reqder, infilename, ascii); if (rv) { rv = secfailure; goto cleanup; } certreq = (certcertificaterequest*) port_arenazalloc (arena, sizeof(certcertificaterequest)); if (!certreq) { rv = secfailure; goto cleanup; } certreq->arena = arena; /* since cert request is a signed data, must decode to get the inner data */ port_memset(&signeddata, 0, sizeof(signeddata)); rv = sec_asn1decodeitem(arena, &signeddata, sec_asn1_get(cert_signeddatatemplate), &reqder); if (rv) { rv = secfailure; goto cleanup; } rv = sec_asn1decodeitem(arena, certreq, sec_asn1_get(cert_certificaterequesttemplate), &...
...And 12 more matches
sample2
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...*/ #ifndef port_errortostring #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif /* sample 6 commands */ typedef enum { generate_csr, add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify,...
...ically from nss versions earlier than 3.13 */ #ifndef sec_error_base #define sec_error_base (-0x2000) typedef enum { sec_error_io = sec_error_base + 0, sec_error_token_not_logged_in = (sec_error_base + 155), sec_error_end_of_list } secerrorcodes; #endif /* port_errortostring introduced in nss 3.13. on earlier versions of nss that * don't support error tables, pr_errortostring will return "unknown code". */ #ifndef port_errortostring #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif /* sample 6 commands */ typedef enum { generate_csr, add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6, certenc= 7, certvfy= 8, sig = 9 } headertype; /* *...
...And 12 more matches
Introduction to XPCOM for the DOM
warning: this document has not yet been reviewed by the dom gurus, it might contain some errors. this document is an introduction to the use of xpcom in the context of the dom code. the use of xpcom and nscomptr's described in this document covers about 80% of what you need to know to read the dom code, and even write some. for more advanced topics, please see the xpcom page. the tracking bug for this document is bug 99592. target audience: people who would like a quick introduction to the use of c++ and xpcom in the dom code. the understanding of the content of this document is a requirement to read the rest of the dom hacking guide. important note: this document assumes some knowledge of c++, specially the object-oriented part of it. i learned c++ by reading "c++ primer" from st...
... would like a quick introduction to the use of c++ and xpcom in the dom code. the understanding of the content of this document is a requirement to read the rest of the dom hacking guide. important note: this document assumes some knowledge of c++, specially the object-oriented part of it. i learned c++ by reading "c++ primer" from stanley lippman and josee lajoie, then experimenting on the dom code. i recommend that book to all the beginners out there. introduction to the introduction the dom makes extensive use of xpcom. in fact, to do anything with the dom implementation you need xpcom. you do not, however, need to know all the hairy details, if you just intend to read the code or to work with the existing framework. the numerous macros and facilities brought by the dom, as well as nsc...
... virtual functions. an interface can also be defined using xpidl. this is described in section 1.e, "how to add an interface". since an interface doesn't have any implementation, it has to be implemented by a non-abstract class -- a concrete class. if the interface is called nsifoo and the class is called nsfoo, we say that "nsfoo implements nsifoo", or that "nsfoo inherits from nsifoo". ...
...And 12 more matches
Xptcall Porting Status
mike shaver <shaver@mozilla.org> is the best contact regarding 'nix (unix, linux, finux, etc.) ports of xptcall. ...
...egcs 1.1. he notes that the vtbl scheme is different. he is hoping that others will help test the changes using these two compilers on the various pl...
...bert's details <font color="white">done</font> mac ppc roger lawrence <rogerl@net...
...And 12 more matches
DOMException - Web APIs
ception) that occurs as a result of calling a method or accessing a property of a web api. this is basically how error conditions are described in web apis. each exception has a name, which is a short "camelcase" style string identifying the error or abnormal condition. constructor domexception() returns a domexception object with a specified message and name. properties domexception.code read only returns a short that contains one of the error code constants, or 0 if none match. this field is used for historical reasons. new dom exceptions don't use this anymore: they put this info in the domexception.name attribute. domexception.message read only returns a domstring representing a message or description associated with the given error name. domexception.name read only ...
...domstring that contains one of the strings associated with an error name. error names common error names are listed here. some apis define their own sets of names, so this is not necessarily a complete list. ...
... not necessarily a complete list. note: because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. indexsizeerror the index is not in the allowed range. for example, this can be thrown by the range object. (legacy code value: 1 and legacy constant name: index_size_err) hierarchyrequesterror the node tree hierarchy is not correct. ...
...And 12 more matches
Using IndexedDB - Web APIs
e operation, like adding or retrieving data. wait for the operation to complete by listening to the right kind of dom event. do something with the results (which can be found on the request object). with these big concepts under our belts, we can get to more concrete stuff. creating and structuring the store using an experimental version of indexeddb in case you want to test your code in browsers that still use a prefix, you can use the following code: // in the following line, you should include the prefixes of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use "var indexeddb = ..." if you're not in a function. // moreover, you may need references to some window.idb* obj...
...rt the object's constants for older browsers window.idbkeyrange = window.idbkeyrange || window.webkitidbkeyrange || window.msidbkeyrange; // (mozilla has never prefixed these objects, so we don't need window.mozidb*) beware that implementations that use a prefix may be buggy, or incomplete, or following an old version of the specification. therefore, it is not recommended to use it in production code. it may be preferable to not support a browser than to claim to support it and fail: if (!window.indexeddb) { console.log("your browser doesn't support a stable version of indexeddb. such and such feature will not be available."); } opening a database we start the whole process like this: // let us open our database var request = window.indexeddb.open("mytestdatabase", 3); see that? op...
...pgradeneeded event trigger. so for example, don't use 2.4 as a version number: var request = indexeddb.open("mytestdatabase", 2.4); // don't do this, as the version will be rounded to 2 generating handlers the first thing you'll want to do with almost all of the requests you generate is to add success and error handlers: request.onerror = function(event) { // do something with request.errorcode! }; request.onsuccess = function(event) { // do something with request.result! }; which of the two functions, onsuccess() or onerror(), gets called? if everything succeeds, a success event (that is, a dom event whose type property is set to "success") is fired with request as its target. once it is fired, the onsuccess() function on request is triggered with the success event as its argument. ...
...And 12 more matches
SubtleCrypto.encrypt() - Web APIs
ing mode, as specified in nist sp800-38a. aes-gcm this represents aes in galois/counter mode, as specified in nist sp800-38d. one major difference between this mode and the others is that gcm is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. examples note: you can try the working examples out on github. ...
...aes-gcm this represents aes in galois/counter mode, as specified in nist sp800-38d. one major difference between this mode and the others is that gcm is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. examples note: you can try the working examples out on github. ...
...-38d. one major difference between this mode and the others is that gcm is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. examples note: you can try the working examples out on github. rsa-oaep this code fetches the contents of a text box, encodes it for encryption, and encrypts it with using rsa-oaep. see the complete code on github. ...
...And 12 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
as well as to help ensure you understand the way the functions and data that are used during xr rendering work together. screenshot of this example in action the core of this example—the spinning, textured, lighted cube—is taken from our webgl tutorial series; namely, the penultimate article in the series, covering lighting in webgl. while reading this article and the accompanying source code, it's helpful to keep in mind that the display for a 3d headset is a single screen, divided in half. the left half of the screen is seen only by the left eye, while the right half is only seen by the right eye. rendering the scene for immersive presentation requires multiple renders of the scene—once from the perspective of each eye. when rendering the left eye, the xrwebgllayer has its viewpo...
...polyfill, we allow the example to work on many browsers that don't yet have webxr implementations in place, and we smooth out any transient deviations from the specification that occur during these still somewhat experimental days of the webxr specification. options this example has a number of options you can configure by adjusting the values of constants before you load it in the browser. ...
...${err}`); } } this takes as its only input a string, where, which is used to indicate what part of the program generated the error, since similar errors can have in multiple situations. the vertex and fragment shaders the vertex and fragment shaders are both exactly the same as those used in the example for our article lighting in webgl. refer to that if you're interested in the glsl source code for the basic shaders used here. suffice it to say that the vertex shader computes the position of each vertex given the initial positions of each vertex and the transforms that need to be applied to convert them to simulate the viewer's current position and orientation. the fragment shader returns the color of each vertex, interpolating as needed from the values found in the texture and applyin...
...And 12 more matches
Rendering and the WebXR frame animation callback - Web APIs
e representing the position and orientation of the viewer by creating an xrrigidtransform representing that position and orientation, then calling the xrreferencespace method getoffsetreferencespace(). then the first animation frame is scheduled by calling the xrsession method requestanimationframe(), providing a callback function, mydrawframe(), whose job is to render the frame. note that this code doesn't have a loop! instead, the frame rendering code—in this case, a function named mydrawframe()—is responsible for scheduling time to draw another frame by once again calling requestanimationframe(). refresh rate and frame rate assuming you've called the xrsession method requestanimationframe() since the last time the screen refreshed, the browser will call your frame renderer callback ...
...tually 120 hz, though, you can get by with just refreshing 60 times per second anyway, 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 ...
... tearing occurs when the the display hardware starts the next refresh cycle while the previous frame is still being drawn to the screen. as a result, you wind up with the visual effect of the top part of the screen showing the new frame, while the bottom part of the frame shows some combination of the previous frame and possibly even the frame before that one. your mission, then, is to keep your code tight and lightweight enough that you don't overrrun the time available to you or otherwise cause dropped frames or excessively abuse the main thread. for these reasons, unless your renderer is fairly small and lightweight, with little to do, you should consider offloading everything you can to a worker so you can be computing the next frame while the browser handles other things. by simply havi...
...And 12 more matches
Using CSS transforms - CSS: Cascading Style Sheets
lements are, the smaller they are. setting perspective this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. ...
...hey are. setting perspective this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. ...
... this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. ...
...And 12 more matches
Closures - JavaScript
a closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). in other words, a closure gives you access to an outer function’s scope from an inner function. in javascript, closures are created every time a function is created, at function creation time. lexical scoping consider the following example code: function init() { var name = 'mozilla'; // name is a local variable created by init function displayname() { // displayname() is the inner function, a closure alert(name); // use variable declared in the parent function } displayname(); } init(); init() creates a local variable called name and a function called displayname(). the displayname() function is an inner function that is defined inside...
...displayname(). the displayname() function is an inner function that is defined inside init() and is available only within the body of the init() function. note that the displayname() function has no local variables of its own. however, since inner functions have access to the variables of outer functions, displayname() can access the variable name declared in the parent function, init(). run the code using this jsfiddle link and notice that the alert() statement within the displayname() function successfully displays the value of the name variable, which is declared in its parent function. this is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. the word lexical refers to the fact that lexical scoping uses the location where a vari...
...e that the alert() statement within the displayname() function successfully displays the value of the name variable, which is declared in its parent function. this is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. ...
...And 12 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten. let’s look at how it works. emscripten environment setup first, let's set up the required development environment. prerequisites get the emscripten sdk, using these instructions: https://emscripten.org/docs/getting_started/downloads.html compiling an example with the environment set up, let's look at how to use it to compile a c example to emscripten. there are a number of options available when compiling with emscripten, but the main two scenarios we'll cover are: compiling to wasm and creating html to run our code in, plus all the javascript "glue" code needed to run the wasm in the web environment. compiling to wasm and just creating the javascript...
... first we need an example to compile. ...
...e directory as your hello.c file, and run the following command: emcc hello.c -s wasm=1 -o hello.html the options we’ve passed in with the command are as follows: -s wasm=1 — specifies that we want wasm output. if we don’t specify this, emscripten will just output asm.js, as it does by default. ...
...And 12 more matches
Using the WebAssembly JavaScript API - WebAssembly
if you have already compiled a module from another language using tools like emscripten, or loaded and run the code yourself, the next step is to learn more about using the other features of the webassembly javascript api. this article teaches you what you’ll need to know. note: if you are unfamiliar with the basic concepts mentioned in this article and need more explanation, read webassembly concepts first, then come back. some simple examples let’s run through some examples that explain how to use the webassembly javascript api, and how to use it to load a wasm module in a web page. note: you can find the sample code in our webassembly-examples github repo. preparing the example first we need a wasm module! grab our simple.wasm file and save a copy in a new directory on your...
...c (export "exported_func") i32.const 42 call $i)) in the second line, you will see that the import has a two-level namespace — the internal function $i is imported from imports.imported_func. we need to reflect this two-level namespace in javascript when writing the object to be imported into the wasm module. create a <script></script> element in your html file, and add the following code to it: var importobject = { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources. this is achieved using the webassembly.compilestreaming() and webassembly.instantiatestreaming() methods. these methods are easier than their non-streaming coun...
... { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources. this is achieved using the webassembly.compilestreaming() and webassembly.instantiatestreaming() methods. these methods are easier than their non-streaming counterparts, because they can turn the byte code directly into module/instance instances, cutting out the need to separately put the response into an arraybuffer. this example (see our instantiate-streaming.html demo on github, and view it live also) shows how to use instantiatestreaming() to fetch a wasm module, import a javascript function into it, compile and instantiate it, and access its exported function — all in one step. add the fol...
...And 12 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
fuse simple tests. introduction in an ideal world, we could author html, xml, css and javascript and only worry about the w3c and ecma standards. however, we don't quite live in such a world yet. due to bugs, incomplete implementations of the standards and legacy browsers, web developers must be able to determine which browser a visitor is using and provide the appropriate content and scripting code path. although browser detection is perhaps the most common scripting task that every web developer faces, it seems that the variety of different strategies in use for detecting browsers is unlimited. as a member of the netscape evangelism team who has spent over a year investigating existing web content, i can say without a doubt that most compatibility problems found on the web today are due t...
...l 1.0 and rfc 2068 - hypertext transfer protocol 1.1). the most common approach at this time was to distinguish user agents by vendor and version using the reported user agent string. although this approach was considered reasonable at the time, this approach caused problems for browser vendors right from the beginning. the original netscape browsers used a user agent string which began with the code name for the netscape browser followed by its version number, e.g. mozilla/version followed by a comment token which gave additional information regarding the operating system being used, etc. since the earliest browser detection techniques were based upon looking for a netscape based browser and only provided customized content to browsers which used the mozilla/version user agent string, other ...
..., etc. since the earliest browser detection techniques were based upon looking for a netscape based browser and only provided customized content to browsers which used the mozilla/version user agent string, other browser vendors standardized on using mozilla/version to signal that they were compatible with a particular netscape version. since other browsers pretended to be netscape browsers and encoded their version information in a non-standard fashion in the user agent comment area, the task of determining which browser was being used became more complicated than it should have been. netscape navigator 2 introduced the ability to run javascript in web browsers. as browser evolution continued, differences in the implementation of scripting and the objects supported by browsers appeared. web ...
...And 11 more matches
Getting started with React - Learn web development
om are often discussed in the same spaces as — and utilized to solve the same problems as — other true web development frameworks. when we refer to react as a "framework", we’re working with that colloquial understanding. react's primary goal is to minimize the bugs that occur when developers are building uis. it does this through the use of components — self-contained, logical pieces of code that describe a portion of the user interface. these components can be composed together to create a full ui, and react abstracts away much of the rendering work, leaving you to concentrate on the ui design. use cases unlike the other frameworks covered in this module, react does not enforce strict rules around code conventions or file organization. this allows teams to set conventions that wor...
... for small pieces of an interface, it's not as easy to "drop into" an application as a library like jquery, or even a framework like vue — it is more approachable when you build your entire app with react. in addition, many of the developer-experience benefits of a react app, such as writing interfaces with jsx, require a compilation process. adding a compiler like babel to a website makes the code on it run slowly, so developers often set up such tooling with a build step. react arguably has a heavy tooling requirement, but it can be learned. this article is going to focus on the use case of using react to render the entire user interface of an application, using tooling provided by facebook’s own create-react-app tool. how does react use javascript? react utilizes features of modern ...
...cle is going to focus on the use case of using react to render the entire user interface of an application, using tooling provided by facebook’s own create-react-app tool. how does react use javascript? react utilizes features of modern javascript for many of its patterns. its biggest departure from javascript comes with the use of jsx syntax. jsx extends javascript's syntax so that html-like code can live alongside it. for example: const heading = <h1>mozilla developer network</h1>; this heading constant is known as a jsx expression. react can use it to render that <h1> tag in our app. suppose we wanted to wrap our heading in a <header> tag, for semantic reasons? the jsx approach allows us to nest our elements within each other, just like we do with html: const header = ( <header> ...
...And 11 more matches
Eclipse CDT
therefore, it is not recommended for use if your machine only has 4 gb of ram. installing eclipse regarding llvm4eclipsecdt, do not install or select this toolchain for mozilla development. ...
...therefore, it is not recommended for use if your machine only has 4 gb of ram. installing eclipse regarding llvm4eclipsecdt, do not install or select this toolchain for mozilla development. ...
... can increase eclipse's memory limits using the eclipse.ini that lives alongside the eclipse binary. set an initial heap space of 1 gb and max heap space of 5 gb, say, by modifying the values of the following two lines in eclipse.ini: -xms1g -xmx5g if you fail to increase these limits, then you will likely find that eclipse either hangs when it tries to index the mozilla source or else that the code intelligence is very broken after the indexing "completes". express setup for the eclipse indexer to work well you must first build mozilla, so that it includes headers from the objdir etc. these can be found and processed by eclipse. note: your moz_objdir must be outside the mozilla source directory. once your build is complete, mach can then generate a useful eclipse project on your behal...
...And 11 more matches
IPDL Tutorial
all messages for multi-process plugins and tabs in firefox are declared in the ipdl language. to experiment with adding a new ipdl protocol, see creating a new protocol. all ipdl messages are sent between parent and a child end points, called actors. an ipdl protocol declares how actors communicate: it declares the possible messages that may be sent between actors, as well as a state machine describing when messages are allowed to be sent. ...
...ed to be sent. the parent actor is typically the more permanent side of the conversation: parent/child actors parent child ipc tabs chrome process content process ipc plugins content process plugin process each protocol is declared in a separate file. the ipdl compiler generates several c++ headers from each ipdl protocol. ...
...t process plugin process each protocol is declared in a separate file. the ipdl compiler generates several c++ headers from each ipdl protocol. this generated code manages the details of the underlying communication layer (sockets and pipes), constructing and sending messages, ensuring that all actors adhere to their specifications, and handling many error conditions. the following ipdl code defines a very basic interaction of browser and plugin actors: async protocol pplugin { child: async init(nscstring pluginpath); async shutdown(); parent: async ready(); }; this code declares the pplugin protocol. two messages can be sent from the parent to the child, init() and shutdown(). one message can be sent from the child to the parent, ready(). ipdl protocols start with the let...
...And 11 more matches
Utility functions
the public functions listed here perform initialization tasks and other services. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
...nction listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
... reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
...And 11 more matches
Introduction to the JavaScript shell
to get the spidermonkey javascript shell, see the spidermonkey build documentation or download a compiled binary for your platform from the nightly builds. ...
...hells. note: starting with spidermonkey 44 (firefox 44 / thunderbird 44 / seamonkey 2.41), the standard, web-compatible javascript version is used by default (and not js1.7+ anymore). the version() shell builtin is still there for testing legacy features. running the javascript shell the shell offers two modes of operation. you can use it as an interactive shell, in which you type javascript code at a prompt and get instant gratification, which is handy for experimenting or testing new features. you can also pass in, on the command line, a javascript program file to run, in which case the program is run automatically. after following the build documentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ if you get "...
...mentation and installing the built shell using make install, you can run the shell in interactive mode using the command: js [ if you get " symbol lookup error: ./js: undefined symbol: pr_setcurrentthreadname" e.g. from a bash console when using a pre-compiled binary, try <path to your firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me] if you'd like to run the javascript code in the file foo.js, you can use this command: js foo.js to run foo.js then drop into the interactive shell, do this: js -f foo.js -i reference note: because the javascript shell is used as a test environment for the javascript engine, the available options and built-in functions can change over time. command line options there are a number of command line options you can specify to contr...
...And 11 more matches
JS::CompileOptions
ntents. to counter this attack, html5 specifies that script errors should be sanitized ("muted") when the script is not same-origin with the global for which it is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. const char *filename() const returns filename of the source code. ...
...source belongs to a dom element in the following cases: source belongs to a <script> element if it is the element's text content (that is, it is written out as the body of the <script> element in the markup text), or is the source document referenced by its src attribute. ...
...onst char *intro, unsigned line, jsscript *script, uint32_t offset) compileoptions &maybemakestrictmode(bool strict) properties properties of js::readonlycompileoptions name type description version jsversion version of the script. versionset bool true if version is set. ...
...And 11 more matches
nsIWebBrowserPersist
ks 4096 fail on broken in-line links. persist_flags_cleanup_on_failure 8192 automatically cleanup after a failed or cancelled operation, deleting all created files and directories. this flag does nothing for failed upload operations to remote servers. persist_flags_autodetect_apply_conversion 16384 let the webbrowserpersist decide whether the incoming data is encoded and whether it needs to go through a content converter, for example to decompress it. persist_flags_append_to_file 32768 append the downloaded data to the target file. this can only be used when persisting to a local file. persist_flags_force_allow_cookies 65536 force relevant cookies to be sent with this load even if normally they wouldn't be. persist_s...
...used when persisting to a local file. persist_flags_force_allow_cookies 65536 force relevant cookies to be sent with this load even if normally they wouldn't be. persist_state_ready 1 persister is ready to save data. persist_state_saving 2 persister is saving data. persist_state_finished 3 persister has finished saving data. ...
...ies to be sent with this load even if normally they wouldn't be. persist_state_ready 1 persister is ready to save data. persist_state_saving 2 persister is saving data. persist_state_finished 3 persister has finished saving data. encode_flags_selection_only 1 output only the current selection as opposed to the whole document. encode_flags_formatted 2 for plain text output. convert html to plain text that looks like the html. implies wrap (except inside <pre>), since html wraps. html output: always do prettyprinting, ignoring existing formatting. encode_flags_raw 4 output without formatting or wrapping the content. this flag may be used to preserve the original formatting as much as possible. enc...
...And 11 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
g of tasks and microtasks, there are things about how the javascript runtime operates under the hood that may be useful to understand. that's what this section covers introduction javascript is an inherently single-threaded language. it was designed in an era in which this was a positive choice; there were few multi-processor computers available to the general public, and the expected amount of code that would be handled by javascript was relatively low at that time. as time passed, of course, we know that computers have evolved into powerful multi-core systems, and javascript has become one of the most prolifically-used languages in the computing world. a vast number of the most popular applications are based at least in part on javascript code. to support this, it was necessary to find wa...
...s as part of the web api (settimeout() and setinterval()), the javascript environment provided by web browsers has gradually advanced to include powerful features that enable scheduling of tasks, multi-threaded application development, and so forth. to understand where queuemicrotask() comes into play here, it's helpful to understand how the javascript runtime operates when scheduling and running code. javascript execution contexts note: the details here are generally not important to most javascript programmers. this information is provided as a basis for why microtasks are useful and how they function; if you don't care, you can skip this and come back later if you find that you need to. when a fragment of javascript code runs, it runs inside an execution context. there are three types ...
...javascript execution contexts note: the details here are generally not important to most javascript programmers. this information is provided as a basis for why microtasks are useful and how they function; if you don't care, you can skip this and come back later if you find that you need to. when a fragment of javascript code runs, it runs inside an execution context. there are three types of code that create a new execution context: the global context is the execution context created to run the main body of your code; that is, any code that exists outside of a javascript function. each function is run within its own execution context. this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new execution context. each context is, in ...
...And 11 more matches
Using Web Workers - Web APIs
web workers are a simple means for web content to run scripts in background threads. the worker thread can perform tasks without interfering with the user interface. in addition, they can perform i/o using xmlhttprequest (although the responsexml and channel attributes are always null). once created, a worker can send messages to the javascript code that created it by posting messages to an event handler specified by that code (and vice versa). this article provides a detailed introduction to using web workers. web workers api a worker is an object created using a constructor (e.g. worker()) that runs a named javascript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. thus, using the win...
...the case of dedicated workers (standard workers that are utilized by a single script; shared workers use sharedworkerglobalscope). a dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts. note: see the web workers api landing page for reference documentation on workers and additional guides. you can run whatever code you like inside the worker thread, with some exceptions. for example, you can't directly manipulate the dom from inside a worker, or use some default methods and properties of the window object. but you can use a large number of items available under window, including websockets, and data storage mechanisms like indexeddb. see functions and classes available to workers for more details. data is ...
...er, multiplied together, and the result is returned to the page and displayed. this example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. more advanced details are covered later on in the article. worker feature detection for slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js): if (window.worker) { ... } spawning a dedicated worker creating a new worker is simple. all you need to do is call the worker() constructor, specifying the uri of a script to execute in the worker thread (main.js): var myworker = new worker('worker.js'); sending messages to and from a dedicated worker the magic of workers happens via the postmessage() meth...
...And 11 more matches
WindowOrWorkerGlobalScope.btoa() - Web APIs
the windoworworkerglobalscope.btoa() method creates a base64-encoded ascii string from a binary string (i.e., a string object in which each character in the string is treated as a byte of binary data). you can use this method to encode data which may otherwise cause communication problems, transmit it, then use the atob() method to decode the data again. for example, you can encode control characters such as ascii values 0 through 31. syntax var encodeddata = scope.btoa(stringtoencode); parameters stringtoencode the binary string to encode. return value an ascii string containing the base64 representation of stringtoencode. exceptions invalidcharactererror the string contained a character that did not fit in a single byte. see "unicode strings" below for more detail. example...
...ascii values 0 through 31. syntax var encodeddata = scope.btoa(stringtoencode); parameters stringtoencode the binary string to encode. return value an ascii string containing the base64 representation of stringtoencode. exceptions invalidcharactererror the string contained a character that did not fit in a single byte. see "unicode strings" below for more detail. example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string unicode strings the btoa() function takes a javascript string as a parameter. in javascript strings are represented using the utf-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. every ascii character fits into the fir...
...e of one of these units, but many other characters don't. base64, by design, expects binary data as its input. in terms of javascript strings, this means strings in which each character occupies only one byte. ...
...And 11 more matches
Setting up adaptive streaming media sources - Developer guides
ost modern browsers. mpeg-dash hls (http live streaming) in order to adaptively stream media we need to split the media up into chunks. we are required to provide several different quality files split up over several time points. the more qualities and time points there are, the more 'adaptive' your stream will be, but we will usually want to find a pragmatic balance between size, time to encode and adaptiveness. the good news is that once we have encoded our media in the appropriate format we are pretty good to go. for adaptive streaming over http, no special server-side components are required. both mpeg-dash and hls use a playlist format to structure the component piece of media that make the possible streams. various bitrate streams are broken into segments and placed in appropriat...
...s. a media presentation description (mpd) file is used to hold the information on the various streams and the bandwidths they are associated with. in your video source (src) attribute you point to the mpd instead of to the media file as you would with non-adaptive media. the mpd file tells the browser where the various pieces of media are located, it also includes meta data such as mimetype and codecs and there are other details such as byte-ranges in there too - it is an xml document and in many cases will be generated for you. there are a few profiles we can use. we're going to take a look at ondemand profile for video on demand (vod) and the live profile. for live services streaming, the live profile is a requirement. the stream switching capabilities are identical between the profiles.
...w3.org/2001/xmlschema-instance" xmlns="urn:mpeg:dash:schema:mpd:2011" xsi:schemalocation="urn:mpeg:dash:schema:mpd:2011 dash-mpd.xsd" type="static" mediapresentationduration="pt654s" minbuffertime="pt2s" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011"> <baseurl>http://example.com/ondemand/</baseurl> <period> <!-- english audio --> <adaptationset mimetype="audio/mp4" codecs="mp4a.40.5" lang="en" subsegmentalignment="true" subsegmentstartswithsap="1"> <representation id="1" bandwidth="64000"> <baseurl>elephantsdream_aac48k_064.mp4.dash</baseurl> </representation> </adaptationset> <!-- video --> <adaptationset mimetype="video/mp4" codecs="avc1.42401e" subsegmentalignment="true" subsegmentstartswithsap="1"> <representation id="2"...
...And 11 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
using eval in add-ons is almost always unnecessary, and many times even a security vulnerability. moreover, code using eval is harder to parse for a human mind, is often pretty complex, and relies on assumptions that are not necessarily true in the future or even now. this article is aimed at presenting alternatives to common eval uses in add-ons and other javascript code. add-on authors are strongly encouraged to update their code to eliminate all instances of eval, no matter if the add-on is to be hosted in the mozilla add-ons gallery or not. in order to host your add-on with mozilla it is crucial to minimize or completely eliminate eval use in order to receive a positive review and have your add-on made public. if it cannot be easily proven that an eval() call is benign and necessary be...
...because there are no viable alternatives, a mozilla add-ons gallery reviewer will generally reject the submission! parsing json mozilla provides native json support since firefox 3. there is simply no need to parse json using eval. additionally, parsing json retrieved from a remote location becomes a security vulnerability when parsed with the eval function. basically, you are executing remote code with full chrome access; that is, introducing a remote code execution vulnerability. even if you trust the remote server; for example, because it is one you rent and administer yourself, there is a huge security risk, because of, but not limited to: you might discontinue your project or sell it, so that it is possible another person with malicious intentions takes over your domain. the server...
... you rent and administer yourself, there is a huge security risk, because of, but not limited to: you might discontinue your project or sell it, so that it is possible another person with malicious intentions takes over your domain. the server and/or domain name might be compromised. if using an unencrypted, insecure connection, a man-in-the-middle attacker might replace the json with attack code before it arrives at the user. use native json since firefox 3.5 you should use json. really, just use it! note: do not use json parsers implemented in javascript. these implementations are less efficient and often also contain serious security vulnerabilities. such implementations are meant to be used within a very different security context, namely a website, where the origin of the data is...
...And 10 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
rowsing, a simple request to retrieve the next set of message headers that replace the currently viewed message headers can dramatically improve user experience. implementing inner-browsing on top of html pages modern browsers have good support for the w3c dom and javascript allowing fine-grained control over page content. instead of forcing the reader to follow links to new pages, the javascript code can act as the mediator for information access. if the user clicks on a link item, the script will be responsible to load the information from the data source and to apply that into the current document. there are basically two steps in this process: data load: acquisition of information data acquisition can be implemented using javascript and remote procedure calls using soap-based rpc mechanism...
...sts retrieving different contents at the same time. example using iframes and javascript: stock ticker this section describes a stock ticker application based on the inner-browsing model. the stock ticker is a web page with a stock ticker element that displays updated stock symbol information. the web page receives updates to its contents but only redraws the stock ticker element information. the code includes the dhtml element. we've separated this sample in two main components following the model. the data loader module and the data binder module. the data loader module is responsible for the requests and retrieves the stock data information from the web. it also sends an event to the data binder module. the data binder module is responsible for the binding of the data with the html interfac...
... components following the model. the data loader module and the data binder module. the data loader module is responsible for the requests and retrieves the stock data information from the web. it also sends an event to the data binder module. the data binder module is responsible for the binding of the data with the html interface. in addition to these components, you will also find the piece of code that is responsible for the dhtml ticker. note that the ticker is a completely separated component. the data binder will put the content in the proper place, so the existing dhtml ticker application is able to handle it. special markup to support the model it's important to add special markup that fulfills the requirements of the application. this example uses an iframe element as the mechanism t...
...And 10 more matches
Nanojit - Archive of obsolete content
overview nanojit is a small, cross-platform c++ library that emits machine code. both the tamarin jit and the spidermonkey jit (a.k.a. tracemonkey) use nanojit as their back end. you can get nanojit by cloning the tamarin-redux mercurial repository at http://hg.mozilla.org/tamarin-redux. it's in the nanojit directory. the input for nanojit is a stream of nanojit lir instructions. the term lir is compiler jargon for a language used internally in a compiler that is usually cross-platform but very close to machine language. it is an acronym for "low-level intermediate representation". a compiler's lir is typically one of several partly-compiled representations of a program that a compiler produces on the way from raw source code to machine code. an application using nanojit creates a ...
... lirwriter objects, all of which implement the same interface as lirbufwriter. this chain of lirwriter objects forms a pipeline for the instructions to pass through. each lirwriter can perform an optimization or other task on the program as it passes through the system and into the lirbuffer. once the instructions are in the lirbuffer, the application calls nanojit::compile() to produce machine code, which is stored in a nanojit::fragment. internally to nanojit, another set of filters operates on the lir as it passes from the lirbuffer toward the assembler. the result of compilation is a function that the application can call from c via a pointer to the first instruction. example the following code works with spidermonkey's hacked version of nanojit. figuring out how to compile it is left...
...e "jsapi.h" #include "jstracer.h" #include "nanojit.h" using namespace nanojit; const uint32_t cache_size_log2 = 20; static avmplus::gc gc = avmplus::gc(); static avmplus::avmcore core = avmplus::avmcore(); int main() { logcontrol lc; #ifdef debug lc.lcbits = lc_readlir | lc_assembly; #else lc.lcbits = 0; #endif // set up the basic nanojit objects. ...
...And 10 more matches
Building up a basic demo with Babylon.js - Game development
babylon.js is one of the most popular 3d game engines used by developers. as with any other 3d library it provides built-in functions to help you implement common 3d functionality more quickly. in this article we'll take you through the real basics of using babylon.js, including setting up a development environment, structuring the necessary html, and writing the javascript code. we will try to create a simple demo first — a cube rendered on the screen. if you have already worked through our building up a basic demo series with three.js, playcanvas or a-frame (or you are familiar with other 3d libraries) you'll notice that babylon.js works on similar concepts: camera, light and objects. environment setup to start developing with babylon.js, you don't need much. you should start of...
...there is on...
...s"); /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element (which babylon.js will use to render the content on) to fill the entire available viewport space. the first <script> element includes the babylon.js library in the page; we will write our example code in the second one. there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. initialising the babylon.js engine we have to create a babylon.js engine instance first (passing it the <canvas> element to render on) before we start developing our game...
...And 10 more matches
GLSL Shaders - Game development
ex shaders and fragment (pixel) shaders. vertex shaders transform shape positions into 3d drawing coordinates. fragment shaders compute the renderings of a shape's colors and other attributes. glsl is not as intuitive as javascript. glsl is strongly typed and there is a lot of math involving vectors and matrices. it can get very complicated — very quickly. in this article we will make a simple code example that renders a cube. to speed up the background code we will be using the three.js api. as you may remember from the basic theory article, a vertex is a point in a 3d coordinate system. vertices may, and usually do, have additional properties. the 3d coordinate system defines space and the vertices help define shapes in that space. shader types a shader is essentially a function requir...
...e and the vertices help define shapes in that space. shader types a shader is essentially a function required to draw something on the screen. shaders run on a gpu (graphics processing unit), which is optimized for such operations. using a gpu to deal with shaders offloads some of the number crunching from the cpu. this allows the cpu to focus its processing power on other tasks, like executing code. vertex shaders vertex shaders manipulate coordinates in a 3d space and are called once per vertex. the purpose of the vertex shader is to set up the gl_position variable — this is a special, global, and built-in glsl variable. gl_position is used to store the position of the current vertex. the void main() function is a standard way of defining the gl_position variable. everything inside v...
...on about the rgba color. 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 brows...
...And 10 more matches
Client-side form validation - Learn web development
t types of client-side validation that you'll encounter on the web: built-in form validation uses html5 form validation features, which we've discussed in many places throughout this module. this validation generally doesn't require much javascript. built-in form validation has better performance than javascript, but it is not as customizable as javascript validation. javascript validation is coded using javascript. this validation is completely customizable, but you need to create it all (or use a library). using built-in form validation one of the most significant features of html5 form controls is the ability to validate most user data without relying on javascript. this is done by using validation attributes on form elements. we've seen many of these earlier in the course, but to re...
...mismatch, valuemissing, or a customerror. built-in form validation examples in this section, we'll test out some of the attributes that we discussed above. simple start file let's start with a simple example: an input that allows you to choose whether you prefer a banana or a cherry. this example involves a simple text <input> with an associated <label> and a submit <button>. find the source code on github at fruit-start.html and a live example below. <form> <label for="choose">would you prefer a banana or cherry?</label> <input id="choose" name="i_like"> <button>submit</button> </form> input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } to begin, make a copy of fruit-start.html in a new directory on your hard drive. the required attribute ...
...ghtgreen); } input:valid { border: 2px solid black; } this css causes the input to have a red dashed border when it is invalid and a more subtle solid black border when valid. we also added a background gradient when the input is required and invalid. try out the new behavior in the example below: note: you can find this example live on github as fruit-validation.html (see also the source code.) try submitting the form without a value. note how the invalid input gets focus, a default error message ("please fill out this field") appears, and the form is prevented from being sent. the presence of the required attribute on any element that supports this attribute means the element matches the :required pseudoclass whether it has a value or not. if the <input> has no value, the input wi...
...And 10 more matches
Sending forms through JavaScript - Learn web development
h stands for "asynchronous javascript and xml". how is it different? the xmlhttprequest (xhr) dom object can build http requests, send them, and retrieve their results. historically, xmlhttprequest was designed to fetch and send xml as an exchange format, which has since been superceded by json. but neither xml nor json fit into form data request encoding. form data (application/x-www-form-urlencoded) is made of url-encoded lists of key/value pairs. for transmitting binary data, the http request is reshaped into multipart/form-data. note: the fetch api is often used in place of xhr these days — it is a modern, updated version of xhr, which works in a similar fashion but has some advantages. most of the xhr code you'll see in this article could be swapped out for fetch. if you control t...
... but if you want to use a third party service, you need to send the data in the format the services require. so how should we send such data? the different techniques you'll require are done below. ...
...ata, the http request is reshaped into multipart/form-data. note: the fetch api is often used in place of xhr these days — it is a modern, updated version of xhr, which works in a similar fashion but has some advantages. most of the xhr code you'll see in this article could be swapped out for fetch. if you control the front-end (the code that's executed in the browser) and the back-end (the code which is executed on the server), you can send json/xml and process them however you want. but if you want to use a third party service, you need to send the data in the format the services require. so how should we send such data? the different techniques you'll require are done below. sending form data there are 3 ways to send form data: building an xmlhttprequest manually. using a stan...
...And 10 more matches
Fetching data from the server - Learn web development
e a long time. to begin this example, make a local copy of ajax-start.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt — in a new directory on your computer. in this example, we will load a different verse of the poem (which you may well recognize) via xhr when it's selected in the drop-down menu. just inside the <script> element, add the following code. this stores a reference to the <select> and <pre> elements in constants and defines an onchange event handler function so that when the select's value is changed, its value is passed to an invoked function updatedisplay() as a parameter. const versechoose = document.queryselector('select'); const poemdisplay = document.queryselector('pre'); versechoose.onchange = function() { const verse =...
...ue is changed, its value is passed to an invoked function updatedisplay() as a parameter. const versechoose = document.queryselector('select'); const poemdisplay = document.queryselector('pre'); versechoose.onchange = function() { const verse = versechoose.value; updatedisplay(verse); }; let's define our updatedisplay() function. first of all, put the following beneath your previous code block — this is the empty shell of the function. note: steps 4 - 9 will all be performed within this function. function updatedisplay(verse) { } we'll start our function by constructing a relative url pointing to the text file we want to load, as we'll need it later. the value of the <select> element at any time is the same as the text inside the selected <option> (unless you specify ...
... it to, which is done using the send() method. add the following below your previous addition to complete the function. this line should rest just above the closing curly brace of your updatedisplay() function. request.send(); one problem with the example as it stands is that it won't show any of the poem when it first loads. to fix this, add the following two lines at the bottom of your code (just above the closing </script> tag) to load verse 1 by default, and make sure the <select> element always shows the correct value: updatedisplay('verse 1'); versechoose.value = 'verse 1'; serving your example from a server modern browsers will not run xhr requests if you just run the example from a local file. this is because of security restrictions (for more on web security, read web...
...And 10 more matches
Introduction to web APIs - Learn web development
overview: client-side web apis next first up, we'll start by looking at apis from a high level — what are they, how do they work, how to use them in your code, and how are they structured? ...
...how are they structured? we'll also take a look at what the different main classes of apis are, and what kind of uses they have. prerequisites: basic computer literacy, a basic understanding of html and css, javascript basics (see first steps, building blocks, javascript objects). objective: to gain familiarity with apis, what they can do, and how you can use them in your code. what are apis? application programming interfaces (apis) are constructs made available in programming languages to allow developers to create complex functionality more easily. they abstract more complex code away from you, providing some easier syntax to use in its place. as a real-world example, think about the electricity supply in your house, apartment, or other dwellings. if you wa...
...would be really inefficient and, if you are not an electrician, difficult and dangerous to attempt. image source: overloaded plug socket by the clear communication people, on flickr. in the same way, if you want to say, program some 3d graphics, it is a lot easier to do it using an api written in a higher-level language such as javascript or python, rather than try to directly write low level code (say c or c++) that directly controls the computer's gpu or other graphics functions. note: see also the api glossary entry for further description. apis in client-side javascript client-side javascript, in particular, has many apis available to it — these are not part of the javascript language itself, rather they are built on top of the core javascript language, providing you with extra ...
...And 10 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
hods and variables. the following new components will be developed throughout the course of this article: moreactions: displays the check all and remove completed buttons, and emits the corresponding events required to handle their functionality. newtodo: displays the <input> field and add button for adding a new todo. todosstatus: displays the "x out of y items completed" status heading. ...
...e github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/05-advanced-concepts or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts remember to run npm install && npm run dev to start your app in development mode. repl to code along with us using the repl, start at https://svelte.dev/repl/76cc90c43a37452e8c7f70521f88b698?version=3.23.2 working on the moreactions component now we'll tackle the check all and remove completed buttons. let's create a component that will be in charge of displaying the buttons and emitting the corresponding events. create a new file — components/moreactions.svelte. when the ...
...ynced with the "real" dom. this is much faster than directly updating the dom and allows the framework to apply many optimization techniques. these frameworks, by default, basically re-run all our javascript on every change against this virtual dom, and apply different methods to cache expensive calculations and optimize execution. they make little to no attempt to understand what our javascript code is doing. svelte doesn't use a virtual dom representation. instead, it parses and analyzes our code, creates a dependency tree, and then generates the required javascript to update only the parts of the dom that need to be updated. this approach usually generates optimal javascript code with minimal overhead, but it also has its limitations. sometimes svelte cannot detect changes to variables b...
...And 10 more matches
Obsolete Build Caveats and Tips
these tips, while helpful, are jarring and superfluous to the majority of new mozilla builders who are mainly interested in building the latest version of firefox. therefore, instead of deleting all these nuggets of information, it's best to collect them all here and remove them from the majority happy path documentation. each piece of information should mention the page and the section it originally came from. ...
... this note below seems redundant as this is true by default https://msdn.microsoft.com/en-us/library/dh8che7s%28v=vs.110%29.aspx note: starting with gecko 7.0, you should no longer include "-zc:wchar_t-" in the command line when...
...2008 pro or express with sp1 (free) (warning ! from firefox 10, the compilator is visual studio 2010; if you want to use it, you must use a previous version of it !), or 2005 professional from build_instructions those who need to work with the code for firefox 3/mozilla 1.9 and earlier can check out the latest source using cvs. in reality, you should probably not need to do this, since that code is very obsolete. this note below seems redundant as this is true by default https://msdn.microsoft.com/en-us/library/dh8che7s%28v=vs.110%29.aspx note: starting with gecko 7.0, you should no longer include "-zc:wchar_t-" in the command line when building on windows. if you're using visual studio, go to project properties > c/c++ > language > treat wchar_t as built-in type and set it to "yes".
...And 10 more matches
nsIDocShell
obsolete since gecko 1.8 nsisimpleenumerator getdocshellenumerator(in long aitemtype, in long adirection); nsidomstorage getsessionstorageforprincipal(in nsiprincipal principal, in domstring documenturi, in boolean create); nsidomstorage getsessionstorageforuri(in nsiuri uri, in domstring documenturi); ...
...er, in boolean top); void createaboutblankcontentviewer(in nsiprincipal aprincipal); void createloadinfo(out nsidocshellloadinfo loadinfo); void detacheditorfromwindow(); violates the xpcom interface guidelines void finishrestore(); void firepagehidenotification(in boolean isunload); native code only! void fireunloadnotification(); native code only! obsolete since gecko 1.8 nsisimpleenumerator getdocshellenumerator(in long aitemtype, in long adirection); nsidomstorage getsessionstorageforprincipal(in nsiprincipal principal, in domstring documenturi, in boolean create); nsidomstorage getsessionstorageforuri(in nsiuri uri, in domstring documenturi); void historypurged(in long numentries); v...
... void preparefornewcontentmodel...
...And 10 more matches
Add to iPhoto
o "add image to iphoto". choose it, and iphoto will start up (if it's not already running) and import the image. declaring the apis the first thing we have to do is declare the mac os x apis we'll be using. this extension uses a number of methods and data types, as well as constants, from three system frameworks. ...
...) and import the image. declaring the apis the first thing we have to do is declare the mac os x apis we'll be using. this extension uses a number of methods and data types, as well as constants, from three system frameworks. since a lot of this stuff is repetitive, we'll only look at selected parts of the code to get an idea how things work. you can download the extension and poke through the code inside it if you'd like to see all of it. for the sake of organization, i chose to implement each system framework (and, mind you, i only declare the apis i actually use, not all of them) as a javascript object containing all the types and methods that framework's api. note: in a few cases, this code takes the easy way out by using ctypes.voidptr_t instead of a typed pointer. that's not really ...
...s the easy way out by using ctypes.voidptr_t instead of a typed pointer. that's not really the ideal way to do things but saved some time for this simple example. some of this may change as i refine the example in the future; i'll update the article if and when that happens. some global types there are a few global data types used by all of our frameworks. these are declared near the top of the code: const osstatus = ctypes.int32_t; const cfindex = ctypes.long; const optionbits = ctypes.uint32_t; osstatus used to represent the status code resulting from an operation. cfindex a core foundation long integer type used to represent indexes into lists. i debated including this in the corefoundation object, and probably would have if i were being more formal, but opted against it for clari...
...And 10 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
ugh the windoworworkerglobalscope mixin. tasks vs microtasks to properly discuss microtasks, it's first useful to know what a javascript task is and how microtasks differ from tasks. this is a quick, simplified explanation, but if you would like more details, you can read the information in the article in depth: microtasks and the javascript runtime environment. tasks a task is any javascript code which is scheduled to be run by the standard mechanisms such as initially starting to run a program, an event callback being run, or an interval or timeout being fired. these all get scheduled on the task queue. tasks get added to the task queue when: a new javascript program or subprogram is executed (such as from a console, or by running the code in a <script> element) directly. an event f...
...only tasks which were already in the task queue when the event loop pass began will be executed during the current iteration. the rest will have to wait until the following iteration. ...
...de handles these tasks one after another, in the order in which they were enqueued. only tasks which were already in the task queue when the event loop pass began will be executed during the current iteration. the rest will have to wait until the following iteration. microtasks at first the difference between microtasks and tasks seems minor. and they are similar; both are made up of javascript code which gets placed on a queue and run at an appropriate time. however, whereas the event loop runs only the tasks present on the queue when the iteration began, one after another, it handles the microtask queue very differently. there are two key differences. first, each time a task exits, the event loop checks to see if the task is returning control to other javascript code. if not, it runs all...
...And 10 more matches
Using Service Workers - Web APIs
rience even when offline, before then getting more data from the network (commonly known as offline first). this is already available with native apps, which is one of the main reasons native apps are often chosen over web apps. setting up to play with service workers many service workers features are now enabled by default in newer versions of supporting browsers. if however you find that demo code is not working in your installed versions, you might need to enable a pref: firefox nightly: go to about:config and set dom.serviceworkers.enabled to true; restart browser. chrome canary: go to chrome://flags and turn on experimental-web-platform-features; restart browser (note that some features are now enabled by default in chrome.) opera: go to opera://flags and enable support for service...
...abled to true; restart browser. chrome canary: go to chrome://flags and turn on experimental-web-platform-features; restart browser (note that some features are now enabled by default in chrome.) opera: go to opera://flags and enable support for serviceworker; restart browser. microsoft edge: go to about:flags and tick enable service workers; restart browser. you’ll also need to serve your code via https — service workers are restricted to running across https for security reasons. github is therefore a good place to host experiments, as it supports https. in order to facilitate local development, localhost is considered a secure origin by browsers as well. basic architecture with service workers, the following steps are generally observed for basic set up: the service worker url...
...pare a traditional synchronous callback structure to its asynchronous promise equivalent. sync try { const value = myfunction(); console.log(value); } catch(err) { console.log(err); } async myfunction().then((value) => { console.log(value); }).catch((err) => { console.log(err); }); in the first example, we have to wait for myfunction() to run and return value before any more of the code can execute. in the second example, myfunction() returns a promise for value, then the rest of the code can carry on running. when the promise resolves, the code inside then will be run, asynchronously. now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? this is a standard thing to want to d...
...And 10 more matches
SubtleCrypto.verify() - Web APIs
ntered: invalidaccesserror raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. supported algorithms the verify() method supports the same algorithms as the sign() method. examples note: you can try the working examples out on github. ...
...s not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. supported algorithms the verify() method supports the same algorithms as the sign() method. examples note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code uses a public key to verify a signature. see the complete code on github. ...
... an algorithm that is either unknown or isn't suitable for a verify operation. supported algorithms the verify() method supports the same algorithms as the sign() method. examples note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the "valid" class on the signature. * otherwis...
...And 10 more matches
WebGL model view projection - Web APIs
tion of the clip space that all of the points must fit into. it is a cube two units on each side, with one corner at (-1,-1,-1) and the opposite corner at (1,1,1). the center of the cube is the point (0,0,0). this 8 cubic meter coordinate system used by clip space is known as normalized device coordinates (ndc). you may encouter that term from time to time while researching and wokring with webgl code. for this section we will put our data into the clip space coordinate system directly. normally model data is used that is in some arbitrary coordinate system, and is then transformed using a matrix, converting the model coordinates into the clip space coordinate system. for this example, it's easiest to illustrate how clip space works by simply using model coordinate values ranging from (-1,-1,...
...we will put our data into the clip space coordinate system directly. normally model data is used that is in some arbitrary coordinate system, and is then transformed using a matrix, converting the model coordinates into the clip space coordinate system. for this example, it's easiest to illustrate how clip space works by simply using model coordinate values ranging from (-1,-1,-1) to (1,1,1). ...
...in addition there is a jsfiddle link at the bottom of each section. ...
...And 10 more matches
Writing a WebSocket server in C# - Web APIs
//enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.dataavailable); byte[] bytes = new byte[client.available]; stream.read(bytes, 0, bytes.length); } handshaking when a client connects to a server, it sends a get request to upgrade the connection to a websocket from a simple http request. this is known as handshaking. this sample code can detect a get from the client. note that this will block until the first 3 bytes of a message are available. alternative solutions should be investigated for production environments. using system.text; using system.text.regularexpressions; while(client.available < 3) { // wait for enough bytes to be available } byte[] bytes = new byte[client.available]; stream.read(bytes, 0, bytes.lengt...
...ehash( encoding.utf8.getbytes( new system.text.regularexpressions.regex("sec-websocket-key: (.*)").match(data).groups[1].value.trim() + "258eafa5-e914-47da-95ca-c5ab0dc85b11" ) ) ) + eol + eol); stream.write(response, 0, response.length); } decoding messages after a successful handshake, the client will send encoded messages to the server. if we send "mdn", we get these bytes: 129 131 61 84 35 6 112 16 109 let's take a look at what these bytes mean. the first byte, which currently has a value of 129, is a bitfield that breaks down as such: fin (bit 0) rsv1 (bit 1) rsv2 (bit 2) rsv3 (bit 3) opcode (bit 4:7) 1 0 0 0 0x1=...
...(bit 0) rsv1 (bit 1) rsv2 (bit 2) rsv3 (bit 3) opcode (bit 4:7) 1 0 0 0 0x1=0001 fin bit: this bit indicates whether the full message has been sent from the client. messages may be sent in frames, but for now we will keep things simple. rsv1, rsv2, rsv3: these bits must be 0 unless an extension is negotiated which supplies a nonzero value to them. opcode: these bits describe the type of message received. opcode 0x1 means this is a text message. full list of opcodes the second byte, which currently has a value of 131, is another bitfield that breaks down as such: mask (bit 0) payload length (bit 1:7) 1 0x83=0000011 mask bit: defines whether the "payload data" is masked. if set to 1, a masking key is present...
...And 10 more matches
Using XMLHttpRequest - Web APIs
to address (or point to) parts of it. manually parsing and serializing xml to strings or objects. using xmlserializer to serialize dom trees to strings or to files. regexp can be used if you always know the content of the xml document beforehand. you might want to remove line breaks, if you use regexp to scan with regard to line breaks. however, this method is a "last resort" since if the xml code changes slightly, the method will likely fail. note: xmlhttprequest can now interpret html for you using the responsexml property. read the article about html in xmlhttprequest to learn how to do this. processing a responsetext property containing an html document if you use xmlhttprequest to get the content of a remote html webpage, the responsetext property is a string containing the raw ...
... in the article html in xmlhttprequest. inject the content into the body of a document fragment via fragment.body.innerhtml and traverse the dom of the fragment. regexp can be used if you always know the content of the html responsetext beforehand. you might want to remove line breaks, if you use regexp to scan with regard to linebreaks. however, this method is a "last resort" since if the html code changes slightly, the method will likely fail. handling binary data although xmlhttprequest is most commonly used to send and receive textual data, it can be used to send and receive binary content. there are several well tested methods for coercing the response of an xmlhttprequest into sending binary data. these involve utilizing the overridemimetype() method on the xmlhttprequest object and...
...request submitting forms without the formdata api does not require other apis for most use cases. the only case where you need an additional api is if you want to upload one or more files, where you use the filereader api. a brief introduction to the submit methods an html <form> can be sent in four ways: using the post method and setting the enctype attribute to application/x-www-form-urlencoded (default); using the post method and setting the enctype attribute to text/plain; using the post method and setting the enctype attribute to multipart/form-data; using the get method (in this case the enctype attribute will be ignored). now, consider the submission of a form containing only two fields, named foo and baz. if you are using the post method the server will receive a string simi...
...And 10 more matches
border-color - CSS: Cascading Style Sheets
sl()> = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
...ntage> <percentage> [ / <alpha-value> ]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
...]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? ...
...And 10 more matches
Audio and Video Delivery - Developer guides
ument.createelement('video') perhaps?) deliver the media file to the player. html audio <audio controls preload="auto"> <source src="audiofile.mp3" type="audio/mpeg"> <!-- fallback for browsers that don't support mp3 --> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for browsers that don't support audio tag --> <a href="audiofile.mp3">download audio</a> </audio> the code above will create an audio player that attempts to preload as much audio as possible for smooth playback. note: the preload attribute may be ignored by some mobile browsers. for further info see cross browser audio basics (html5 audio in detail) html video <video controls width="640" height="480" poster="initialimage.png" autoplay muted> <source src="videofile.mp4" type="video/mp4"> <!
...we instruct the video to autoplay but to be muted by default. note: the autoplay attribute may be ignored by some mobile browsers. also, the autoplay feature can be controversial when misused. it's strongly recommended that you read the autoplay guide for media and web audio apis to l...
...dio/ogg')) { myaudio.setattribute('src','audiofile.ogg'); } myaudio.currenttime = 5; myaudio.play(); we set the source of the audio depending on the type of audio file the browser supports, then set the play-head 5 seconds in and attempt to play it. note: play will be ignored by most browsers unless issued by a user-initiated event. it's also possible to feed an <audio> element a base64 encoded wav file, allowing to generate audio on the fly: <audio id="player" src="data:audio/x-wav;base64,uklgrvc..."></audio> speak.js employs this technique. try the demo. javascript video var myvideo = document.createelement('video'); if (myvideo.canplaytype('video/mp4')) { myvideo.setattribute('src','videofile.mp4'); } else if (myvideo.canplaytype('video/webm')) { myvideo.setattribute('src',...
...And 10 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
reported by their operating system, whereas the date/time value is always formatted yyyy-mm-ddthh:mm. when the above value submitted to the server, for example, it will look like partydate=2017-06-01t08:30. note: also bear in mind that if such data is submitted via http get, the colon character will need to be escaped for inclusion in the url parameters, e.g. partydate=2017-06-01t08%3a30. see encodeuri() for one way to do this. you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var datecontrol = document.queryselector('input[type="datetime-local"]'); datecontrol.value = '2017-06-01t08:30'; there are several methods provided by javascript's date that can be used to convert numeric date information into a properly-formatted string,...
...09:50">(gmt -9:30) taiohae</option> <option value="-09:00">(gmt -9:00) alaska</option> <option value="-08:00">(gmt -8:00) pacific time (us &amp; canada)</option> ... </select> in either case, the date/time and time zone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side. note: the above code snippet is taken from all world timezones in an html select element. validation by default, <input type="datetime-local"> does not apply any validation to entered values. the ui implementations generally don't let you enter anything that isn't a date/time — which is helpful — but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of april). ...
...eft: 5px; } important: html form validation is not a substitute for scripts that ensure that the entered data is in the proper format. it's far too easy for someone to make adjustments to the html that allow them to bypass the validation, or to remove it entirely. it's also possible for someone to simply bypass your html entirely and submit the data directly to your server. if your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth). handling browser support as mentioned above, the major problem with using date inputs at the time of writing is browser support — only chrome/opera and edge support it on desktop, and most modern browsers on mobile. as an ...
...And 10 more matches
Browser detection using the user agent - HTTP
fers between browsers, instead of checking the user agent string, you should instead implement a test to detect how the browser implements the api and determine how to use it from that. an example of feature detection is as follows. in 2017, chrome unflagged experimental lookbehind support in regular expressions, but no other browser supported it. ...
...o this: // this code snippet splits a string in a special notation if (navigator.useragent.indexof("chrome") !== -1){ // yes! ...
...])/. it will cause a syntax error in // browsers that do not support look-behind expressions // because all browsers parse the entire script, including // sections of the code that are never executed. ...
...And 10 more matches
Text formatting - JavaScript
each element in the string occupies a position in the string. the first element is at index 0, the next at index 1, and so on. the length of a string is the number of elements in it. you can create strings using string literals or string objects. ...
...ot include any characters above u+ffff, until mdn bug 857438 is fixed ( https://bugzilla.mozilla.org/show_bug.cgi?id=857438 ). string literals you can create simple strings using either single or double quotes: 'foo' "bar" more advanced strings can be created using escape sequences: hexadecimal escape sequences the number after \x is interpreted as a hexadecimal number. ...
...e u+ffff, until mdn bug 857438 is fixed ( https://bugzilla.mozilla.org/show_bug.cgi?id=857438 ). string literals you can create simple strings using either single or double quotes: 'foo' "bar" more advanced strings can be created using escape sequences: hexadecimal escape sequences the number after \x is interpreted as a hexadecimal number. ...
...And 10 more matches
Compiling from Rust to WebAssembly - WebAssembly
if you have some rust code, you can compile it into webassembly (wasm). this tutorial takes you through all you need to know to compile a rust project to wasm and use it in an existing web app. rust and webassembly use cases there are two main use cases for rust and webassembly: to build an entire application — an entire web app based in rust. to build a part of an application — using rust in an existing javascript frontend. for now, the rust team is focusing on the latter case, and so that's what we cover here. for the former case, check out projects like yew. in this tutorial, we build an npm package using wasm-pack, a tool for building npm packages in rust. ...
...sed in rust. to build a part of an application — using rust in an existing javascript frontend. for now, the rust team is focusing on the latter case, and so that's what we cover here. for the former case, check out projects like yew. in this tutorial, we build an npm package using wasm-pack, a tool for building npm packages in rust. this package will contain only webassembly and javascript code, and so the users of the package won't need rust installed. they may not even notice that it's written in webassembly. rust environment setup let's go through all the required steps to get our environment set up. install rust install rust by going to the install rust page and following the instructions. this installs a tool called "rustup", which lets you manage multiple versions of rust. by ...
...ell as cargo, rust's package manager, rust-std, rust's standard libraries, and some helpful docs — rust-docs. note: pay attention to the post-install note about needing cargo's bin directory in your system path. this is added automatically, but you must restart your terminal for it to take effect. wasm-pack to build the package, we need an additional tool, wasm-pack. this helps compile the code to webassembly, as well as produce the right packaging for npm. to download and install it, enter the following command into your terminal: $ cargo install wasm-pack install node.js we are building an npm package in this tutorial, and so you need to have node.js and npm installed. to get node.js and npm, go to the get npm! page and follow the instructions. when it comes to picking a version, ...
...And 10 more matches
Understanding WebAssembly text format - WebAssembly
to enable webassembly to be read and edited by humans, there is a textual representation of the wasm binary format. this is an intermediate form designed to be exposed in text editors, browser developer tools, etc. this article explains how that text format works, in terms of the raw syntax, and how it is related to the underlying bytecode it represents — and the wrapper objects representing wasm in javascript. note: this is potentially overkill if you are a web developer who just wants to load a wasm module into a page and use it in your code (see using the webassembly javascript api), but it is more useful if for example, you want to write wasm modules to optimize the performance of your javascript library, or build your own webassembly compiler. s-expressions in both the binary and ...
... overkill if you are a web developer who just wants to load a wasm module into a page and use it in your code (see using the webassembly javascript api), but it is more useful if for example, you want to write wasm modules to optimize the performance of your javascript library, or build your own webassembly compiler. s-expressions in both the binary and textual formats, the fundamental unit of code in webassembly is a module. in the text format, a module is represented as one big s-expression. s-expressions are a very old and very simple textual format for representing trees, and thus we can think of a module as a tree of nodes that describe the module’s structure and its code. unlike the abstract syntax tree of a programming language, though, webassembly’s tree is pretty flat, mostl...
...ut is still a valid module. if we convert our module to binary now (see converting webassembly text format to wasm), we’ll see just the 8 byte module header described in the binary format: 0000000: 0061 736d ; wasm_binary_magic 0000004: 0100 0000 ; wasm_binary_version adding functionality to your module ok, that’s not very interesting, let’s add some executable code to this module. all code in a webassembly module is grouped into functions, which have the following pseudo-code structure: ( func <signature> <locals> <body> ) the signature declares what the function takes (parameters) and returns (return values). the locals are like vars in javascript, but with explicit types declared. the body is just a linear list of low-level instructions. so this ...
...And 10 more matches
Preferences - Archive of obsolete content
[iid_is(atype), retval] out nsqiresult avalue); void setcomplexvalue(in string aprefname, in nsiidref atype, in nsisupports avalue); as you can see, both of them take a parameter, atype, which can have one of the following values (to be precise, you should pass components.interfaces.nsiwhatever instead of just nsiwhatever, which is undefined). nsisupportsstring used to handle unicode strings in preferences. use this when the preference value may contain non-ascii characters (for example, a user's name). nsipreflocalizedstring almost the same as nsisupportsstring, but it is handled differently in getcomplexvalue() when there's no user value for the given preference; see below for details. nsilocalfile and nsirelativefilepref store paths in preferences. nsilocalfile is used...
...ed differently in getcomplexvalue() when there's no user value for the given preference; see below for details. nsilocalfile and nsirelativefilepref store paths in preferences. nsilocalfile is used to store absolute paths, while nsirelativefilepref is used to store paths relative to a "special" directory, such as the profile folder. ...
...elow for details. nsilocalfile and nsirelativefilepref store paths in preferences. nsilocalfile is used to store absolute paths, while nsirelativefilepref is used to store paths relative to a "special" directory, such as the profile folder. nsisupportsstring as noted above, this is used to handle unicode strings in preferences. ...
...And 9 more matches
MMgc - Archive of obsolete content
g when the memory is no longer reachable from anywhere in the application and reclaiming it at that time. in mmgc, you get managed memory by subclassing gcobject/gcfinalizedobject/rcobject, or by calling gc::alloc. unmanaged memory is everything else. this is c++ memory management as you're accustomed to it. memory can be allocated with the new operator, and must be explicitly deleted in your c++ code at some later time using the delete operator. another way to think about it: unmanaged memory is c++ operators new and delete managed memory is c++ operator new, with optional delete mmgc contains a page allocator called gcheap, which allocates large blocks (megabytes) of memory from the system and doles out 4kb pages to the unmanaged memory allocator (fixedmalloc) and the managed memory alloca...
...ntainspointers indicates to the gc that the memory will contain pointers to other gc objects, and thus needs to be scanned by the gc's mark phase. if you know for certain that the objects will not contain gc pointers, leave this flag off; it will make the mark phase faster by excluding your object. kfinalize and krcobject are used internally by the gc; you should not need to set them in your user code. gc::getgc given the pointer to any gcobject, it is possible to get a pointer to the gc object that allocated it. void gcobject::method() { gc* gc = mmgc::gc::getgc(this); ... } this practice should be used sparingly, but is sometimes useful. base classes gcobject a basic garbage collected object. a gcobject is allocated with parameterized operator new, passing the mmgc::gc object: class m...
...s is as simple as using global operator new/delete, the same way you always have. to allocate a managed (gc) object, you must use the parameterized form of operator new, and pass it a reference to the mmgc::gc object. class myobject : public mmgc::gcobject { ... }; ... myobject* myobject = new (gc) myobject(); dwb/drc/drcwb there are several smart pointer templates which must be used in your c++ code to work properly with mmgc. dwb dwb stands for declared write barrier. it must be used on a pointer to a gcobject/gcfinalizedobject, when that pointer is a member variable of a class derived from gcobject/gcfinalizedobject/rcobject/rcfinalizedobject. class mymanagedclass : public mmgc::gcobject { // mymanagedclass is a gcobject, and // avmplus::hashtable is a gcobject, so use dwb dwb(avmplu...
...And 9 more matches
jspage - Archive of obsolete content
ay,date:date,function:function,number:number,regexp:regexp,string:string};for(var h in a){new native({name:h,initialize:a[h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){this[b]=a[b];}return this;}});hash.implement({forea...
...ar a=[]; hash.each(this,function(c,b){a.push(b);});return a;},getvalues:function(){var a=[];hash.each(this,function(b){a.push(b);});return a;},toquerystring:function(a){var b=[]; hash.each(this,function(f,e){if(a){e=a+"["+e+"]";}var d;switch($type(f)){case"object":d=hash.toquerystring(f,e);break;case"array":var c={};f.each(function(h,g){c[g]=h; });d=hash.toquerystring(c,e);break;default:d=e+"="+encodeuricomponent(f);}if(f!=undefined){b.push(d);}});return b.join("&");}});hash.alias({keyof:"indexof",hasvalue:"contains"}); var event=new native({name:"event",initialize:function(a,f){f=f||window;var k=f.document;a=a||f.event;if(a.$extended){return a;}this.$extended=true;var j=a.type; var g=a.target||a.srcelement;while(g&&g.nodetype==3){g=g.parentnode;}if(j.test(/key/)){var b=a.which||a.keycode;var ...
...f",hasvalue:"contains"}); var event=new native({name:"event",initialize:function(a,f){f=f||window;var k=f.document;a=a||f.event;if(a.$extended){return a;}this.$extended=true;var j=a.type; var g=a.target||a.srcelement;while(g&&g.nodetype==3){g=g.parentnode;}if(j.test(/key/)){var b=a.which||a.keycode;var m=event.keys.keyof(b);if(j=="keydown"){var d=b-111; if(d>0&&d<13){m="f"+d;}}m=m||string.fromcharcode(b).tolowercase();}else{if(j.match(/(click|mouse|menu)/i)){k=(!k.compatmode||k.compatmode=="css1compat")?k.html:k.body; var i={x:a.pagex||a.clientx+k.scrollleft,y:a.pagey||a.clienty+k.scrolltop};var c={x:(a.pagex)?a.pagex-f.pagexoffset:a.clientx,y:(a.pagey)?a.pagey-f.pageyoffset:a.clienty}; if(j.match(/dommousescroll|mousewheel/)){var h=(a.wheeldelta)?a.wheeldelta/120:-(a.detail||0)/3;}var e=(a.wh...
...And 9 more matches
Gecko Compatibility Handbook - Archive of obsolete content
rent platforms unlike internet explorer for mac and ie for windows, which are very different programs and so may behave quite differently from each other. quick compatibility test if your site uses netscape 4.x and microsoft proprietary technologies, see using web standards in your web pages for a quick tutorial on standards. this compatibility test will be most beneficial to sites using simple code or that have updated to support standards. set up browsers for testing the various gecko-based browsers do not always contain netscape in the user-agent string. thus it's critical to verify that you are properly detecting browsers such as aol for macos. you can either download the various browsers. or, if you are using user-agent detection, you can install an extension in firefox or mozilla wh...
...rowsers. upgrade the browser detection javascript to detect "gecko." (related article) content differs in gecko browsers and internet explorer use of proprietary or invalid markup (such as is generated by some microsoft office applications). use the w3 html and css validator tools to validate the web page. correct any errors and replace proprietary code wherever possible. upgrade web authoring tool to versions that support the w3 standards and gecko browsers content differs in gecko browsers and internet explorer the javascript console in netscape 6.x and netscape 7.x displays errors about document.all, document.layers, document.<property> not being defined because of an incorrect browser sniffing, or use of proprietary...
...results in a 404-page not found but works in internet explorer the link may use an invalid form of a relative url. change relative urls from http://directory/... to directory/.... or use absolute paths in urls such as http://example.com/directory/... verify that all hyperlinks use forward slashes (/) clicking on a link displays a "download" or displays html code instead of rendering the page correctly, but works as expected in internet explorer the web server has incorrectly specified the mime type for the content. internet explorer tries to guess the mime type of documents while gecko browsers relies upon the web server to specify the correct mime type. gecko does not try to 'sniff' the mime type for a document in order to reduce the possibility of u...
...And 9 more matches
Scratchpad - Archive of obsolete content
scratchpad is deprecated as of firefox 70 (bug 1565380), and will be removed as of firefox 72 (bug 1519103). as an alternative, starting in firefox 71, you can use the multi-line mode of the javascript console input. scratchpad provides an environment for experimenting with javascript code. you can write, run, and examine the results of code that interacts with the web page. unlike the web console, which is designed for interpreting a single line of code at a time, scratchpad lets you edit larger chunks of javascript code, then execute it in various ways depending on how you want to use the output. the featured video tutorial shows a case of using scratchpad with a page run by a local web server. it is also possible to use scratchpad over pages opened from a local file system, if perm...
... lets you edit larger chunks of javascript code, then execute it in various ways depending on how you want to use the output. the featured video tutorial shows a case of using scratchpad with a page run by a local web server. it is also possible to use scratchpad over pages opened from a local file system, if permission policies allow that. but even with possible limitations present, the html code can be either manually entered or copied from the source and pasted into the "about:blank" page (a new empty tab) with the use page inspector's edit as html context menu command. usage opening scratchpad in its own window there are several different ways to open scratchpad in its own window: press shift + f4, or go to the web developer menu (which is a submenu in the tools menu on macos an...
...e toolbox, alongside other tools like the page inspector and the web console. this is especially useful in split console mode: you can use scratchpad for a persistent, multiline editor, and the console to interact with the page. editing the scratchpad window looks something like this (on macos the menu bar is at the top of the screen): the file menu offers options to save and load javascript code snippets, so you can reuse code later if you like. code completion scratchpad integrates the tern code analysis engine, and uses that to provide autocomplete suggestions and popups containing information on the current symbol. to list autocomplete suggestions, press ctrl + space. for example, try typing d, then pressing ctrl + space. you'll see the autocomplete box, as shown below: the icon n...
...And 9 more matches
HTML: A good basis for accessibility - Learn web development
onger to write than non-semantic (bad) markup if you do it consistently from the start of your project. even better, semantic markup has other benefits beyond accessibility: easier to develop with — as mentioned above, you get some functionality for free, plus it is arguably easier to understand. better on mobile — semantic html is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive. good for seo — search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic <div>s, etc., so your documents will be more findable by customers. let's get on and look at accessible html in more detail. note: it is a good idea to have a screen reader set up on your local computer so that you can do some te...
...ement for the job. this cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly. out there on the web, the truth is that people do some very strange things with html markup. some abuses of html are due to legacy practices that have not been completely forgotten, and some are just plain ignorance. whatever the case, you should replace such bad code. sometimes you are not in the position to get rid of lousy markup — your pages might be generated by some kind of server-side framework over which you don't have full control, or you might have third party content on your page (such as ad banners) over which you have no control. the goal isn't "all or nothing." however, — every improvement you can make will help the cause of accessibility. ...
...ly (depending on which screen reader you're using) have to go down into the table as an object and look at its features separately, then get out of the table again to carry on navigating the content. table layouts are a relic of the past — they made sense back when css support was not widespread in browsers, but now they just create confusion for screen reader users. additionally, their source code requires more markup, which makes them less flexible and more difficult to maintain. you can verify these claims by comparing your previous experience with a more modern website structure example, which could look something like this: <header> <h1>header</h1> </header> <nav> <!-- main navigation in here --> </nav> <!-- here is our page's main content --> <main> <!-- it contains an artic...
...And 9 more matches
HTML: A good basis for accessibility - Learn web development
onger to write than non-semantic (bad) markup if you do it consistently from the start of your project. even better, semantic markup has other benefits beyond accessibility: easier to develop with — as mentioned above, you get some functionality for free, plus it is arguably easier to understand. better on mobile — semantic html is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive. good for seo — search engines give more importance to keywords inside headings, links, etc. than keywords included in non-semantic <div>s, etc., so your documents will be more findable by customers. let's get on and look at accessible html in more detail. note: it is a good idea to have a screen reader set up on your local computer so that you can do some te...
...ement for the job. this cannot be ignored, as it is one of the main places that accessibility is badly broken if not handled properly. out there on the web, the truth is that people do some very strange things with html markup. some abuses of html are due to legacy practices that have not been completely forgotten, and some are just plain ignorance. whatever the case, you should replace such bad code. sometimes you are not in the position to get rid of lousy markup — your pages might be generated by some kind of server-side framework over which you don't have full control, or you might have third party content on your page (such as ad banners) over which you have no control. the goal isn't "all or nothing." however, — every improvement you can make will help the cause of accessibility. ...
...ly (depending on which screen reader you're using) have to go down into the table as an object and look at its features separately, then get out of the table again to carry on navigating the content. table layouts are a relic of the past — they made sense back when css support was not widespread in browsers, but now they just create confusion for screen reader users. additionally, their source code requires more markup, which makes them less flexible and more difficult to maintain. you can verify these claims by comparing your previous experience with a more modern website structure example, which could look something like this: <header> <h1>header</h1> </header> <nav> <!-- main navigation in here --> </nav> <!-- here is our page's main content --> <main> <!-- it contains an artic...
...And 9 more matches
Debugging HTML - Learn web development
previous overview: introduction to html next writing html is fine, but what if something goes wrong, and you can't work out where the error in the code is? this article will introduce you to some tools that can help you find and fix errors in html. prerequisites: html familiarity, as covered in, for example, getting started with html, html text fundamentals, and creating hyperlinks. objective: learn the basics of using debugging tools to find problems in html. debugging isn't scary when writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. for example, the following shows an error reported...
...llo, world!"); might logically be missing a double quote. however, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about rust. debugging doesn't have to be scary though — the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools. html and debugging html is not as complicated to understand as rust. html is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). and html's element syntax is arguably a lot easier to understand than a "real programming language" like rust, javascript, or python. the way that ...
...t compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). and html's element syntax is arguably a lot easier to understand than a "real programming language" like rust, javascript, or python. the way that browsers parse html is a lot more permissive than how programming languages are run, which is both a good and a bad thing. permissive code so what do we mean by permissive? well, generally when you do something wrong in code, there are two main types of error that you'll come across: syntax errors: these are spelling errors in your code that actually cause the program not to run, like the rust error shown above. these are usually easy to fix as long as you are familiar with the language's syntax and know what the error messages ...
...And 9 more matches
Third-party APIs - Learn web development
...
... developer keys to allow developers access to the api functionality, which is more to protect the api vendor than the user. you'll find a line similar to the following in the mapquest api example: l.mapquest.key = 'your-api-key-here'; this line specifies an api or developer key to use in your application — the developer of the application must apply to get a key, and then include it in their code to be allowed access to the api's functionality. in our example we've just provided a placeholder. note: when creating your own examples, you'll use your own api key in place of any placeholder. other apis may require that you include the key in a slightly different way, but the pattern is relatively similar for most of them. requiring a key enables the api provider to hold users of the api ...
...') try changing 'map' to 'hybrid' to show a hybrid-style map. try some other values too. the tilelayer reference page shows the different available options, plus a lot more information. adding different controls the map has a number of different controls available; by default it just shows a zoom control. you can expand the controls available using the map.addcontrol() method; add this to your code, inside the window.onload handler: map.addcontrol(l.mapquest.control()); the mapquest.control() method just creates a simple full-featured control set, and it is placed in the top-right hand corner by default. you can adjust the position by specifying an options object as a parameter for the control containing a position property, the value of which is a string specifying a position for the con...
...And 9 more matches
Working with JSON - Learn web development
d by objects. we want to access the second object inside the array, so we use [1]. inside this object, we want to access the powers property, so we use ["powers"]. inside the powers property is an array containing the selected hero's superpowers. we want the third one, so we use [2]. note: we've made the json seen above available inside a variable in our jsontest.html example (see the source code). try loading this up and then accessing data inside the variable via your browser's javascript console. arrays as json above we mentioned that json text basically looks like a javascript object, and this is mostly right. the reason we said "mostly right" is that an array is also valid json, for example: [ { "name": "molecule man", "age": 29, "secretidentity": "dan jukes", "...
... use (although computer-generated json is less likely to include errors, as long as the generator program is working correctly). you can validate json using an application like jsonlint. json can actually take the form of any data type that is valid for inclusion inside json, not just arrays or objects. so for example, a single string or number would be a valid json object. unlike in javascript code in which object properties may be unquoted, in json only quoted strings may be used as properties. active learning: working through a json example so, let's work through an example to show how we could make use of some json data on a website. getting started to begin with, make local copies of our heroes.html and style.css files. the latter contains some simple css to style our page, while t...
...n example so, let's work through an example to show how we could make use of some json data on a website. getting started to begin with, make local copies of our heroes.html and style.css files. the latter contains some simple css to style our page, while the former contains some very simple body html: <header> </header> <section> </section> plus a <script> element to contain the javascript code we will be writing in this exercise. at the moment it only contains two lines, which grab references to the <header> and <section> elements and store them in variables: const header = document.queryselector('header'); const section = document.queryselector('section'); we have made our json data available on our github, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json...
...And 9 more matches
Script security
this page provides an overview of the script security architecture in gecko. like any web browser, gecko can load javascript from untrusted and potentially hostile web pages and run it on the user's computer. the security model for web content is based on the same-origin policy, in which code gets full access to objects from its origin but highly restricted access to objects from a different origin. ...
...legacy sdk extensions also run with chrome privileges. ...
...full access to objects from its origin but highly restricted access to objects from a different origin. the rules for determining whether an object is same-origin with another, and what access is allowed cross-origin, are now mostly standardized across browsers. gecko has an additional problem, though: while its core is written in c++, the front-end code is written in javascript. this javascript code, which is commonly referred to as chrome code, runs with system privileges. if the code is compromised, the attacker can take over the user's computer. legacy sdk extensions also run with chrome privileges. having the browser front end in javascript has benefits: it can be much quicker to develop in javascript than in c++, and contributors do not need to learn c++. however, javascript is a highl...
...And 9 more matches
How to embed the JavaScript engine
see also jsapi user guide. in particular, it has more and better code examples! a bare bones tutorial hello world sample embedding application the following code is a very simple application that shows how to embed spidermonkey and run a simple javascript script. see the instructions for building and running the sample below the code. the code differs for each spidermonkey version, please choose right version for your spidermonkey. spidermonkey 24 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object. */ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratest...
...*/ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepr...
...oname"; int lineno = 1; bool ok = js_evaluatescript(cx, global, script, strlen(script), filename, lineno, rval.address()); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); } js_destroycontext(cx); js_destroyruntime(rt); js_shutdown(); return 0; } spidermonkey 31 // following code might be needed in some case // #define __stdc_limit_macros // #include <stdint.h> #include "jsapi.h" /* the class of the global object. */ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, nullptr, nullptr, ...
...And 9 more matches
SpiderMonkey 1.8.5
spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0. ...
...experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —22 march 2011 platform support spidermonkey 1.8.5 is supported on all the platforms where firefox 4 runs. spidermonkey 1.8.5 includes a just-in-time compiler (jit) (several, actually) that compiles javascript to machine code, for a significant speed increase. it is supported only on x86, x86_64 and arm architectures. on other platforms, the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8 the following features in earlier versions of spidermonkey have been dropped. support for extended class methods (in p...
...each thread must operate on objects in a separate compartment, isolated from the other threads. the old build system (using makefile.ref) is no longer supported. spidermonkey 1.8.5 includes a new configure-based build system, introduced shortly after active development on the engine moved from cvs to mercurial. spidermonkey 1.8.5 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. previous...
...And 9 more matches
Components.utils.Sandbox
s.utils.sandbox(...) to create a sandbox has the same effect as calling sandbox(...) without new. the created sandbox is simply an empty javascript object marked as having been created by the restricted privilege principal. you can then use it with evalinsandbox() to make it the global scope object for the specified script. ...
...ript. principal the security principal defined for a sandbox determines what code running in that sandbox will be allowed to do. the principal may be one of four types: the system principal, a content principal, an expanded principal, or a null principal. see security checks for more information on security principals. ...
...siprincipal, a dom window, or a uri. so this can be simply an array with a single element. for example the content principal above can be made expanded/extended like so: var principal = [gbrowser.selectedtab.linkedbrowser.contentprincipal]; // this is now an expanded (aka extended) principal var sandbox = components.utils.sandbox(principal); null principal you can create a null principal using code like: cc["@mozilla.org/nullprincipal;1"].createinstance(ci.nsiprincipal); from firefox 37 onwards, you can also specify the null principal by simply passing null as the principal argument. options the constructor accepts an optional parameter. this parameter is an object with the following optional properties: freshzone if true creates a new gc region separate from both the calling conte...
...And 9 more matches
Language bindings
the scriptable methods on the nsicomponentmanager interface can be called directly on this object.compone...
...the scriptable methods on the nsicomponentmanager interface can be called directly on this object.components.resultscomponents.results is a read-only...
...ative component manager service. the scriptable methods on the nsicomponentmanager interface can be called directly on this object.components.resultscomponents.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of errors), with the value of each corresponding to that constant's value.components.returncodecomponents.stackcomponents.stack is a read only property of type nsistackframe (idl definition) that represents a snapshot of the current javascript callstack. this can be used for various diagnostic purposes.components.utilscomponents.utils is a collection of various useful xpconnect features. its interface is defined at js/xpconnect/idl/xpccomponents.idl.components.utils.cloneintothis function p...
...And 9 more matches
nsIPushService
a service for components to subscribe and receive push messages from remote servers. inherits from: nsisupports last changed in gecko 46.0 (firefox 46.0 / thunderbird 46.0 / seamonkey 2.43) push lets a remote server send payloads to a web site, add-on, or component running in the browser. nsipushservice supports the push api implementation in firefox, and can be used directly from privileged code to create system subscriptions. implemented by @mozilla.org/push/service;1 as a service: const pushservice = components.classes["@mozilla.org/push/service;1"] .getservice(components.interfaces.nsipushservice); method overview void subscribe(in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback); void getsubscrip...
...be() creates a push subscription. void subscribe( in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback ); parameters scope the serviceworkerregistration.scope for a service worker subscription, or a unique url (for example, chrome://my-module/push) for a system subscription. principal the nsiprincipal to associate with the subscription. privileged code should pass the system principal. callback the callback to call when the nsipushsubscription is created. passing the system principal exempts the subscription from permission checks and background messages quotas, which are enforced for service worker subscriptions. example const { classes: cc, interfaces: ci, utils: cu } = components; const scriptsecuritymanager = cc["@mozilla.org/scrip...
... subscription.endpoint; subscription.getkey("p256dh"); subscription.getkey("auth"); } ); getsubscription() fetches an existing subscription. void getsubscription( in domstring sco...
...And 9 more matches
Setting HTTP request headers
http is one of the core technologies behind the web. in addition to the actual content, some important information is passed with http headers for both http requests and responses. you can add your own http headers to any request the application makes, whether the request is initiated by your code explicitly opening an http channel, because of xmlhttprequest activity, an <img> element in content, or even from css. http channels when you deal with http requests and responses, typically you are doing this with an nsihttpchannel. the nsihttpchannel interface has a number of properties and methods, but the method that is of interest to us is setrequestheader. this method allows us to set an http request header. below is some sample code where we set an http header. // adds "x-hello: world"...
...u are doing this with an nsihttpchannel. the nsihttpchannel interface has a number of properties and methods, but the method that is of interest to us is setrequestheader. this method allows us to set an http request header. below is some sample code where we set an http header. // adds "x-hello: world" header to the request httpchannel.setrequestheader("x-hello", "world", false); in the example code above we have a variable named httpchannel which points to an object implementing nsihttpchannel. (this variable could have been named anything though.) the setrequestheader method takes 3 parameters. the first parameter is the name of the http request header. the second parameter is the value of the http request header. and for now, just ignore the third parameter, and just always make it false.
... variable named httpchannel which points to an object implementing nsihttpchannel. (this variable could have been named anything though.) the setrequestheader method takes 3 parameters. the first parameter is the name of the http request header. the second parameter is the value of the http request header. and for now, just ignore the third parameter, and just always make it false. in our example code, the http request header that we added is named x-hello and the value of this http request header is world. note: if you are making up your own http header, you must put a x- in front of the name. (in our example, our made up http header is x-hello and not hello because we correctly added the x- in front of our name.) no longer the case: http://tools.ietf.org/html/rfc6648 notifications the...
...And 9 more matches
Using Fetch - Web APIs
e cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites are silently ignored. fetch won’t send cookies, unless you set the credentials init option. (since aug 25, 2017. the spec changed the default credentials policy to same-origin. firefox changed since 61.0b13.) a basic fetch request is really simple to set up. have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); here we are fetching a json file across the network and printing it to the console. the simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a response object). this is just an http response, n...
...th * const response = await fetch(url, { method: 'post', // *get, post, put, delete, etc. ...
... fetch('https://example.com', { credentials: 'include' }); if you only want to send credentials if the request url is on the same origin as ...
...And 9 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
ction, it's highly flexible. however, despite that flexibility in transport and communication of signaling messages, there's still a recommended design pattern you should follow when possible, known as perfect negotiation. this article introduces webrtc perfect negotiation, describing how it works and why it's the recommended way to negotiate a webrtc connection between peers, and provides sample code to demonstrate the technique. after the first deployments of webrtc-capable browsers, it was realized that parts of the negotiation process were more complicated than they needed to be for typical use cases. this was due to a small number of issues with the api and some potential race conditions that needed to be prevented. these issues have since been addressed, letting us simplify our webrtc n...
...is the "callee." the perfect negotiation pattern smooths this difference away by separating that difference out into independent negotiation logic, so that your application doesn't need to care which end of the connection it is. as far as your application is concerned, it makes no difference whether you're calling out or receiving a call. the best thing about perfect negotiation is that the same code is used for both the caller and the callee, so there's no repetition or otherwise added levels of negotiation code to write. perfect negotiation works by assigning each of the two peers a role to play in the negotiation process that's entirely separate from the webrtc connection state: a polite peer, which uses ice rollback to prevent collisions with incoming offers. a polite peer, essentiall...
...the polite role to the first peer to connect to the signaling server, or you could do something more elaborate like having the peers exchange random numbers and assigning the polite role to the winner. however you make the determination, once these roles are assigned to the two peers, they can then work together to manage signaling in a way that doesn't deadlock and doesn't require a lot of extra code to manage. an important thing to keep in mind is this: the roles of caller and callee can switch during perfect negotiation. if the polite peer is the caller and it sends an offer but there's a collision with the impolite peer, the polite peer drops its offer and instead replies to the offer it has received from the impolite peer. by doing so, the polite peer has switched from being the caller t...
...And 9 more matches
Writing a WebSocket server in Java - Web APIs
this server conforms to rfc 6455, so it only handles connections from chrome version 16, firefox 11, ie 10 and higher. first steps websockets communicate over a tcp (transmission control protocol) connection. java's serversocket class is located in the java.net package. ...
.... try { string data = s.usedelimiter("\\r\\n\\r\\n").next(); matcher get = pattern.compile("^get").matcher(data); creating the response is easier than understanding why you must do it in this way. you must, obtain the value of sec-websocket-key request header without any leading and trailing whitespace link it with "258eafa5-e914-47da-95ca-c5ab0dc85b11" compute sha-1 and base64 code of it write it back as value of sec-websocket-accept response header as part of a http response. if (get.find()) { matcher match = pattern.compile("sec-websocket-key: (.*)").matcher(data); match.find(); byte[] response = ("http/1.1 101 switching protocols\r\n" + "connection: upgrade\r\n" + "upgrade: websocket\r\n" + "sec-websocket-accept: " + base64.g...
...it write it back as value of sec-websocket-accept response header as part of a http response. if (get.find()) { matcher match = pattern.compile("sec-websocket-key: (.*)").matcher(data); match.find(); byte[] response = ("http/1.1 101 switching protocols\r\n" + "connection: upgrade\r\n" + "upgrade: websocket\r\n" + "sec-websocket-accept: " + base64.getencoder().encodetostring(messagedigest.getinstance("sha-1").digest((match.group(1) + "258eafa5-e914-47da-95ca-c5ab0dc85b11").getbytes("utf-8"))) + "\r\n\r\n").getbytes("utf-8"); out.write(response, 0, response.length); decoding messages after a successful handshake, client can send messages to the server, but now these are encoded. if we send "abcdef", we get these bytes: 129 ...
...And 9 more matches
Audio and video manipulation - Developer guides
var processor = { timercallback: function() { if (this.video.paused || this.video.ended) { return; } this.computeframe(); var self = this; settimeout(function () { self.timercallback(); }, 16); // roughly 60 frames per second }, doload: function() { this.video = document.getelementbyid("my-video"); this.c1 = document...
... return; } }; once the page has loaded you can call processor.doload() result this is a pretty simple example showing how to manipulate video frames using a canvas. for efficiency, you should consider using requestanimationframe() instead of settimeout() when running on browsers that support it. note: due to potential security issues if your video is on a different domain than your code, you'll need to enable cors (cross origin resource sharing) on your video server. video and webgl webgl is a powerful api that uses canvas to draw hardware-accelerated 3d or 2d scenes. you can combine webgl and the <video> element to create video textures, which means you can put video inside 3d scenes. note: you can find the source code of this demo on github (see it live also). playbac...
...n both cases, it changes the playback speed but not the pitch. to manipulate the audio's pitch you need to use the web audio api. see the audiobuffersourcenode.playbackrate property. ...
...And 9 more matches
Overview of events and handlers - Developer guides
events and event handling provide a core technique in javascript for reacting to incidents occurring when a browser accesses a web page, including events from preparing a web page for display, from interacting with the content of the web page, relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing. ...
...andling the incidence of new events follows painting. the innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which javascript leverages. (the talk is available from several sources, including this one.) currently, all execution environments for javascript code use events and event handling. the event design pattern the event system, at its core, is simply a programming design pattern. the pattern starts with an agreement over a kind of event and: the name string used for the event, the type of the data structure used to represent the key properties of that event, and the javascript object which will 'emit' that event. the pattern is implemente...
...t' that event. the pattern is implemented by defining a javascript function which takes as an argument the data structure which was agreed upon, and registering the function using the name string with the object which will emit the event. the function is said to be a 'listener' or a 'handler' with both names used interchangeably. this pattern can easily be followed using completely custom code, as explained in the article on custom events. the pattern is also used by modern web browsers which define many events emitted in response to user input or browser activity. modern web browsers follow the event pattern using a standardized approach. browsers use as the data structure for the properties of the event, an object derived from the eventprototype object. browsers use as the registrat...
...And 9 more matches
Content Scripts - Archive of obsolete content
many add-ons need to access and modify the content of web pages. but the main add-on code doesn't get direct access to web content. instead, sdk add-ons need to factor the code that gets access to web content into separate scripts that are called content scripts. this page describes how to develop and implement content scripts. content scripts can be one of the more confusing aspects of working with the sdk, but you're very likely to have to use them. ...
...ess to web content. instead, sdk add-ons need to factor the code that gets access to web content into separate scripts that are called content scripts. this page describes how to develop and implement content scripts. content scripts can be one of the more confusing aspects of working with the sdk, but you're very likely to have to use them. ...
...five basic principles: the add-on's main code, including "main.js" and other modules in "lib", can use the sdk high-level and low-level apis, but can't access web content directly content scripts can't use the sdk's apis (no access to globals exports, require) but can access web content sdk apis that use content scripts, like page-mod and tabs, provide functions that enable the add-on's main code to load content scripts into web pages content scripts can be loaded in as strings, but are more often stored as separate files under the add-on's "data" directory. jpm doesn't make a "data" directory by default, so you must add it and put your content scripts in there. ...
...And 8 more matches
panel - Archive of obsolete content
create dialogs. to do this, save the html in your add-on's data directory and load it using the data.url() method exported by the self module, like this: var mypanel = require("sdk/panel").panel({ contenturl: require("sdk/self").data.url("myfile.html") }); mypanel.show(); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: var mypanel = require("sdk/panel").panel({ contenturl: "./myfile.html" }); mypanel.show(); panel positioning by default the panel appears in the center of the currently active browser window. you can position the panel by passing a position to the panel's constructor or to its show() method. attaching panels to buttons you can attach a panel to a toggle button by passing the ...
...s is usually the best approach. embedding an iframe in the panel, and changing its document setting the panel's contenturl property. however, doing this will cause any content scripts to be unloaded and then reloaded, so it may be less efficient, and you'll lose any state associated with the scripts. scripting panel content you can't directly access your panel's content from your main add-on code. to access the panel's content, you need to load a script into the panel. in the sdk these scripts are called "content scripts" because they're explicitly used for interacting with web content. while content scripts can access the content they're attached to, they can't use the sdk's apis. so implementing a complete solution usually means you have to send messages between the content script and ...
...panel's content, you need to load a script into the panel. in the sdk these scripts are called "content scripts" because they're explicitly used for interacting with web content. while content scripts can access the content they're attached to, they can't use the sdk's apis. so implementing a complete solution usually means you have to send messages between the content script and the main add-on code. you can specify one or more content scripts to load into a panel using the contentscript or contentscriptfile options to the panel() constructor. you can communicate with the script using either the postmessage() api or (preferably, usually) the port api. for example, here's an add-on whose content script intercepts mouse clicks on links inside the panel, and sends the target url...
...And 8 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
sending data from unprivileged document to chrome an easy way to send data from a web page to an extension is by using custom dom events. in your extension's browser.xul overlay, write code which listens for a custom dom event. here we call the event myextensionevent. var myextension = { mylistener: function(evt) { alert("received from web page: " + evt.target.getattribute("attribute1") + "/" + evt.target.getattribute("attribute2")); } } document.addeventlistener("myextensionevent", function(e) { myextension.mylistener(e); }, false, true); // the last value is a mozilla-specific value to indicate untrusted content is allowed to trigger the event. the data from the web page (unprivileged code) will be the values of attribute1 and attribute2. to trigger th...
... } } document.addeventlistener("myextensionevent", function(e) { myextension.mylistener(e); }, false, true); // the last value is a mozilla-specific value to indicate untrusted content is allowed to trigger the event. the data from the web page (unprivileged code) will be the values of attribute1 and attribute2. ...
...data from the web page, write code such as this in the web page: var element = document.createelement("myextensiondataelement"); element.setattribute("attribute1", "foobar"); element.setattribute("attribute2", "hello world"); document.documentelement.appendchild(element); var evt = document.createevent("events"); evt.initevent("myextensionevent", true, false); element.dispatchevent(evt); this code creates an arbitrary element -- <myextensiondataelement/> -- and inserts it into the web page's dom. values are set for two arbitrary attributes on the element. these can also be named anything you like, but we've chosen attribute1 and attribute2. ...
...And 8 more matches
Adding Events and Commands - Archive of obsolete content
« previousnext » event handlers just like with html, most javascript code execution is triggered by event handlers attached to dom elements. the most commonly used event is the onload event, which is used in overlays and other windows to detect when the window has loaded and then run initialization code: // rest of overlay code goes here. window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); you can do something similar with the onunload event, to do any cleanup you may need. please read appendix a for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on firefox. ...
...", function() { xulschoolchrome.browseroverlay.init(); }, false); you can do something similar with the onunload event, to do any cleanup you may need. please read appendix a for recommendations on how to use the load event to initialize your add-on without having a negative performance impact on firefox. another way to attach event handlers, just like html, is to place the handler in the xul code: <overlay id="xulschoolhello-browser-overlay" onload="xulschoolchrome.browseroverlay.init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> we prefer the first method because it keeps a better separation of content and behavior. also, note that the addeventlistener method receives the event name without the "on" prefix, while element attributes do have the prefix. ...
...ion on the event. you can get information on key modifiers (in case the user was holding a modifier key like alt while performing the event), screen coordinates for mouse events, and most importantly, the target element for the event. for example: <button label="&xulschoolhello.defaultgreeting.label;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("label", somenewgreeting); } the target in this example is the button element, so clicking on it will change its text. the advantage of using the event argument is that the method is not dependent of the specific button, so it can also be used for other elements. for more advan...
...And 8 more matches
Using Breakpoints in Venkman - Archive of obsolete content
this article continues a series of articles on venkman that began with venkman introduction. one of the basic tasks of debugging any language is setting breakpoints. breakpoints are places in code where execution is suspended. when you set a breakpoint in a debugging application such as venkman, you can take advantage of the suspension to examine variables, objects, and other featues of the execution. this article describes breakpoints in javascript and how to use venkman to set and examine breakpoints. basic breakpoints the stop button and debugger keyword are useful features of the javascript debugger, but when you are debugging deep in code—especially code you have authored yourself and are responsible for troubleshooting—you're going to need breakpoints. types of breakpoints ve...
...hard breakpoints can only exist in the context of a function currently "live" in the browser. hard breakpoints are the ones that actually stop program execution. ...
...kpoint as soon as it is possible. future breakpoints are used when you want to stop in a script that has not yet been compiled. the most common use of future breakpoints is to stop in a "top level" script (script that executes outside of any function), or script that executes during the onload event of a page. ...
...And 8 more matches
Anatomy of a video game - Game development
if something looks like it should be attached to a more infrequent event then it is often a good idea to break it out of the main loop (but not always). building a main loop in javascript javascript works best with events and callback functions. modern browsers strive to call methods right as they are needed and idle (or do their other tasks) in the gaps. ...
... a callback function must be passed in to it when it is called. that callback function will be executed at a suitable time before the next repaint. ...
...}; main(); // start the cycle note: in each of the main() methods discussed here, we schedule a new requestanimationframe before performing our loop contents. that is not by accident and it is considered best practice. calling the next requestanimationframe early ensures the browser receives it on time to plan accordingly even if your current frame misses its vsync window. the above chunk of code has two statements. the first statement creates a function as a global variable called main(). this function does some work and also tells the browser to call itself next frame with window.requestanimationframe(). the second statement calls the main() function, defined in the first statement. because main() is called once in the second statement and every call of it places itself in the queue of ...
...And 8 more matches
Positioning - Learn web development
ns the different position values, and how to use them. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how css positioning works. we'd like you to follow along with the exercises on your local computer, if possible — grab a copy of 0_basic-flow.html from our github repo (source code here) and use that as a starting point. introducing positioning the whole idea of positioning is to allow us to override the basic document flow behavior described above, to produce interesting effects. what if you want to slightly alter the position of some boxes inside a layout from their default layout flow position, to give a slightly quirky, distressed feel? positioning is your tool. or if...
...e following rule to the bottom of your css: .positioned { position: static; background: yellow; } if you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. ...
... so how do you modify the element's position? you need to use the top, bottom, left, and right properties, which we'll explain in the next section. ...
...And 8 more matches
How CSS is structured - Learn web development
er: 1px solid black;">hello world!</h1> <p style="color:red;">this is my first css example</p> </body> </html> avoid using css in this way when possible. it is the opposite of a best practice. first, it is the least efficient implementation of css for maintenance. one styling change might require multiple edits within in a single web page. second, inline css also mixes (css) presentational code with html and content, making everything more difficult to read and understand. separating code and content makes maintenance easier for all who work on the the website. there are a few circumstances where inline styles are more common. you might have to resort to using inline styles if your working environment is very restrictive. for example, perhaps your cms only allows you to edit the html b...
... as an altenative, you can also use the interactive editor below. read on and have fun! selectors a selector targets html to apply styles to content. we have already discovered a variety of selectors in the getting started with css tutorial. if css is not applying to content as-expected, your selector may not match the way you think it should match. each css rule starts w...
... color: red; } p { color: blue; } suppose that in our html document, we have a paragraph with a class of special. both rules apply. which selector prevails? do you expect to see blue or red paragraph text? <p class="special">what color am i?</p> the css language has rules to control which selector is stronger in the event of a conflict. these rules are called cascade and specificity. in the code block below, we define two rules for the p selector, but the paragraph text will be blue. this is because the declaration that sets the paragraph text to blue appears later in the stylesheet. later styles replace conflicting styles that appear earlier in the stylesheet. this is the cascade rule. p { color: red; } p { color: blue; } however, in the case of our earlier example with the confl...
...And 8 more matches
Aprender y obtener ayuda - Learn web development
s an obvious one, with channels such as mozilla layout land, mozilladeveloper, and google chromedevelopers providing many useful videos. many people prefer textual articles for more in-depth learning and reference material, and videos for quick explanations of concepts and new features, but it is really up to you what you prefer to learn from. there is no right and wrong answer here. ...
...ople prefer textual articles for more in-depth learning and reference material, and videos for quick explanations of concepts and new features, but it is really up to you what you prefer to learn from. there is no right and wrong answer here. interactive code playgrounds you might be the kind of person that prefers minimal instructions and would prefer to jump straight in and start playing with code. this is also a reasonable approach, and some learning sites tend to favor it. ...
...videos for quick explanations of concepts and new features, but it is really up to you what you prefer to learn from. there is no right and wrong answer here. interactive code playgrounds you might be the kind of person that prefers minimal instructions and would prefer to jump straight in and start playing with code. this is also a reasonable approach, and some learning sites tend to favor it. codecademy for example is a learning site where the tutorials mainly consist of interactive code editors where you have to directly write code and see if the desired result was achieved. ...
...And 8 more matches
Command line crash course - Learn web development
l is software that starts and connects to a shell. a shell is your session and session environment (where things like the prompt and shortcuts might be customised). the command line is the literal line where you enter commands and the cursor blinks. do you have to use the terminal? although there's a great wealth of tools available from the command line, if you're using tools like visual studio code there's also a mass of extensions that can be used as a proxy to using terminal commands without needing to use the terminal directly. however, you won’t find a code editor extension for everything you want to do — you’ll have to get some experience with the terminal eventually. basic built-in terminal commands enough talk — let’s start looking at some terminal commands! out of the bo...
...omitting the leading slash like we’ve done above makes the path relative to the your present working directory. this is exactly the same as you would see with urls in your web browser. a leading slash means "at the root of the web site", whereas omitting...
...our terminal command out inside a text editor, figure out how you think it should look, and then make a backup copy of your directory and try running the command on that first, to test it. another good tip — if you’re not comfortable trying terminal commands out on your own machine, a nice safe place to try them is over at glitch.com. along with being a great place to try out web development code, the projects also give you access to a terminal, so you can run all these commands directly in that terminal, safe in the knowledge that you won’t break your own machine. a great resource for getting a quick overview of specific terminal commands is tldr.sh. this is a community-driven documentation service, similar to mdn, but specific to terminal commands. in the next section let’s step...
...And 8 more matches
Android-specific test suites
all of these suites require a functioning build of firefox for android — either a full build or an artifact build. all of the suites are configured by and invoked using gradle. android-test runs android-specific local unit tests. ...
... all of these suites require a functioning build of firefox for android — either a full build or an artifact build. all of the suites are configured by and invoked using gradle. android-test runs android-specific local unit tests. ...
... all of these suites require a functioning build of firefox for android — either a full build or an artifact build. all of the suites are configured by and invoked using gradle. android-test runs android-specific local unit tests. ...
...And 8 more matches
Limitations of chrome scripts
to the content process". this is one of a pair of articles: the other one lists limitations of frame scripts. compatibility shims for many of the patterns described here we've implemented compatibility shims so the patterns still work. for example: whenever extensions try to access web content from the chrome process, the browser will return a cross process object wrapper that gives the chrome code synchronous access to the content. you'll get the shims for your add-on by default, unless you set the multiprocesscompatible flag in your add-on's install manifest. however, these shims are not a substitute for migrating extensions: they are only a temporary measure, and will be removed eventually they can have a bad effect on responsiveness there are likely to be edge cases in which they...
...ess firefox as well as how are shims try to paper over the problem. for each pattern we've noted: whether a shim exists and what kind of behavior it provides how to update your add-on so you don't need the shim gbrowser.contentwindow, window.content... without the shim all apis in the chrome process that provide direct access to content objects will no longer work. ...
...this case, the shim will return a javascript object that looks somewhat like a window or a document for about:blank. however, this "dummy" object is completely static and only exposes a few of the normal properties that windows and documents have. for this reason, add-ons that try to access content objects in fresh <browser> elements may run into trouble. to make the shim unnecessary: factor the code that needs to access content into a separate script, load that script into the content process as a frame script, and communicate between the chrome script and the frame script using the message-passing apis. see the article on using the message manager. limitations of cpows cross process object wrappers (cpows) are a migration aid giving chrome code synchronous access to content objects. howev...
...And 8 more matches
Message manager overview
in multiprocess firefox there are (at least) two processes: the chrome process, also called the parent process, runs the browser ui (chrome) code and code inserted by extensions one or more content processes, also called child processes. these processes run web content. message managers are designed to enable chrome-privileged javascript code in one process to communicate with chrome-privileged javascript code in a different process. this article describes the different types of message manager, how to access them, and at a high level, what sorts of things you can use them for. ...
...hrome-privileged javascript code in one process to communicate with chrome-privileged javascript code in a different process. this article describes the different types of message manager, how to access them, and at a high level, what sorts of things you can use them for. at the top level, there are two different sorts of message managers: frame message managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in the content process. these scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. if chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. process message managers: these correspond to proce...
...rowser frame (essentially, a single browser tab) in the content process. these scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. if chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. process message managers: these correspond to process boundaries, and enable code running in the parent (chrome) process to communicate with code running in the child (content) process. ...
...And 8 more matches
Examples
callback is specified and the return value of the last then method is ignored. if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instance. this state will propagate to newpomise, and components.utils.reporterror will report all the details of the exception to the console. ...
...dir); }); }).then(null, components.utils.reporterror); parallel promise (this example needs more work) so when chaining promises, consequent promises run after the previous promise completes. now what if we want to run multiple promises and then return when all are done? this is accomplished by using promise.all, this feature requires promise.jsm. ...
...).then(null, components.utils.reporterror); parallel promise (this example needs more work) so when chaining promises, consequent promises run after the previous promise completes. now what if we want to run multiple promises and then return when all are done? this is accomplished by using promise.all, this feature requires promise.jsm. ...
...And 8 more matches
Localization content best practices
note on localizers mozilla localizers are volunteers with very diverse technical skills: some of them rely exclusively on translation tools, others prefer to work directly with text editors and don't have problems working with vcs systems. ...
... note on localizers mozilla localizers are volunteers with very diverse technical skills: some of them rely exclusively on translation tools, others prefer to work directly with text editors and don't have problems working with vcs systems. ...
... are temporary, they shouldn't be exposed to the localization process. this would waste everybody's time and create unnecessary frustration: localizers have to translate strings that are destined to change, developers will need to use new ids later to update them. if you're reviewing a patch, check also strings for grammar errors, capitalization or inconsistencies. ...
...And 8 more matches
Tutorial: Embedding Rhino
objects exposed to scripts can be customized further. this tutorial leads you through the steps from a simple embedding to more customized, complex embeddings. fully compilable examples are provided along the way. the examples live in the rhino/examples directory in the distribution and in mozilla/js/rhino/examples in cvs. this document will link to them using lxr. in this document, javascript code will be in green, java code will be in green, and shell logs will be in purple. in this document: runscript: a simple embedding entering a context initializing standard objects collecting the arguments evaluating a script printing the result exiting the context expose java apis using java apis implementing interfaces adding java objects using java...
...from the command line, execute it, and print a result. here's an example use of runscript from a shell command line: $ java runscript "math.cos(math.pi)" -1 $ java runscript "function f(x){return x+1} f(7)" 8 note that you'll have to have both the rhino classes and the runscript example class file in the classpath. let's step through the body of main one line at time. entering a context the code context cx = context.enter(); creates and enters a context. a context stores information about the execution environment of a script. initializing standard objects the code scriptable scope = cx.initstandardobjects(); initializes the standard objects (object, function, etc.) this must be done before scripts can be executed. the null parameter tells initstandardobjects to create and return...
...ores information about the execution environment of a script. initializing standard objects the code scriptable scope = cx.initstandardobjects(); initializes the standard objects (object, function, etc.) this must be done before scripts can be executed. the null parameter tells initstandardobjects to create and return a scope object that we use in later calls. collecting the arguments this code is standard java and not specific to rhino. it just collects all the arguments and concatenates them together. string s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } evaluating a script the code object result = cx.evaluatestring(scope, s, "<cmd>", 1, null); uses the context cx to evaluate a string. evaluation of the script looks up variables in scope, and errors will be r...
...And 8 more matches
64-bit Compatibility
what widths are the random typedefs everywhere? the following types or typedefs are always 64-bit on 64-bit platforms, and 32-bit on 32-bit platforms: pointers uintptr_t, intptr_t, ptrdiff_t, (probably) size_t jsval jsuword, jsword length of a string, though the actual length cannot exceed 30 bits jsuintptr, jsintptr, jsptrdiff, jsuptrdiff, jssize, jsuword, jsword (let's not use these, kthx) the following types are 32-bit on 32-bit platforms. ...
... following types are 32-bit on 32-bit platforms. for all intents and purposes they are also 32-bit on 64-bit platforms: intn, uintn jsintn, jsuintn, jsbool general problems with pointers when performing bitwise operations on pointer values, make sure that both operands are 64-bit. the compiler can implicitly sign or zero extend operands with unintended side effects. for example, consider this code: #define pointer_tagbits 3 static inline uintptr_t unmaskpointer(uintptr_t v) { return v & ~pointer_tagbits; } the value 3 will be inverted to 0xfffffffc, then zero-extended to 0x00000000fffffffc - a subtle and nasty bug, assuming it is unintended. the best way to fix this is to make types explicit, such as: const uintptr_t pointer_tagbits = 3 or by using a cast inside the macro. this s...
...e_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 integers". a native integer is the ...
...And 8 more matches
Secure Development Guidelines
the following content will likely see significant revision, though can be used as a reference for security best practices to follow when developing code for mozilla. introduction provide developers with information on specific security issues cover common coding mistakes and how they affect a product how to avoid making them how to mitigate them everything is oriented toward c/c++ introduction: gaining control specifics about the underlying architecture, using x86 as an example 6 basic registers (eax, ebx, ecx, edx, edi, esi) 2 stack-related registers (esp, ebp) mark top and bottom of current stack frame status register (eflags) contains various state information instruction pointer (eip) points to register being executed; can’t be modifi...
...ol over the eip otherwise the attacker can try to control memory pointed to by an existing function pointer a vulnerability is required to modify the eip or sensitive memory saved return addr or function pointer get altered introduction: gaining control (3) common issues used to gain control buffer overflows format string bugs integer overflows/underflows writing secure code: input validation input validation most vulnerabilities are a result of un-validated input always perform input validation could save you without knowing it examples: if it doesn’t have to be negative, store it in an unsigned int if the input doesn’t have to be > 512, cut it off there if the input should only be [a-za-z0-9], enforce it cross site scripting (xss) x...
... xss: example the following snippet of javascript: document.write("welcome to " + document.location); ... is exploitable...
...And 8 more matches
Animated PNG graphics
Mozilla › Tech › APNG
ics (png) format, adding support for animated images. it is intended to be a replacement for simple animated images that have traditionally used the gif format, while adding support for 24-bit images and 8-bit transparency. apng is a simpler alternative to mng, providing a spec suitable for the most common usage of animated images on the internet. apng is backwards-compatible with png; any png decoder should be able to ignore the apng-specific chunks and display a single image. terminology the default image is the image described by the standard 'idat' chunks, and is the image that is displayed by decoders that do not support apng. the canvas is the area on the output device on which the frames are to be displayed. the contents of the canvas are not necessarily available to the decoder. as...
...e png specification, if a 'bkgd' chunk exists it may be used to fill the canvas if there is no preferrable background. the output buffer is a pixel array with dimensions specified by the width and height parameters of the png 'ihdr' chunk. conceptually, each frame is constructed in the output buffer before being composited onto the canvas. the contents of the output buffer are available to the decoder. the corners of the output buffer are mapped to the corners of the canvas. fully transparent black means red, green, blue and alpha components are all set to zero. for purposes of chunk descriptions, an unsigned int shall be a 32-bit unsigned integer in network byte order limited to the range 0 to (2^32)-1; an unsigned short shall be a 16-bit unsigned integer in network byte order with the ran...
...d integer in network byte order with the range 0 to (2^16)-1; and a byte shall be an 8-bit unsigned integer with the range 0 to (2^8)-1. error handling apng is designed to allow incremental display of frames before the entire image has been read. this implies that some errors may not be detected until partway through the animation. it is strongly recommended that when any error is encountered decoders should discard all subsequent frames, stop the animation, and revert to displaying the default image. a decoder which detects an error before the animation has started should display the default image. an error message may be displayed to the user if appropriate. structure an apng stream is a normal png stream as defined in the png specification, with three additional chunk types describing t...
...And 8 more matches
nsICryptoHash
ha384 5 secure hash algorithm 384 sha512 6 secure hash algorithm 512 methods finish() completes the hash object and produces the actual hash data. note: this method may be called any time after " .. manch("init") .. " is called. this call resets the object. acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value this method returns a hash of the data that was read by this object. this can be either binary data or a base-64 encoded string. exceptions thrown ns_error_not_initialized indicates that init() or initwithstring() has not been called. init() initialize the hashing object. this method may be called multiple times wi...
... ns_error_not_initialized indicates that init() or initwithstring() has not been called. example computing the hash of a file you can easily compute the hash of a file using nsicryptohash. you will need to create an instance of nsicryptohash, open an input stream from a file, and then update the hash with the file. ...
...this example, while simple, shows most of the functionality of the interfa...
...And 8 more matches
nsISelectionPrivate
ng: the content of this article may be out of date. this page wasn't updated since the initial import in 2011. see the idl file linked above for up-to-date information. ...
...2011. see the idl file linked above for up-to-date information. ...
...obsolete since gecko 12.0 long gettableselectiontype(in nsidomrange range); void removeselectionlistener(in nsiselectionlistener listenertoremove); void scrollin...
...And 8 more matches
Console messages - Firefox Developer Tools
that information. message the message itself. number of occurrences if a line that generates a warning or error 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 o...
... method the specific http request method. if the request was made as an xmlhttprequest, there's an additional "xhr" tag indicating this. if more information is available, a disclosure triangle lets you display it, in an embedded panel that is identical to the network monitor request details. uri the target uri. summary the http version, response code, and time taken to complete. clicking the response code takes you to the reference page for that code. the context menu for network messages includes a few extra items in addition the globally-available ones: copy link location acts as you would expect, copying the url into the clipboard open in network panel switches context to the network tab, selects the request and shows you ...
...ands source maps. this means that if your javascript sources are compressed, you can supply a source map for them. then any messages or errors your source generates will show up in the web console with a link back to the original source, not the compressed version. async stack frames stack traces show stack frames for async functions separately from those for synchronous functions. when you run code containing an async function, its traces (console.trace or thrown error) are shown with an async: prefix. css note: css warnings and reflow messages are not shown by default, for performance reasons (see bug 1452143). use the filtering feature to show them. some css messages contain a disclosure triangle at the left of the message. click it to view more information about the error, as well...
...And 8 more matches
Using the Payment Request API - Web APIs
provides a browser-based method of connecting users and their preferred payment systems and platforms to merchants that they want to pay for goods and services. this article is a guide to making use of the payment request api, with examples and suggested best practices. the basics of making a payment this section details the basics of using the payment request api to make a payment. note: the code snippets from this section are from our feature detect support demo. creating a new payment request object a payment request always starts with the creation of a new paymentrequest object — using the paymentrequest() constructor. this takes two mandatory parameters and one option parameter: methoddata — an object containing information concerning the payment provider, such as what payme...
...ails()); the functions invoked inside the constructor simply return the required object parameters: function buildsupportedpaymentmethoddata() { // example supported payment methods: return [{ supportedmethods: 'basic-card', data: { supportednetworks: ['visa', 'mastercard'], supportedtypes: ['debit', 'credit'] } }]; } function buildshoppingcartdetails() { // hardcoded for demo purposes: return { id: 'order-123', displayitems: [ { label: 'example item', amount: {currency: 'usd', value: '1.00'} } ], total: { label: 'total', amount: {currency: 'usd', value: '1.00'} } }; } starting the payment process once the paymentrequest object has been created, you call the paymentrequest.show() method on it t...
...'success') .then(function() { // for demo purposes: intropanel.style.display = 'none'; successpanel.style.display = 'block'; }); }) this object provides the developer with access to details they can use to complete the logical steps required after the payment completes, such as an email address to contact the customer, a shipping address for mailing goods out to them, etc. in the code above, you'll see that we've called the paymentresponse.complete() method to signal that the interaction has finished — you'd use this to carry out finishing steps, like updating the user interface to tell the user the transaction is complete, etc. other useful payment request methods there are some other useful payment request methods worth knowing about. paymentrequest.canmakepayment() can...
...And 8 more matches
TransformStream - Web APIs
this is intended as a polyfill for unsupported platforms. ...
...this is intended as a polyfill for unsupported platforms. const t...
...r("cannot send a symbol as a chunk part") break case 'undefined': controller.error("cannot send undefined as a chunk part") default: controller.enqueue(this.textencoder.encode(string(chunk))) break }, flush() { /* do any destructor work here */ } } class anytou8stream extends transformstream { constructor() { super({...transformcontent, textencoder: new textencoder()}) } } polyfilling textencoderstream and textdecoderstream note that this is deprecated by the native constructors. this is intended as a polyfill for unsupported platforms. ...
...And 8 more matches
Inputs and input sources - Web APIs
ould then look at each input source and find one matching this, if available, falling back to another controller if no controller is in that hand. ...
...then the select event handler is replaced with the function realselecthandler(), which will be used for handling all future select events. ...
... events tell you when you might want to display something to the user indicating that the primary action is going on. this might be drawing a controller with the activated button in a new color, or showing the targeted object being grabbed and moved around, starting when selectstart arrives and stopping when selectend is received. the select event, on the other hand, is the event that tells your code that the user has completed the action they want to complete. this might be as simple as throwing an object or pulling the trigger of a gun in a game, or as involved as placing an object that they were dragging around the world back down again in a new location. if your primary action is a simple trigger action and you don't need to animate anything while the trigger is engaged, you can ignore t...
...And 8 more matches
WritableStream.WritableStream() - Web APIs
() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...f the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 8 more matches
WritableStream - Web APIs
() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...f the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 8 more matches
WritableStreamDefaultWriter - Web APIs
rface of the the streams api is the object returned by writablestream.getwriter() and once created locks the writer to the writablestream ensuring that no other streams can write to the underlying sink. constructor writablestreamdefaultwriter() creates a new writablestreamdefaultwriter object instance. properties writablestreamdefaultwriter.closedread only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the writer's lock is released, or rejects if the stream errors. writablestreamdefaultwriter.desiredsizeread only returns the desired size required to fill the stream's internal queue. writablestreamdefaultwriter.readyread only returns a promise that resolves when the desired...
...is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...ach chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 8 more matches
filter - CSS: Cascading Style Sheets
Web › CSS › filter
<image xlink:href="/files/3710/test_form_2.jpeg" filter="url(#svgblur)" width="212px" height="161px"/> </svg> </div> </td> <td><img alt="test_form_s.jpg" id="img4" class="internal default" src="/files/3711/test_form_2_s.jpg" style="width: 100%;" /></td> </tr> </tbody> </table> html { height:100%; } body { font: 14px/1.286 "lucida grande", "lucida sans unicode", "dejavu sans", lucida, arial, helvetica, sans-serif; color: rgb(51, 51, 51); height:100%; overflow:hidden; } #img2 { width:100%; height:auto; -webkit-filter:blur(5px); -ms-filter:blur(5px); filter:blur(5px); } table.standard-table { border: 1px solid rgb(187, 187, 187); border-collapse: collapse; border-spacing: 0; margin: 0 0 1.286em; height: 100%; width: 85%; } tab...
...ponenttransfer> </filter> <image xlink:href="/files/3708/test_form.jpg" filter="url(#brightness)" width="286px" height="217px" /> </svg><div></td> <td><img alt="test_form_s.jpg" id="img4" class="internal default" src="/files/3709/test_form_s.jpg" style="width: 100%;" /></td> </tr> </tbody> </table> html { height:100%; } body { font: 14px/1.286 "lucida grande","lucida sans unicode","dejavu sans",lucida,arial,helvetica,sans-serif; color: rgb(51, 51, 51); height:100%; overflow:hidden; } #img2 { width:100%; height:auto; -moz-filter:brightness(2); -webkit-filter:brightness(2); -ms-filter:brightness(2); filter:brightness(2); } table.standard-table { border: 1px solid rgb(187, 187, 187); border-collapse: collapse; border-spacing: 0px; margin: 0px 0px 1.
...enttransfer> </filter> <image xlink:href="/files/3712/test_form_3.jpeg" filter="url(#contrast)" width="240px" height="151px" /> </svg><div></td> <td><img alt="test_form_s.jpg" id="img4" class="internal default" src="/files/3713/test_form_3_s.jpg" style="width: 100%;" /></td> </tr> </tbody> </table> html { height:100%; } body { font: 14px/1.286 "lucida grande","lucida sans unicode","dejavu sans",lucida,arial,helvetica,sans-serif; color: rgb(51, 51, 51); height:100%; overflow:hidden; } #img2 { width:100%; height:auto; -moz-filter:contrast(200%); -webkit-filter:contrast(200%); -ms-filter:contrast(200%); filter:contrast(200%); } table.standard-table { border: 1px solid rgb(187, 187, 187); border-collapse: collapse; border-spacing: 0px; margin: 0px 0p...
...And 8 more matches
Writing forward-compatible websites - Developer guides
it's not always possible to follow all of these, but following as many of them as possible will help future-proof your website. ...
...is really a particularly common instance of assuming that one feature (the presence of a particular substring in the user agent (ua) string) implies something about the presence or absence of other features. if you have to ua-sniff, only sniff for past browser versions if you have to resort to ua sniffing, only use it to target past browser versions of particular browsers. ...
...tring) implies something about the presence or absence of other features. if you have to ua-sniff, only sniff for past browser versions if you have to resort to ua sniffing, only use it to target past browser versions of particular browsers. first, have a default code path that runs in unknown browsers and in the current and future versions of browsers you are testing with. then, if the default code path doesn't work in past versions of particular browsers and the breakage cannot be detected by sniffing for the absence of certain features your default code path uses, it's ok to add hacks that are targeted to old versions of particular browsers by sniffing for those old browser versions. for the purpose of this piece of advice, "current" means the most recent version of a browser you have te...
...And 8 more matches
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
n the same document. the <datalist> provides a list of predefined values to suggest to the user for this input. any values in the list that are not compatible with the type are not included in the suggested options. the values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. maxlength the maximum number of characters (as utf-16 code units) the user can enter into the telephone number field. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the telephone number field has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text entered into the field is greater than ma...
...r can enter into the telephone number field. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the telephone number field has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text entered into the field is greater than maxlength utf-16 code units long. minlength the minimum number of characters (as utf-16 code units) the user can enter into the telephone number field. this must be an non-negative integer value smaller than or equal to the value specified by maxlength. if no minlength is specified, or an invalid value is specified, the telephone number input has no minimum length. the telephone number field will fail constraint va...
... can enter into the telephone number field. this must be an non-negative integer value smaller than or equal to the value specified by maxlength. if no minlength is specified, or an invalid value is specified, the telephone number input has no minimum length. the telephone number field will fail constraint validation if the length of the text entered into the field is fewer than minlength utf-16 code units long. pattern the pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treat...
...And 8 more matches
Grammar and types - JavaScript
for example, the word früh (which means "early" in german) could be used as a variable name. ...
...ey must be separated by semicolons. ecmascript also has rules for automatic insertion of semicolons (asi) to end statements. (for more information, see the detailed reference about javascript's lexical grammar.) it is considered best practice, however, to always write a semicolon after a statement, even when it is not strictly needed. this practice reduces the chances of bugs getting into the code. the source text of javascript script gets scanned from left to right, and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments, or whitespace. (spaces, tabs, and newline characters are considered whitespace.) comments the syntax of comments is the same as in c++ and in many other languages: // a one line comment /* this is a longer,...
...our application. the names of variables, called identifiers, conform to certain rules. a javascript identifier must start with a letter, underscore (_), or dollar sign ($). subsequent characters can also be digits (0–9). because javascript is case sensitive, letters include the characters "a" through "z" (uppercase) as well as "a" through "z" (lowercase). you can use most of iso 8859-1 or unicode letters such as å and ü in identifiers. (for more details, see this blog post.) you can also use the unicode escape sequences as characters in identifiers. some examples of legal names are number_hits, temp99, $credit, and _name. declaring variables you can declare a variable in two ways: with the keyword var. for example, var x = 42. this syntax can be used to declare both local and glob...
...And 8 more matches
Inheritance and the prototype chain - JavaScript
console.log(o.d); // undefined // is there a 'd' own property on o? no, check its prototype. // is there a 'd' own property on o.[[prototype]]? no, check its prototype. // o.[[prototype]].[[prototype]] is object.prototype and there is no 'd' property by default, check its prototype. // o.[[prototype]].[[prototype]].[[prototype]] is null, stop searching, // no property found, return undefined. code link setting a property to an object creates an own property. the only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter. inheriting "methods" javascript does not have "methods" in the form that class-based languages define them. in javascript, any function can be added to an object in the form of a property. an inherited funct...
...g(p.m()); // 5 // when p.m is called, 'this' refers to p. // so when p inherits the function m of o, // 'this.a' means p.a, the property 'a' of p using prototypes in javascript let's look at what happens behind the scenes in a bit more detail. in javascript, as mentioned above, functions are able to have properties. all functions have a special property named prototype. please note that the code below is free-standing (it is safe to assume there is no other javascript on the webpage other than the below code). for the best learning experience, it is highly recommended that you open a console, navigate to the "console" tab, copy-and-paste in the below javascript code, and run it by pressing the enter/return key. (the console is included in most web browser's developer tools. more informat...
...t matter how you declare the function, a // function in javascript will always have a default // prototype property. // (ps: there is one exception that arrow function doesn't have a default prototype property) var dosomething = function(){}; console.log( dosomething.prototype ); as seen above, dosomething() has a default prototype property, as demonstrated by the console. after running this code, the console should have displayed an object that looks similar to this. { constructor: ƒ dosomething(), __proto__: { constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolocalestring(), tostring: ƒ tostring(), valueo...
...And 8 more matches
String.prototype.normalize() - JavaScript
if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. ...
...turns the unicode normalization form of the string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.normalize([form]) parameters form optional one of "nfc", "nfd", "nfkc", or "nfkd", specifying the unicode normalization form. if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. ...
...", specifying the unicode normalization form. if omitted or undefined, "nfc" is used. these values have the following meanings: "nfc" canonical decomposition, followed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, followed by canonical composition. "nfkd" compatibility decomposition. return value a string containing the unicode normalization form of the given string. errors thrown rangeerror a rangeerror is thrown if form isn't one of the values specified above. description unicode assigns a unique numerical value, called a code point, to each character. for example, the code point for "a" is given as u+0041. ...
...And 8 more matches
throw - JavaScript
w userexception('invalidmonthno'); } } try { // statements to try var mymonth = 15; // 15 is out of bound to raise the exception var monthname = getmonthname(mymonth); } catch (e) { monthname = 'unknown'; console.error(e.message, e.name); // pass exception object to err handler } another example of throwing an object the following example tests an input string for a u.s. zip code. if the zip code uses an invalid format, the throw statement throws an exception by creating an object of type zipcodeformatexception. /* * creates a zipcode object. * * accepted formats for a zip code are: * 12345 * 12345-6789 * 123456789 * 12345 6789 * * if the argument passed to the zipcode constructor does not * conform to one of these patterns, an exception is thrown. ...
... uses an invalid format, the throw statement throws an exception by creating an object of type zipcodeformatexception. /* * creates a zipcode object. * * accepted formats for a zip code are: * 12345 * 12345-6789 * 123456789 * 12345 6789 * * if the argument passed to the zipcode constructor does not * conform to one of these patterns, an exception is thrown. ...
.../* * creates a zipcode object. * * accepted formats for a zip code are: * 12345 * 12345-6789 * 123456789 * 12345 6789 * * if the argument passed to the zipcode constructor does not * conform to one of these patterns, an exception is thrown. ...
...And 8 more matches
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
phong lighting model. in svg, this can be any non-negative number. 58 direction svg, svg attribute the direction attribute specifies the inline-base direction of a <text> or <tspan> element. it defines the start and end points of a line of text as used by the text-anchor and inline-size properties. it also may affect the direction in which characters are positioned if the unicode-bidi property's value is either embed or bidi-override. 59 display svg, svg attribute the display attribute lets you control the rendering of graphical or container elements. 60 divisor filters, svg, svg attribute the divisor attribute specifies the value by which the resulting number of applying the kernelmatrix of a <feconvolvematrix> element to the inp...
...g attribute the transform-origin svg attribute sets the origin for an item’s transformations. 225 type needscompattable, needsexample, svg, svg attribute, filter the type attribute is a generic attribute and it has different meaning based on the context in which it's used. ...
... sets the origin for an item’s transformations. 225 type needscompattable, needsexample, svg, svg attribute, filter the type attribute is a generic attribute and it has different meaning based on the context in which it's used. ...
...And 8 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
ox. all of these documents currently assume, however, that you are developing your extension using xul and javascript only. for complex extensions, it may be necessary to create components in c++ that provide additional functionality. reasons why you might want to include c++ components in your extension include: need for high-performance beyond what can be delivered by javascript code. use of third-party libraries written in c or c++. use of mozilla interfaces that are not exposed via xpcom (e.g. nspr). note: with the modern jit javascript engine in gecko and js-ctypes more extension code can be written only in javascript than ever before. please consider all of your options carefully before deciding to use native code (c++) in your extension. i...
...iles that are to be used directly by other modules. the easiest way to accomplish the latter is to use inline implementations for all methods so you don't have any additional linking dependencies. otherwise you will have to link statically to your module if you use these public headers in other modules. personally i would discourage this practice (among other things, static linking means the same code gets loaded more than once into memory, and the code won't be available from javascript or other non-c++ languages) and encourage the use of xpcom wherever possible. the makefile in the public/ directory should follow this model: depth = ../../.. topsrcdir = @top_srcdir@ srcdir = @srcdir@ vpath = @srcdir@ include $(depth)/config/autoconf.mk module = myextension xp...
....mk xpidl_module is the name of the generated xpt file that contains type information about your idl interfaces. if you have multiple modules, make absolutely sure that you use a different value for xpidl_module for each one. otherwise the first module's xpt file will be overwritten by the second and you'll get ns_error_xpc_bad_iid errors when you try to access its idl interfaces from your code. the files under exports are copied directly to the /mozilla/$(moz_objdir)/dist/include/ directory and are thus accessible from other modules (the value of moz_objdir is defined in /mozilla/.mozconfig). xpidlsrcs are run through the idl processor, and the generated c++ headers are copied into the same include directory. in addition, an xpt (type library) file is generated and placed in the compon...
...And 7 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
ser files.” set up quicknote for the purposes of this explanation, we’re going to use the file-storage mechanism in quicknote1 for our debugger. install quicknote from the following url and relaunch firefox. https://addons.mozilla.org/firefox/46/. after relaunching firefox, activate quicknote. then select tools:quicknote:float to display it in its own window. using venkman read in source code activate venkman, and then select open windows:quicknote.xul:files on the top-left of the screen. double-click on quicknote.js to open it in source-code view (figure 2). fixme: figure 2: selecting source code inserting breakpoints now you’ll want to set some breakpoints. try inserting one within the quicknote_savenote function, around line 345 (figure 3). fixme: figure 3: inserting a break...
...alc.js. update it with the contents of listing 3. run test run the test again. you should see a green bar showing that the test succeeded. implement the subtraction operation now let’s add subtraction. create test case first, add the test case for the subtraction method. open test_calc.js and update it with the method in listing 4. implement in calc.js next we need to add the executable code. this will work much as it did for addition. update calc.js with the method in listing 5. run test if we run the test at this point, we’ll get a red bar. what’s the matter? the screen will display “expected -1, got 1”. somehow, using pop() got the order of the arguments mixed up. so let’s update the _letfunc function as shown in listing 6. if we run the test again, we should get a gr...
...we’re going to use mxr (http://mxr.mozilla.org), a linux so...
...And 7 more matches
Custom XUL Elements with XBL - Archive of obsolete content
. you should see a new item in the hello world menu, that opens a binding test window where you can add "persons" to a list. xbl basics in order to create an xbl binding you'll need 2 files: the xbl file and a css file that binds an element name to your xbl declaration. if you look into the content directory, you'll see both files: person.xml - this is the main binding file. it holds all the code necessary to control the new element we created. we'll look into the code throughout the rest of this section. for now, just notice the opening part of the binding element: <binding id="person">. bindings.css - this is the file that associates the element name to the xbl file. it associates the xshelloperson element name to the binding defined in the xbl file. since you can have more than one bi...
... for binding elements. notice how the default namespace for the document is xbl, and the xul namespace is defined as "xul". you'll need to keep this in mind when defining the content of the binding, because weird things can happen if you don't add "xul:" to your content nodes. <binding id="person"> in general, you should only have one binding per file. bindings tend to require many lines of code, and having more than one ends up making gigantic, unbrowsable files. on the other hand, if your bindings are small and have a strong relationship with each other, it makes sense to keep them together. as for the css file, it's usually good to have a single file declaring all bindings in your extension. content under the content tag you define the xul content that will be displayed for your ele...
...ur content. the xbl:inherits attribute lets your inner xul use the attributes that are set on the node. so, if you have this: <xshelloperson name="pete" greeting="good morning" image="" />, then those attribute values are "inherited" to the content nodes that have this special attribute. the value attribute of the xul:label element would be "pete". the oncommand attribute of the button has some code you've probably never seen before: document.getbindingparent(this). this code gets the dom object that corresponds to the xshelloperson tag, allowing you access to its methods and properties. in this case we're calling the remove method, which we will discuss later on. if you need to create a container element, or any other element that has child nodes, you can use the xbl children tag in your ...
...And 7 more matches
Index of archived content - Archive of obsolete content
n logging modifying web pages based on url modifying the page hosted by a tab open a web page troubleshooting unit testing using xpcom without chrome using third-party modules (jpm) bootstrapped extensions code snippets alerts and notifications autocomplete bookmarks boxes canvas code snippets cookies customizing the download progress bar delayed execution dialogs and prompts downloading files drag & drop embedding svg examples and demos ...
...bookmarks boxes canvas code snippets cookies customizing the download progress bar delayed execution dialogs and prompts downloading files drag & drop embedding svg examples and demos from articles file i/o finding window handles forms related code snippets html in xul for rich tooltips html to dom isdefaultnamespace js xpcom javascript debugger service javascript timers javascript daemons management label and description lookupnamespaceuri lookupprefix m...
... progress listeners queryselector rosetta running applications svg animation svg general scrollbar sidebar stringview tabbox toolbar tree uri parsing view source for xul applications windows xml-related code snippets xml:base support in old browsers xpath getattributens common pitfalls communication between html and your extension creating custom firefox extensions with the mozilla build system custom about: urls default preferences deployin...
...And 7 more matches
Localizing an extension - Archive of obsolete content
calize into various languages without having to edit the xul or javascript files themselves. if you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension. download the sample localizing strings in xul files create the needed locale files each xul file that comprises the user interface for your extension should have a locale file in its locale directory. each locale file maps entity names referenced in the xul files to the strings themselves. the pre...
...watcher2.xul file: <!entity panel_loading "loading..."> <!entity menu_refresh_now.label "refresh now"> <!entity menu_apple.label "apple (aapl)"> <!entity menu_google.label "google (goog)"> <!entity menu_microsoft.label "microsoft (msft)"> <!entity menu_yahoo.label "yahoo (yhoo)"> update the xul files each xul file needs to reference its corresponding locale file. we also need to update the code to use the entities instead of the strings, so that the substitutions take place based on the currently active locale. to add a reference to the correct locale file for a given xul file, we need to add one line to the xul file. to options.xul, we add this line: <!doctype window system "chrome://stockwatcher2/locale/options.dtd"> we add a similar line to the stockwatcher.xul file: <!doctype ove...
...on()"/> do this for every string used in each xul file. update the chrome manifest to let firefox know about the locale files, we need to make a revision to our chrome.manifest file, adding one line for each localization: locale stockwatcher2 en-us chrome/locale/ this instructs firefox that the en-us localization is located in the chrome/locale/en-us directory. localizing strings in javascript code if your javascript code contains literal strings that need to be localized, as does our stock watcher sample, we need to make those localizable as well. we can do this by moving the strings into a string bundle. string bundles are created by establishing a property file that maps keys to string values. for a detailed explanation of how this works, see xul tutorial:property files. create a propert...
...And 7 more matches
Venkman Introduction - Archive of obsolete content
will make you a more confident web developer and debugger. venkman is both a graphic and a console debugger. features such as breakpoint management, call stack inspection, and variable/object inspection are available from the user interface and from console commands, letting you work in the way you are most accustomed to. the interactive console also allows for execution of arbitrary javascript code. venkman's keyboard shortcuts are the same as leading visual debugging environments, and gdb users should be familiar with venkman's /break, /step, /next, /finish, /frame, and /where commands. on windows, the javascript debugger compares favorably with visual interdev and other large web development tools. on other platforms, including mac os and unix, it is alone in offering this degree of flex...
... in the view customization section below. the scripts that have been loaded by the javascript engine appear in the loaded scripts window (for more information about how scripts are loaded and accessed in venkman, see "loading scripts into the debugger"). the menubar, toolbar, and all of the views can be collapsed or hidden, giving you a lot of control over the debugging environment. the source code view is empty until you select a script, and the interactive session view starts up with basic startup information. each of the views has a label, a float button that lets you display the view in its own window, and a close button that puts the view away until you want to display it again, as seen in figure 2. the following section describes these views and their use within the interface as a w...
...ed you will see a green check mark on the toolbar button, and the menu item will be checked as well. the loaded scripts view the loaded scripts view is in the top left portion of the window. when a file is loaded by the browser it will appear in this view, and when unloaded it will be removed. files are listed in alphabetical order, grouped by file type. file names are displayed after a color coded, single letter icon representing the file extension. figure 6 shows the table of icon and file types. at the time if this writing, the order and grouping of file names cannot be changed. icon file type .js .html, .htm .xul .xml all other files javascript function figure 6. icons in the script view...
...And 7 more matches
When To Use ifdefs - Archive of obsolete content
in this document, the term is used more loosely to discuss any kind of conditional that differentiates between different build configurations. ...
...in this document, the term is used more loosely to discuss any kind of conditional that differentiates between different build configurations. ...
...in this document, the term is used more loosely to discuss any kind of conditional that differentiates between different build configurations. ...
...And 7 more matches
Elements - Archive of obsolete content
.org/xbl%22%3e%0a%20%20%3cbinding%20id%3d%22xbltest%22%3e%3ccontent%3epass%3c/content%3e%3c/binding%3e%0a%3c/bindings%3e%0a); } since data: urls don't support fragment identifiers, the first binding found in the embedded xml is used instead. keep in mind that the binding is still required to have an id even though you're not referencing it. in addition, data: urls are only supported from chrome code (in other words, from the application or an extension). note: the normal same-origin policy is used for web sites; they can only link to xbl files on the same domain, or within the chrome. for clarity's sake, here's what the embedded xml in the previous example looks like: <?xml version="1.0"?> <bindings id="xbltestbindings" xmlns="http://www.mozilla.org/xbl"> <binding id="xbltest"><content>...
...f interfaces that are implemented by the binding. its value is a comma-separated list of named interfaces. if supported, in strongly typed languages the bound element can be referenced not only as any of the interfaces that the element might already support (e.g., htmlelement) but also as any of the interfaces described by this attribute. support of this capability is optional. constructor the code inside the constructor is called when a binding has just been attached to an element. so full access to anonymous nodes generated by the binding is already possible. the constructor tag must be placed inside the implementation tag. id - the id attribute is a document-unique identifier. note: prior to firefox 3, the constructor could be called at a time when reflow of the document layout was...
... get layout information from within the constructor could return out of date information. in firefox 3 and later, the constructor is called when reflow can take place, which results in up-to-date information being returned. see bug 398404 for details. note: all properties of the binding are "imported" as local variables in a constructor's scope. see bug 407314 for more details. destructor the code inside the destructor is called when a binding is being removed from an element. you can use this to unload resources to free memory. however the destructor is often not called when it should, see bug 230086. the destructor tag must be placed inside the implementation tag. id - the id attribute is a document-unique identifier. method <!entity % method-content "(parameter*,body?)"> <!element...
...And 7 more matches
XUL Questions and Answers - Archive of obsolete content
ocumentation on search plugins is available in the search plugins category. is localizing remote xul possible? loading remote dtds for xml documents is currenty not supported in xul. the following bugs were reported on this issue: bug 22942, bug 133698. is there an editor widget in xul that supports syntax highlighting? daniel glazman has been working on this for his projects. he said the code will be open-source, but it is not released yet (as of oct 2006). some teasers are on his blog. overlaying elements without ids the original developers only tend to put ids where they need them. as an extension author, you have at least two options: use dom methods to dynamically create or rearrange elements file an enhancement request in bugzilla to have extra ids added. displaying g...
...n a mac? unfortunately, no simple solution to this was posted. a workaround is to open the content in a new window using "window.open" and send titlebar=”no” as one of the flags in the 3rd argument. is it possible to have checkbox support for multi column lists? the current issue is a person exploring if it is possible to have checkbox support for multi column lists. ...
... 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 the server. by getting data (e.g. json string) from the server, parsing it on client, and building the menupopup using dom methods (such as document.createelementns). by getting data as xml from the server. (server can just send the xul code to use for popup - alternatively it can send generic xml describing the attributes of the items in the menu and you generate the xul on client by applying an xslt transform.) can i change a xul tree cell/row/item background color with javascript? to set the background color you need to set the property for the cell/row and not for the item. an example of this is: var tree = document.getelem...
...And 7 more matches
Common causes of memory leaks in extensions - Extensions
ed to be aware of the practices that caused these leaks, as the fix causes many add-ons which would have otherwise caused a leak to instead throw errors when attempting to access nodes from documents which no longer exist. storing references to window objects and dom nodes the most common problem is extensions holding onto references to content windows for too long. for example, in xul overlay code: var contentwindows = []; function inbrowserxuloverlay(contentwindow) { // forgetting or failing to pop the content window thing again contentwindows.push(contentwindow); } this will keep the content window compartments alive until the browser window is closed. users often only open a single browser window per session and use tabs, in which case the leaked compartments will live for the wh...
...tments alive until the browser window is closed. users often only open a single browser window per session and use tabs, in which case the leaked compartments will live for the whole life of the session. a similar problem is holding onto window objects or dom nodes (such as window.document) for too long by storing them in a javascript module. for example: var windows = []; function injavascriptcodemodule(window) { // forgetting or failing to pop the window again windows.push(window); } both of these cases can happen if you forget to declare local variables with var or let, which means they end up belonging to the global scope. for example: function implicitdeclarationleak(window) { // implicit variable declaration in the js global, holding a strong ref to the document doc = windo...
... local variables with var or let, which means they end up belonging to the global scope. for example: function implicitdeclarationleak(window) { // implicit variable declaration in the js global, holding a strong ref to the document doc = window.document; } implicitly declared variables can be avoided by using ecmascript 5's strict mode. strict mode also excludes several other error-prone code patterns. for some examples found in real-world add-ons, see bug 712733, bug 725875, and bug 727552. to avoid these issues, references to dom nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. be careful with setinterval/settimeout using window.setinterval() or window...
...And 7 more matches
Paddle and keyboard controls - Game development
« previousnext » this is the 4th 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/lesson4.html. the ball is bouncing off the walls freely and you can watch it indefinitely, but currently there's no interactivity. it's not a game if you cannot control it! so let's add some user interaction: a controllable paddle. defining a paddle to hit the ball so, we need a paddle to hit the ball. let's define a few variables for that. add the following variables near the top of your code, beside your other variables: var paddleheight = 10; var paddlewidth = 75; var paddlex = (canvas.width-paddlewidth) / 2; here we're defining the height and width of the paddle and its starting point on th...
...let's create a function that will draw the paddle on the screen. ...
...ll(); ctx.closepath(); } allowing the user to control the paddle we can draw the paddle wherever we want, but it should respond to the user's actions. it's time to implement some keyboard controls. we will need the following: two variables for storing information on whether the left or right control button is pressed. two event listeners for keydown and keyup events. we want to run some code to handle the paddle movement when the buttons are pressed. two functions handling the keydown and keyup events the code that will be run when the buttons are pressed. the ability to move the paddle left and right pressed buttons can be defined and initialized with boolean variables like in the example. add these lines somewhere near the rest of your variables: var rightpressed = false; var...
...And 7 more matches
Storing the information you need — Variables - Learn web development
eal basics, looking at how to work with the most basic building blocks of javascript — variables. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. objective: to gain familiarity with the basics of javascript variables. tools you need throughout this article, you'll be asked to type in lines of code to test your understanding of the content. if you are using a desktop browser, the best place to type your sample code is your browser's javascript console (see what are browser developer tools for more information on how to access this tool). what is a variable? a variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. but ...
...part of a sentence. but one special thing about variables is that their contained values can change. let's look at a simple example: <button>press me</button> const button = document.queryselector('button'); button.onclick = function() { let name = prompt('what is your name?'); alert('hello ' + name + ', nice to see you!'); } in this example pressing the button runs a couple of lines of code. the first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. the second line displays a welcome message that includes their name, taken from the variable value. to understand why this is so useful, let's think about how we'd write this example without using a variable. it would end up looking something like this: let name = promp...
...'bella') { alert('hello bella, nice to see you!'); } else if (name === 'bianca') { alert('hello bianca, nice to see you!'); } else if (name === 'chris') { alert('hello chris, nice to see you!'); } // ... and so on ... you may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for any name. this is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work — you couldn't possibly store all possible choices. variables just make sense, and as you learn more about javascript they will start to become second nature. another special ...
...And 7 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
r fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in javascript programs. prerequisites: basic computer literacy, a basic understanding of html and css, an understanding of what javascript is. objective: to gain the ability and confidence to start fixing problems in your own code. types of error generally speaking, when you do something wrong in code, there are two main types of error that you'll come across: syntax errors: these are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. these are usually okay to fix, as long as you are famil...
...these are often harder to fix than syntax errors, as there usually isn't an error message to direct you to the source of the error. okay, so it's not quite that simple — there are some other differentiators as you drill down deeper. ...
...s in greater detail. the name of the javascript file, which links through to the debugger tab of the developer tools. if you follow this link, you'll see the exact line where the error is highlighted. the line number where the error is, and the character number in that line where the error is first seen. in this case, we've got line 86, character number 3. if we look at line 86 in our code editor, we'll find this line: guesssubmit.addeventlistener('click', checkguess); the error message says "guesssubmit.addeventlistener is not a function", which means that the function we're calling is not recognized by the javascript interpreter. often, this error message actually means that we've spelled something wrong. if you are not sure of the correct spelling of a piece of syntax, it i...
...And 7 more matches
Framework main features - Learn web development
to updating the dom, handling browser events, and providing an enjoyable developer experience. this article will explore the main features of “the big 4” frameworks, looking at how frameworks tend to work from a high level, and the differences between them. prerequisites: familiarity with the core html, css, and javascript languages. objective: to understand the main code features of frameworks. domain-specific languages all of the frameworks discussed in this module are powered by javascript, and all allow you to use domain-specific languages (dsls) in order to build your applications. in particular, react has popularized the use of jsx for writing its components, while ember utilizes handlebars. unlike html, these languages know how to read data variable...
...d"; var header = react.createelement("header", null, react.createelement("h1", null, "hello, ", subject, "!") ); when ultimately rendered by the browser, the above snippet will produce html that looks like this: <header> <h1>hello, world!</h1> </header> handlebars the handlebars templating language is not specific to ember applications, but it is heavily utilized in ember apps. handlebars code resembles html, but it has the option of pulling data in from elsewhere. this data can be used influence the html that an application ultimately builds. like jsx, handlebars uses curly braces to inject the value of a variable. handlebars uses a double-pair of curly braces, instead of a single pair. given this handlebars template: <header> <h1>hello, {{subject}}!</h1> </header> and this data...
...e of a variable. handlebars uses a double-pair of curly braces, instead of a single pair. ...
...And 7 more matches
Cross Process Object Wrappers
this document describes cross process object wrappers (cpows), which enable chrome code to synchronously access content in multiprocess firefox. note that from firefox 47 onwards, unsafe cpow usage is no longer permitted in browser code. if browser code tries an unsafe cpow operation, the browser will throw an exception and you'll see an "unsafe cpow usage forbidden” error in the browser console. add-on code is still allowed to use cpows "unsafely". however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an exception. so as a general rule, add-ons should avoid passing cpows into non-addon code. ...
...on and you'll see an "unsafe cpow usage forbidden” error in the browser console. add-on code is still allowed to use cpows "unsafely". however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an exception. so as a general rule, add-ons should avoid passing cpows into non-addon code. in multiprocess firefox, chrome code runs in a different process from web content. so chrome code can't directly interact with web content: instead, it must factor out the code that interacts with web content into separate scripts that are called frame scripts. chrome code can load frame scripts into the content process using the message manager, and can then communicate with them using a message-passing api. to learn more about th...
...d can then communicate with them using a message-passing api. to learn more about this, see the documentation on using the message manager. chrome to content messaging must be asynchronous. this is because the chrome process runs the firefox ui, so if it were blocked by the content process, then a slow content process could cause firefox to become unresponsive to users. converting synchronous code to be asynchronous can be difficult and time-consuming. as a migration aid, the messaging framework enables frame scripts to make content objects available to chrome through a wrapper called a cross process object wrapper, also known as a cpow. however, although cpows are convenient, they have serious limitations and can cause responsiveness problems, so should only be used when necessary and onl...
...And 7 more matches
Message manager overview
in the initial version of multiprocess firefox there are two processes: the chrome process, also called the parent process, runs the browser ui (chrome) code and code inserted by extensions the content processes, also called the child processes, run all web content. different tabs may run in different processes. message managers are designed to enable code in one process to communicate with code in a different process. ...
...e) code and code inserted by extensions the content processes, also called the child processes, run all web content. different tabs may run in different processes. message managers are designed to enable code in one process to communicate with code in a different process. at the top level, there are two different sorts of message managers: frame message managers: these enable chrome process code to load a script into a browser frame (essentially, a single browser tab) in the content process. these scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. if chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. process message managers: these correspond to proce...
...rowser frame (essentially, a single browser tab) in the content process. these scripts are called frame scripts, and as the name suggests, they are scoped to a specific browser frame. if chrome code wants to run code in the content process so it can access web content, this is usually the sort of message manager to use. process message managers: these correspond to process boundaries, and enable code running in the parent (chrome) process to communicate with code running in the child (content) process. ...
...And 7 more matches
Gecko Keypress Event
gecko 1.9 key handling changed significantly after beta 5 (bug 359638, bug 429510 and the bugs on which they depend). the changes were risky so late in the release schedule, but they were necessary for fixing the many key handling bugs. charcode of dom keypress event if a keypress event is fired without any modifier keys (ctrl/alt(option)/meta(win/command)), then the properties of the event are the same as they were in gecko1.8.1. that is, when the currently selected keyboard layout produces a unicode character (according to the current state of capslock and numlock), the charcode property contains that character. when the keypress event includes modifier keys, sometimes the charcode value is replaced with an ascii character according to the following rules. the accel key depends ...
... state of capslock and numlock), the charcode property contains that character. when the keypress event includes modifier keys, sometimes the charcode value is replaced with an ascii character according to the following rules. the accel key depends on the platform. ctrl is the accel key on windows and linux, while meta (i.e. command) is the accel key on mac. when the accel key is down, the charcode of a keypress event may be replaced with a character from a latin keyboard layout only when the original character is not an ascii character. this behavior helps the internationalization of web applications that have custom shortcut keys. ...
...e accel key on windows and linux, while meta (i.e. command) is the accel key on mac. when the accel key is down, the charcode of a keypress event may be replaced with a character from a latin keyboard layout only when the original character is not an ascii character. this behavior helps the internationalization of web applications that have custom shortcut keys. if gecko doesn't replace the charcode with an ascii character, the web application developers would need to consider all non-latin keyboard layouts (arabic, greek, hebrew, russian, etc.). the charcode value depends on the state of capslock and numlock (except they are currently ignored if alt (option) is down on mac - see bug 432953). there are also some differences between the platforms, as described in the following sections. win...
...And 7 more matches
CustomizableUI.jsm
it is available in the firefox window as the customizableui property on the window. if you want to use it from a jsm or another context without a window reference, you need to import it yourself: components.utils.import("resource:///modules/customizableui.jsm"); introduction the module is intended for two primary purposes: allow adding, moving and removing customizable widgets. manage the areas in which these widgets are shown. ...
...s, and mostly abstracts the dom away from you. the lifetime of your widget should be identical to the lifetime of the add-on - it's process-global, so if you call createwidget on bootstrap's "startup" and destroywidget on bootstrap's "shutdown", that's enough. listeners customizableui provides a way to listen for various bits of customization happening. this can be useful if other parts of the code need to react to changes in the customization of the user interface. in order to use this facility, you should create a plain js object which defines some of the event handlers defined below. not all event handler methods need to be defined. customizableui will catch exceptions. events are dispatched synchronously on the ui thread, so if you can delay any/some of your processing, that is advisab...
...e it was added. beginbatchupdate() start a batch update of items. during a batch update, the customization state is not saved to the user's preferences file, in order to reduce (possibly sync) io. calls to begin/endbatchupdate may be nested. callers should ensure that no matter what happens they call endbatchupdate once for each call to beginbatchupdate, even if there are exceptions in the code in the batch update. otherwise, for the duration of the firefox session, customization state is never saved. typically, you would do this using a try...finally block wrapped around your insertion code. endbatchupdate() end a batch update. see the documentation for beginbatchupdate above. state is not saved if we believe it is identical to the last known saved state. state is only ever saved ...
...And 7 more matches
Following the Android Toasts Tutorial from a JNI Perspective
toast description a toast provides simple feedback about an operation in a small popup. ...
...ge, and the current activity remains visible and interactive. for example, navigating away from an email before you send it triggers a "draft saved" toast to let you know that you can continue editing later. toasts automatically disappear after a timeout. toasts do not have to be created with jni; they are exposed by the nativewindow feature on firefox for android, see toast documentation. ...
...le and interactive. for example, navigating away from an email before you send it triggers a "draft saved" toast to let you know that you can continue editing later. toasts automatically disappear after a timeout. toasts do not have to be created with jni; they are exposed by the nativewindow feature on firefox for android, see toast documentation. ...
...And 7 more matches
Mozilla DOM Hacking Guide
seriously hacking on it requires excellent knowledge of c++ and xpcom, mozilla's own component model. in this document i will try to outline the main aspects of the implementation, beginning with the class info mechanism, which lies at the heart of the dom, then with the description of various interfaces and classes. ...
... and xpconnect. before we begin the explanation of class info, i'd like to introduce quickly the javascript engine and xpconnect. in javascript, there is no knowledge of types, like there is in c++. a function for example can be represented by a jsfunction, a jsobject, a jsval, ... this means that when we use the dom from javascript, we pass arguments that have no type. however, since the dom is coded in c++, we expect to receive an argument of the correct type for our function. this is one of the jobs of xpconnect. xpconnect will "wrap" the argument in a wrapper that will be of the type expected by our c++ function. similarly, then return type of the c++ function will be wrapped by xpconnect so that javascript can use it safely. when, in javascript, a client tries to access a dom object or ...
...cscriptable interface, implemented by the nsdomclassinfo class (see section) defines several flags, one of which is the want_getproperty flag. when set, it allows us to define a getproperty() function on nshistorysh (the helper class for the history object), which will handle the array behavior. indeed, it will forward the call history[1] to history.item(1), which is defined in the idl and easily coded. the relevant code is at nsdomclassinfo.cpp, around line 4520. these two examples demonstrate the power of the dom combined with xpconnect and the javascript engine. the possibilities are endless. "what do you want to code today?" ;-) all the dom classes are listed in an enum defined in nsidomclassinfo.h, nsdomclassinfoid. there are classes for the dom0, core dom, html, xml, xul, xbl, range, c...
...And 7 more matches
Mozilla Development Strategies
your writing skills, keep in mind that our helpful, happy documentation gnomes will follow along behind you and clean up for you. note: you can mark the bug with this keyword at any time; you don't need to wait until it's actually fixed. ...
...s will follow along behind you and clean up for you. note: you can mark the bug with this keyword at any time; you don't need to wait until it's actually fixed. take extra time to do it right the first time it's also better to come up with one really solid, well tested, well commented, clean, easy to maintain piece of code than a bunch of quick fixes. you (or someone else) will be back in that code someday. it's easier to do it right once, when your mind is in the problem, than to do it once quickly and then have to come back and do it again the right way. the only thing worse than not understanding someone else's code is not understanding your own. test your code qa's job is to assure quality, not to add quality. that's your job. it's your responsibility to find and fix the problems in y...
...eday. it's easier to do it right once, when your mind is in the problem, than to do it once quickly and then have to come back and do it again the right way. the only thing worse than not understanding someone else's code is not understanding your own. test your code qa's job is to assure quality, not to add quality. that's your job. it's your responsibility to find and fix the problems in your code before checking in. when you land your bug-free code, it's qa's job to assure others that it's really bug free. make sure you appreciate anyone who finds a bug in your code. appreciate it even more if they find it before you ship. they're giving you a second chance to get it right before it becomes a bug that affects users. minimize how you are affected by regressions unless you are the type t...
...And 7 more matches
Mozilla projects on GitHub
this is a great place to start looking for any projects not listed below. ...
...this is a great place to start looking for any projects not listed below. ...
...this is a great place to start looking for any projects not listed below. ...
...And 7 more matches
Creating JavaScript jstest reftests
ate.py. writing a new test file please read the high level advice for test writing in the parent article here. jstests has a special requirement: the call to reportcompare in every jstest is required by the test harness. except in old tests or super strange new tests, it should be the last line of the test. comparison functions and shared test functionality the jstest runner loads the code in js/src/tests/shell.js for every test. additionally, it loads every shell.js and broswer.js file in the subdirectories on the path from js/src/tests to the location of your test. if you have functionality several tests share in a given folder, you can add the functionality to the shell.js or broswer.js file in the directory. asserteq asserteq(v1, v2[, message]) checks that v1 and v2 are the s...
... in an unspecified way. for example, reportcompare sometimes considers numbers to be the same if they are "close enough" to each other, even if the == operator would return false. expected = 3; actual = 1 + 2; reportcompare(expected, actual, '3==1+2'); comparesource comparesource(expected, actual, description) is used to test if the decompilation of a javascript object (conversion to source code) matches an expected value. note that tests which use comparesource should be located in the decompilation sub-suite of a suite. for example, to test the decompilation of a simple function you could write: var f = (function () { return 1; }); expect = 'function () { return 1; }'; actual = f + ''; comparesource(expect, actual, 'decompile simple function'); handling shell or browser specific fe...
...runs in the browser. if your test needs to use shell-specific features, like gc(), either: make the test silently pass if those features aren't present; or make it a jit-test (so that it never runs in the browser); or at the top of the test, add the comment // skip-if(!xulruntime.shell), so that it only runs in the shell. ...
...And 7 more matches
JSAPI Cookbook
argsfromvp(argc, vp); jsobject *global = js_getglobalforobject(cx, &args.callee()); ... } defining a function // javascript function justforfun() { return null; } /* jsapi */ bool justforfun(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); args.rval().setnull(); return true; } ... /* * add this to your jscontext setup code. * this makes your c function visible as a global function in javascript. */ if (!js_definefunction(cx, global, "justforfun", &justforfun, 0, 0)) return false; to define many jsapi functions at once, use js_definefunctions. creating an array // javascript var x = []; // or "x = array()", or "x = new array" /* jsapi */ js::rootedobject x(cx, js_newarrayobject(cx, 0)); if (!x) retu...
....setint32(23); return true; returning a floating-point number // javascript return 3.14159; /* jsapi */ js::callargs args = js::callargsfromvp(argc, vp); args.rval().setdouble(3.14159); exception handling throw the most common idiom is to create a new error object and throw that. js_reporterror does this. note that javascript exceptions are not the same thing as c++ exceptions. the jsapi code also has to return false to signal failure to the caller. // javascript throw new error("failed to grow " + varietal + ": too many greenflies."); /* jsapi */ js_reporterror(cx, "failed to grow %s: too many greenflies.", varietal); return false; to internationalize your error messages, and to throw other error types, such as syntaxerror or typeerror, use js_reporterrornumber instead. javascr...
...eerror, use js_reporterrornumber instead. javascript also supports throwing any value at all, not just error objects. use js_setpendingexception to throw an arbitrary js::value from c/c++. ...
...And 7 more matches
SpiderMonkey 1.8.7
spidermonkey 1.8.5 is the javascript engine that shipped in firefox 4.0. ...
...key 1.8.7 is supported on all the platforms where firefox 10 runs. spidermonkey 1.8.7 includes type inference, which boosts the speed of the jägermonkey jit by about 30% over version 1.8.5. type inference largely obviates tracemonkey, so the tracemonkey jit has been removed. the jit is supported only on x86, x86_64 and arm architectures. on other platforms, the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8.7 this covers migrating from version 1.8.5. see the 1.8.5 release notes for information on migrating from earlier versions. the following features in earlier versions of spidermonkey have been dropped. xxx is there anything here? spidermonkey 1.8.7 is not binary-compatible w...
...versions. it's the same language, just not as fast. migrating to spidermonkey 1.8.7 this covers migrating from version 1.8.5. see the 1.8.5 release notes for information on migrating from earlier versions. the following features in earlier versions of spidermonkey have been dropped. xxx is there anything here? spidermonkey 1.8.7 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. xxx is t...
...And 7 more matches
Web Replay
between recording and replay. if this difference can affect the recording, the weak pointer must be instrumented so that during replay it holds onto its target for the same duration it was held while recording. recording a recording content process differs from a normal content process in the following ways: calls to certain functions are intercepted by hooking them (rewriting the machine code at their entry points to call a different function with the same signature), including the function used to dispatch mach messages. when a call or message is intercepted, the wrapped call/message is first performed normally and then it and its outputs are recorded in a data stream for the thread performing the call. during execution of the wrapped call/message, recording of any inner calls is s...
..., section above. the ipc, rewind, and debugger components are all active while recording. these spawn a number of threads which do not participate in the recording: any events they execute are live. see the sections below for details on how these affect the process' behavior. to make it easier to ensure that the non-deterministic components do not have an effect on recorded behavior, certain code regions can be marked as disallowing events — while executing them no thread, lock, or atomic events should be recorded. this is done in code associated with the non-deterministic components, such as during gc or ion compilation, to help track down behaviors that should go unrecorded. replaying a replaying content process behaves in the same way as a recording process, except for the followi...
... or restoring a snapshot they should be in a consistent state for the child process. constraints are used for when messages may be sent between the middleman and child process, ensuring that the middleman process cannot send a message at a time when the child process may be rewinding. debugger integration when debugging a normal content process, the devtools js debugger runs quite a bit of js code in the content process, communicating with the chrome process primarily through streams of json data. when debugging a child content process, this js code runs in the middleman process. when the code creates a debugger object, that debugger provides information about the child process rather than the current (middleman) process. while the debugger can indicate it is for a child process, the in...
...And 7 more matches
nsIDOMWindowUtils
void removesheet(in nsiuri sheeturi, in unsigned long type); void resumetimeouts(); void sendcompositionevent(in astring atype); obsolete since gecko 9 void sendcompositionevent(in astring atype, in astring adata, in astring alocale); obsolete since gecko 38.0 void sendcontentcommandevent(in astring atype, [optional] in nsitransferable atransf...
... void sendcompositionevent(in astring atype); obsolete since gecko 9 void sendcompositionevent(in astring atype, in astring adata, in astring alocale); obsolete since gecko 38.0 void sendcontentcommandevent(in astring atype, [optional] in nsitransferable atransferable); void getclassname(in object aobj); boolean sendkeyevent(in astring atype, in long akeycode, in long acharcode, in long amodifiers, [optional] in boolean apreventdefault); obsolete since gecko 15.0 boolean sendkeyevent(in astring atype, in long akeycode, in long acharcode, in long amodifiers, [optional] in unsigned long aadditionalflags); deprecated since gecko 38.0 void sendmouseevent(in astring atype, in float ax, in float ay, in long abutton, in long aclickcount, ...
...ollflags, in long adelta, in long amodifiers); obsolete since gecko 17.0 void sendwheelevent(in float ax, in float ay, in double adeltax, in double adeltay, in double adeltaz, in unsigned long adeltamode, in long amodifiers, in long alineorpagedeltax, in long alineorpagedeltay, in unsigned long aoptions); void sendnativekeyevent(in long anativekeyboardlayout, in long anativekeycode, in long amodifierflags, in astring acharacters, in astring aunmodifiedcharacters); void sendnativemouseevent(in long ascreenx, in long ascreeny, in long anativemessage, in long amodifierflags, in nsidomelement aelement); nsiquerycontenteventresult sendquerycontentevent(in unsigned long atype, in unsigned long aoffset, in unsigned long alength, in long ax, in long ay); obsole...
...And 7 more matches
nsIFocusManager
nsidomelement getfocusedelementforwindow(in nsidomwindow awindow, in prbool adeep, out nsidomwindow afocusedwindow); pruint32 getlastfocusmethod(in nsidomwindow window); void movecarettofocus(in ...
... var focusmanager = components.classes["@mozilla.org/focus-manager;1"] .getservice(components.interfaces.nsifocusmanager); method overview void clearfocus(in nsidomwindow awindow); void contentremoved(in nsidocument adocument, in nsicontent aelement); native code only! obsolete since gecko 2.0 void firedelayedevents(in nsidocument adocument); native code only! void focusplugin(in nsicontent aplugin); native code only! nsidomelement getfocusedelementforwindow(in nsidomwindow awindow, in prbool adeep, out nsidomwindow afocusedwindow); pruint32 getlastfocusmethod(in nsidomwindow window); void movecarettofocus(in nsidomwindow awindow); void elementisfocusable(in nsidomelement aelement, in unsigned long af...
... attributes attribute type description activewindow nsidomwindow the most active (frontmost) window, or null if no window ...
...And 7 more matches
Using COM from js-ctypes
veloped a series of technologies alongside the main windows api. this started out with dynamic data exchange (dde), which was superseded by object linking and embedding (ole) and later by the component object model (com), automation objects, activex controls, and the .net framework. com is c++ and it cannot be written directly with js-ctypes. this documentaion explains how to convert the com c++ code into js-ctypes code. basis and reference for this article bugzilla :: bug 738501 - implement ability to create windows shortcuts from javascript - comment 4 relavent topic bugzilla :: bug 505907 - support c++ calling from jsctypes converting com code to c code to convert com code to js-ctypes, we need to write c++ vtable pointers in c. after that, we can pass a pointer . speech synthesi...
...e for this article bugzilla :: bug 738501 - implement ability to create windows shortcuts from javascript - comment 4 relavent topic bugzilla :: bug 505907 - support c++ calling from jsctypes converting com code to c code to convert com code to js-ctypes, we need to write c++ vtable pointers in c. after that, we can pass a pointer . speech synthesis example let's start with following c++ code, which invokes microsoft speech api and says "hello, firefox!" with system default voice, then wait until the speaking done. #include <sapi.h> int main(void) { if (succeeded(coinitialize(null))) { ispvoice* pvoice = null; hresult hr = cocreateinstance(clsid_spvoice, null, clsctx_all, iid_ispvoice, (void**)&pvoice); if (succe...
... $ cl ole32.lib test.cpp vtable needs vtable description here. the order of the vtable is very critical. when used from c or js-ctypes, the order of the vtable methods should match the order of the c++ vtable. __stdcall and __cdecl needs __stdcall and __cdecl (callback_abi) description here. call by ...
...And 7 more matches
KeyboardEvent.which - Web APIs
the which read-only property of the keyboardevent interface returns the numeric keycode of the key pressed, or the character code (charcode) for an alphanumeric key pressed. syntax var keyresult = event.which; return value keyresult contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. please see keyboardevent.charcode and keyboardevent.keycode for more details. ...
...ode of the key pressed, or the character code (charcode) for an alphanumeric key pressed. syntax var keyresult = event.which; return value keyresult contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. please see keyboardevent.charcode and keyboardevent.keycode for more details. ...
...he key pressed, or the character code (charcode) for an alphanumeric key pressed. syntax var keyresult = event.which; return value keyresult contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. please see keyboardevent.charcode and keyboardevent.keycode for more details. ...
...And 7 more matches
Using the Media Capabilities API - Web APIs
the media capabilities api provides several key features to help you better decide how to handle media, but also to determine how well media is being handled, in real time. these features include: the ability to query the browser to determine its ability to encode or decode media given a specified set of encoding parameters. these parameters may include the codecs, resolutions, bit rates, frame rates, and other such details. with the media capabilities api, you can determine not just if the browser can support a given format, but whether or not it can do so efficiently and smoothly. in short, this api replaces—and improves upon—the mediasource method istypesupported() or the htmlmediaelement method canplaytype(). more and more finely-detailed information about the display's properties...
...(). more and more finely-detailed information about the display's properties, so that informed decisions can be made when choosing the best format to play on the user's device. for example, you can use the api to ensure that you don't try to play high dynamic range (hdr) content on a standard dynamic range (sdr) screen. support for getting real-time feedback about the playback of media, so your code can make informed decisions about adapting the stream's quality or other settings to manage the user's perceived media performance and quality. one feature of this is the ability to detect when the device switches gpus, so you can make appropriate adjustments based on the new gpu's capabilities. note: the display capabilities functionality mentioned in the third point above have not yet appear...
... mediacapabilities is available } else { // mediacapabilities is not available } taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to mediacapabilities.decodinginfo() method. this returns a promise that fulfills with information about the media capabilities as to whether the video can be decoded, and whether decoding will be smooth and power efficient. you can also test audio decoding as well as video and audio encoding. creating a video decoding configuration the mediacapabilities.decodinginfo() method takes as a parameter a media decoding configuration. there are very specific ways to go about creating the configuration defined by the mediadecodingconfiguration dictionary. in our e...
...And 7 more matches
SubtleCrypto.sign() - Web APIs
Web › API › SubtleCrypto › sign
nature each time. an extra property, defining the salt length, is passed into the sign() and verify() functions when they are invoked. ecdsa ecdsa (elliptic curve digital signature algorithm) is a variant of the digital signature algorithm, specified in fips-186, that uses elliptic curve cryptography (rfc 6090). ...
...c 6090). hmac the hmac algorithm calculates and verifies hash-based message authentication codes according to the fips 198-1 standard. the digest algorithm to use is specified in the hmackeygenparams object that you pass into generatekey(), or the hmacimportparams object that you pass into importkey(). examples note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new te...
...ches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "rsassa-pkcs1-v1_5", privatekey, encoded ); rsa-pss this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. ...
...And 7 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
the settimeout() method of the windoworworkerglobalscope mixin (and successor to window.settimeout()) sets a timer which executes a function or specified piece of code once the timer expires. syntax var timeoutid = scope.settimeout(function[, delay, arg1, arg2, ...]); var timeoutid = scope.settimeout(function[, delay]); var timeoutid = scope.settimeout(code[, delay]); parameters function a function to be executed after the timer expires. code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. this syntax is not recommended for the same reasons that make using eval() a security risk. delay optional the time, in milliseconds (thousandths of a second), the timer should wait before the specified funct...
...if this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. note that in either case, the actual delay may be longer than intended; see reasons for delays longer than specified below. ...
...ntifies 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 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 ca...
...And 7 more matches
WritableStream.getWriter() - Web APIs
() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...f the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 7 more matches
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...f the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 7 more matches
WritableStreamDefaultWriter.close() - Web APIs
() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...f the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 7 more matches
WritableStreamDefaultWriter.write() - Web APIs
() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
... write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...f the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
...And 7 more matches
perspective-origin - CSS: Cascading Style Sheets
bottom ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage> examples changing the perspective origin this example shows cubes with popular perspective-origin values. ...
...| <length-percentage> ] [ top | center | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage> examples changing the perspective origin this example shows cubes with popular perspective-origin values. ...
...ion><code>perspective-origin: top left;</code></figcaption> <div class="container"> <div class="cube potl"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </div> </div> </figure> <figure> <figcaption><code>perspective-origin: top;</code></figcaption> <div class="container"> <div class="cube potm"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </div> </div> </figure> <figure> <figcaption><code>perspective-or...
...And 7 more matches
Getting Started - Developer guides
necessary functionality. this is where xmlhttprequest comes in. its predecessor originated in internet explorer as an activex object called xmlhttp. then, mozilla, safari, and other browsers followed, implementing an xmlhttprequest object that supported the methods and properties of microsoft's original activex object. meanwhile, microsoft implemented xmlhttprequest as well. // old compatibility code, no longer needed. if (window.xmlhttprequest) { // mozilla, safari, ie7+ ... httprequest = new xmlhttprequest(); } else if (window.activexobject) { // ie 6 and older httprequest = new activexobject("microsoft.xmlhttp"); } note: for illustration purposes, the above is a somewhat simplified version of the code to be used for creating an xmlhttp instance. for a more realistic example, see ...
...ous. if true (the default), javascript execution will continue and the user can interact with the page while the server response has yet to arrive. this is the first a in ajax. the parameter to the send() method can be any data you want to send to the server if post-ing the request. ...
...e a query string: "name=value&anothername="+encodeuricomponent(myvar)+"&so=on" or other formats, like multipart/form-data, json, xml, and so on. note that if you want to post data, you may have to set the mime type of the request. for example, use the following before calling send() for form data sent as a query string: httprequest.setrequestheader('content-type', 'application/x-www-form-urlencoded'); step 2 – handling the server response when you sent the request, you provided the name of a javascript function to handle the response: httprequest.onreadystatechange = nameofthefunction; what should this function do? first, the function needs to check the request's state. if the state has the value of xmlhttprequest.done (corresponding to 4), that means that the full server response ...
...And 7 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
password" or "confirm new password" field, as opposed to a general "enter your current password" field that might be present. this may be used by the browser both to avoid accidentally filling in an existing password and to offer assistance in creating a secure password (see also preventing autofilling with autocomplete="new-password"). "current-password" the user's current password. "one-time-code" a one-time code used for verifying user identity. "organization-title" a job title, or the title a person has within an organization, such as "senior technical writer", "president", or "assistant troop leader". "organization" a company or organization name, such as "acme widget company" or "girl scouts of america". "street-address" a street address. this can be multiple lines of text, and...
...r", "president", or "assistant troop leader". "organization" a company or organization name, such as "acme widget company" or "girl scouts of america". "street-address" a street address. this can be multiple lines of text, and should fully identify the location of the address within its second administrative level (typically a city or town), but should not include the city name, zip or postal code, or country name. "address-line1", "address-line2", "address-line3" each individual line of the street address. these should only be present if the "street-address" is not present. "address-level4" the finest-grained administrative level, in addresses which have four levels. "address-level3" the third administrative level, in addresses with at least three administrative levels. "address-le...
...es with two administrative levels, this would typically be the city, town, village, or other locality in which the address is located. "address-level1" the first administrative level in the address. this is typically the province in which the address is located. in the united states, this would be the state. in switzerland, the canton. in the united kingdom, the post town. "country" a country code. "country-name" a country name. "postal-code" a postal code (in the united states, this is the zip code). "cc-name" the full name as printed on or associated with a payment instrument such as a credit card. using a full name field is preferred, typically, over breaking the name into pieces. "cc-given-name" a given (first) name as given on a payment instrument like a credit card. "cc-addi...
...And 7 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
data, but data is unexpectedly not forthcoming. suspend media data loading has been suspended. timeupdate the time indicated by the currenttime attribute has been updated. volumechange the volume has changed. waiting playback has stopped because of a temporary lack of data usage notes browsers don't all support the same file types and audio codecs; you can provide multiple sources inside nested <source> elements, and the browser will then use the first one it understands: <audio controls> <source src="myaudio.mp3" type="audio/mpeg"> <source src="myaudio.ogg" type="audio/ogg"> <p>your browser doesn't support html5 audio. here is a <a href="myaudio.mp4">link to the audio</a> instead.</p> </audio> we offer a substantive and tho...
...sted <source> elements, and the browser will then use the first one it understands: <audio controls> <source src="myaudio.mp3" type="audio/mpeg"> <source src="myaudio.ogg" type="audio/ogg"> <p>your browser doesn't support html5 audio. here is a <a href="myaudio.mp4">link to the audio</a> instead.</p> </audio> we offer a substantive and thorough guide to media file types and the audio codecs that can be used within them. also available is a guide to the codecs supported for video. other usage notes: if you don't specify the controls attribute, the audio player won't include the browser's default controls. you can, however, create your own custom controls using javascript and the htmlmediaelement api. to allow precise control over your audio content, htmlmediaelements fire many...
...ascript and the htmlmediaelement api. to allow precise control over your audio content, htmlmediaelements fire many different events. this also provides a way to monitor the audio's fetching process so you can watch for errors or detect when enough is available to begin to play or manipulate it. you can also use the web audio api to directly generate and manipulate audio streams from javascript code rather than streaming pre-existing audio files. <audio> elements can't have subtitles or captions associated with them in the same way that <video> elements can. see webvtt and audio by ian devlin for some useful information and workarounds. a good general source of information on using html <audio> is the video and audio content beginner's tutorial. styling with css the <audio> element has ...
...And 7 more matches
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
n the same document. the <datalist> provides a list of predefined values to suggest to the user for this input. any values in the list that are not compatible with the type are not included in the suggested options. the values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ...
...this must be a non-negative integer value smaller than or equal to the value specified by maxlength. if no minlength is specified, or an invalid value is specified, the search input has no minimum length. ...
...teger value 0 or higher. if no maxlength is specified, or an invalid value is specified, the search field has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text entered into the field is greater than maxlength utf-16 code units long. minlength the minimum number of characters (as utf-16 code units) the user can enter into the search field. ...
...And 7 more matches
Expressions and operators - JavaScript
structuring var one = foo[0]; var two = foo[1]; var three = foo[2]; // with destructuring var [one, two, three] = foo; comparison operators a comparison operator compares its operands and returns a logical value based on whether the comparison is true. the operands can be numerical, string, logical, or object values. strings are compared based on standard lexicographical ordering, using unicode values. in most cases, if the two operands are not of the same type, javascript attempts to convert them to an appropriate type for the comparison. this behavior generally results in comparing the operands numerically. the sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. these operators do not attemp...
...is behavior generally results in comparing the operands numerically. the sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. these operators do not attempt to convert the operands to compatible types before checking equality. the following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; comparison operators operator description examples returning true equal (==) returns true if the operands are equal. 3 == var1 "3" == var1 3 == '3' not equal (!=) returns true if the operands are not equal. var1 != 4 var2 != "3" strict equal (===) returns true if the operands are equal and of...
.... thus, when used with boolean values, || returns true if either operand is true; if both are false, returns false. logical not (!) !expr returns false if its single operand that can be converted to true; otherwise, returns true. examples of expressions that can be converted to false are those that evaluate to null, 0, nan, the empty string (""), or undefined. the following code shows examples of the && (logical and) operator. var a1 = true && true; // t && t returns true var a2 = true && false; // t && f returns false var a3 = false && true; // f && t returns false var a4 = false && (3 == 4); // f && f returns false var a5 = 'cat' && 'dog'; // t && t returns dog var a6 = false && 'cat'; // f && t returns false var a7 = 'cat' && false; // t && f re...
...And 7 more matches
URIError: malformed URI sequence - JavaScript
the javascript exception "malformed uri sequence" occurs when uri encoding or decoding wasn't successful. message urierror: the uri to be encoded contains invalid character (edge) urierror: malformed uri sequence (firefox) urierror: uri malformed (chrome) error type urierror what went wrong? ...
... the javascript exception "malformed uri sequence" occurs when uri encoding or decoding wasn't successful. message urierror: the uri to be encoded contains invalid character (edge) urierror: malformed uri sequence (firefox) urierror: uri malformed (chrome) error type urierror what went wrong? ...
... the javascript exception "malformed uri sequence" occurs when uri encoding or decoding wasn't successful. message urierror: the uri to be encoded contains invalid character (edge) urierror: malformed uri sequence (firefox) urierror: uri malformed (chrome) error type urierror what went wrong? ...
...And 7 more matches
Intl - JavaScript
omparison. intl.datetimeformat() constructor for objects that enable language-sensitive date and time formatting. intl.displaynames() constructor for objects that enable the consistent translation of language, region and script display names. intl.listformat() constructor for objects that enable language-sensitive list formatting. intl.locale() constructor for objects that represents a unicode locale identifier. intl.numberformat() constructor for objects that enable language-sensitive number formatting. intl.pluralrules() constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals. intl.relativetimeformat() constructor for objects that enable language-sensitive relative time formatting. static methods intl.getcanonicallocales() r...
...ptions arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the options.localematcher property. locales argument the locales argument requests that a particular locale (or a locale from a list of them) be considered for use in a given operation. ...
... that is a unicode bcp 47 locale identifier. multiple locales may be specified (and a best-supported locale determined by evaluating each of them in order and comparing against the locales supported by the implementation) by passing an array (or array-like object, with a length property and corresponding indexed elements) whose elements are either intl.locale objects or values that convert to unicode bcp 47 locale identifier strings. if the locales argument is not provided or is undefined, the runtime's default locale is used. ...
...And 7 more matches
Promise - JavaScript
the effect is a dynamic replacement. the return causes a promise to be popped, but the nextvalue promise is pushed into its place. for the nesting shown above, suppose the .then() associated with "promise b" returns a nextvalue of "promise x". the resulting nesting would look like this: (promise d, (promise c, (promise x) ) ) a promise can participate in more than one nesting. for the following code, the transiton of promisea into a "settled" state will cause both instances of .then() to be invoked. const promisea = new promise(myexecutorfunc); const promiseb = promisea.then(handlefulfilled1, handlerejected1); const promisec = promisea.then(handlefulfilled2, handlerejected2); an action can be assigned to an already "settled" promise. in that case the action (if appropriate) will be perfor...
...se that is resolved when the original promise is resolved. the handler is called when the promise is settled, whether fulfilled or rejected. examples basic example let myfirstpromise = new promise((resolve, reject) => { // we call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. // in this example, we use settimeout(...) to simulate async code. // in reality, you will probably be using something like xhr or an html5 api. settimeout( function() { resolve("success!") // yay! everything went well! }, 250) }) myfirstpromise.then((successmessage) => { // successmessage is whatever we passed in the resolve(...) function above. // it doesn't have to be a string, but if it is only a succeed message, it probably will be. conso...
... whatever we passed in the resolve(...) function above. // it doesn't have to be a string, but if it is only a succeed message, it probably will be. console.log("yay! " + successmessage) }); example with diverse situations this example shows diverse techniques for using promise capabilities, and diverse situations that can occur. to understand this, start by scrolling to the bottom of the code block, and examine the promise chain. upon provision of an initial promise, a chain of promises can follow. the chain is composed of .then() calls, and typically (but not necessarily) has a single .catch() at the end, optionally followed by .finally(). in this example, the promise chain is initiated by a custom written new promise() construct; but in actual practice, promise chains more typically...
...And 7 more matches
Optimizing startup performance - Web Performance
and when porting an app from another platform to the web. starting up nicely regardless of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. ...
...s of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. that means not running all your startup code in a single event handler on the app's main thread. instead, you should write your code so that your app creates a web worker that does as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken up into small pieces so that the app's event loop continues to cycle while it starts up. this will prevent the app, browser, and/or device from appearing t...
...ssible the user may get an "unresponsive app" or "slow script" notification. you should present some kind of interface, such as a progress bar, so that the user knows how much longer they'll need to wait while your app starts up. where there's a will... if you're starting your project from scratch, it's usually pretty easy to just write everything the "right way," making appropriate bits of the code asynchronous. all pure startup calculations should be performed in background threads, while you keep the run-time of main thread events as short as possible. include a progress indicator so the user knows what's going on and how long they'll be waiting. in theory, anyway, it should be pretty easy to design your new app to start up nicely. on the other hand, however, it can get tricky when you'r...
...And 7 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
a core use-case for webassembly is to take the existing ecosystem of c libraries and allow developers to use them on the web. these libraries often rely on c's standard library, an operating system, a file system and other things. emscripten provides most of these features, although there are some limitations. as an example, let's compile an encoder for webp to wasm. ...
... a core use-case for webassembly is to take the existing ecosystem of c libraries and allow developers to use them on the web. these libraries often rely on c's standard library, an operating system, a file system and other things. emscripten provides most of these features, although there are some limitations. as an example, let's compile an encoder for webp to wasm. ...
...and other things. emscripten provides most of these features, although there are some limitations. as an example, let's compile an encoder for webp to wasm. the source for the webp codec is written in c and available on github as well as some extensive api documentation. that's a pretty good starting point. $ git clone https://github.com/webmproject/libwebp to start off simple, expose webpgetencoderversion() from encode.h to javascript by writing a c file called webp.c: #include "emscripten.h" #include "src/webp/encode.h" emscripten_keepalive int version() { return webpgetencoderversion(); } this is a good simple program to test whether you can get the source code of libwebp to compile, as it doesn't require any parameters or complex data structures to invoke this function. to compile...
...And 7 more matches
base64 - Archive of obsolete content
data encoding and decoding using base64 algorithms. var base64 = require("sdk/base64"); var encodeddata = base64.encode("hello, world"); var decodeddata = base64.decode(encodeddata); globals functions encode(data, charset) creates a base-64 encoded ascii string from a string of binary data. parameters data : string the data to encode charset : string the charset of the string to encode (optional). the only accepted value is "utf-8". in order to encode and decode unicode strings, the charset parameter needs to be set: var base64 = require("sdk/base64"); var encodeddata = base64.encode(unicodestring, "utf-8"); returns string : the encoded string decode(data, charset) decodes a string of data which has been encoded using base-64 encoding. parameters data : string the encod...
... encode and decode unicode strings, the charset parameter needs to be set: var base64 = require("sdk/base64"); var encodeddata = base64.encode(unicodestring, "utf-8"); returns string : the encoded string decode(data, charset) decodes a string of data which has been encoded using base-64 encoding. parameters data : string the encoded data charset : string the charset of the string to encode (optional). the only accepted value is "utf-8". ...
...be set: var base64 = require("sdk/base64"); var encodeddata = base64.encode(unicodestring, "utf-8"); returns string : the encoded string decode(data, charset) decodes a string of data which has been encoded using base-64 encoding. parameters data : string the encoded data charset : string the charset of the string to encode (optional). the only accepted value is "utf-8". ...
...And 6 more matches
widget - Archive of obsolete content
content you need to load a separate script into the panel. in the sdk these scripts are called "content scripts" because they're explicitly used for interacting with web content. while content scripts can access the content they're attached to, they can't use the sdk's apis. so implementing a complete solution usually means you have to send messages between the content script and the main add-on code. you can specify one or more content scripts to load into the widget using the contentscript or contentscriptfile options to the widget() constructor. you can communicate with the script using either the postmessage() api or (preferably, usually) the port api. unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, ...
... you can communicate with the script using either the postmessage() api or (preferably, usually) the port api. unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. for example, suppose we want to implement a media player as an add-on. we could implement the main user interface as a widget hosting an array of buttons to control play/pause/stop functions. we can then use a content script to listen for clicks on those buttons. but because content scripts can't use the sdk's apis, we'll want the content script to...
... and review. for example, suppose we want to implement a media player as an add-on. we could implement the main user interface as a widget hosting an array of buttons to control play/pause/stop functions. we can then use a content script to listen for clicks on those buttons. but because content scripts can't use the sdk's apis, we'll want the content script to send messages to the main add-on code, which can then implement the media player functions using the sdk. the widget's content is specified using html like this: <html> <body> <img src="play.png" id="play-button"> <img src="pause.png" id="pause-button"> <img src="stop.png" id="stop-button"> </body> </html> we just include three icons, and assign an id to each one. this html file, and the icon files it references, a...
...And 6 more matches
Creating Event Targets - Archive of obsolete content
ibes how to consume events: that is, how to listen to events generated by event targets. for example, you can listen to the tabs module's ready event or the panel object's show event. with the sdk, it's also simple to implement your own event targets. this is especially useful if you want to build your own modules, either to organize your add-on better or to enable other developers to reuse your code. if you use the sdk's event framework for your event targets, users of your module can listen for events using the sdk's standard event api. in this tutorial we'll create part of a module to access the browser's places api. it will emit events when the user adds and visits bookmarks, enabling users of the module to listen for these events using the sdk's standard event api. using the places api...
...nt framework for your event targets, users of your module can listen for events using the sdk's standard event api. in this tutorial we'll create part of a module to access the browser's places api. it will emit events when the user adds and visits bookmarks, enabling users of the module to listen for these events using the sdk's standard event api. ...
...s when the user adds and visits bookmarks, enabling users of the module to listen for these events using the sdk's standard event api. using the places api first, let's write some code using places api that logs the uris of bookmarks the user adds. create a new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults. ...
...And 6 more matches
Connecting to Remote Content - Archive of obsolete content
request.open("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode. you can see that an instance of the xmlhttprequest class is created and it holds all functionality for making a request. we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code. following initialization, onload and onerror handlers are registered to a callback function to handle the response returned from the remote server. in both cases aevent.target is an nsixmlhttprequest. in the onload callback function, the responsetext parameter contains the server response as text. if the response is an xml document, the responsexml property will hold an xmldocument object that...
...t! the open method takes two required parameters: the http request method and the url to send the request. the http request method can be "get", "post" or "put". sending a post request requires you to set the content type of the request and to pass the post data to the send() method as below. request.open("post", url, true); request.setrequestheader("content-type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); the third parameter for the open method specifies whether the request should be handled asynchronously or not. in asynchronous mode code execution continues immediately after the send call. in synchronous mode the code and user interface are blocked while waiting for a response to come back. note: requests can take a long time to process and you don't ...
...processed. therefore, it is very important that xmlhttprequest calls are always done asynchronously. now let's look at the most common types of content you can use to communicate with remote servers. json content json is a very lightweight and simple data representation format, similar to the object representation used in javascript. unlike javascript, the json format doesn't allow any kind of code that can be run, only data. json used to be risky in terms of security because the favored way of parsing it was to use the javascript eval function. since eval executes any code contained in the string, workarounds had to be devised in order to close security holes. luckily, firefox now provides a few alternatives for extension developers. the json page explains in detail how to parse json data...
...And 6 more matches
XPCOM Objects - Archive of obsolete content
s is just an identifier, in this case corresponding to the observer service. you'll usually know what string to use by reading examples and documentation. there is no comprehensive list of these (that we know of), and that's understandable since it would be a very long list, and it can be extended by add-ons. if you want to see the list in your current firefox installation, just run the following code in the error console: var str = ""; for (var i in components.classes) { str += i + "\n" }; str a run on firefox 3.6.2 with a few extensions installed yields 876 strings. that's quite a lot. luckily, you'll only need to know a handful of those for extension development. the @mozilla.org/ prefix is just a way to keep things namespaced. we would use something like @xulschool.com/ to make our o...
... 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 keeping things in order. the ns stands for netscape, mozilla's predecessor. the "i" stands for interface. our interfaces should begin with something like xsihello. an interface is just a definition of a set of attributes and methods that an object implementing it shou...
...luded in all xpcom components. this._prefservice = cc["@mozilla.org/preferences-service;1"].getservice(ci.nsiprefbranch); this._prefvalue = this._prefservice.getboolpref("somepreferencename"); this._prefservice.queryinterface(ci.nsiprefbranch2); this._prefservice.addobserver("somepreferencename", this, false); this._prefservice.queryinterface(ci.nsiprefbranch); this is a common piece of code you'll see when initializing components or jsm that rely on preferences. we use the preferences service to get and set preference values, such as the preference value we're getting on the fourth line of code. these methods are in the nsiprefbranch interface. the getservice and createinstance methods allow you to get the component already set to an interface. in many cases you only need to use one...
...And 6 more matches
Reading textual data - Archive of obsolete content
to the default character encoding stored in preferences (intl.charset.default, a localized pref value) when reading from a file, the question is harder to answer. using the system character encoding may work (xxx insert text how to get it), or again the default character encoding from preferences. converting read data if you read data from nsiscriptableinputstream as described on the file i/o code snippets page, you can convert it to utf-8 // sstream is nsiscriptableinputstream var str = sstream.read(4096); var utf8converter = components.classes["@mozilla.org/intl/utf8converterservice;1"]. getservice(components.interfaces.nsiutf8converterservice); var data = utf8converter.converturispectoutf8 (str, "utf-8"); gecko 1.8 and newer reading strings starting with gecko 1.8 (seamonkey 1.
...nterfaces.nsiunicharlineinputstream) { var line = {}; var cont; do { cont = is.readline(line); // now you can do something with line.value } while (cont); } the above example reads an entire stream until eof. see nsiconverterinputstream for nsiconverterinputstream.init() arguments. ...
... // now you can do something with line.value } while (cont); } the above example reads an entire stream until eof. see nsiconverterinputstream for nsiconverterinputstream.init() arguments. earlier versions reading strings earlier versions of gecko do not provide easy ways to read unicode data from a stream. you will have to manually read a block of data and convert it using nsiscriptableunicodeconverter. ...
...And 6 more matches
Tamarin build documentation - Archive of obsolete content
for instructions on tamarin tracing, please see tamarin tracing build documentation. supported platforms tamarin currently supports the following operating systems and/or architectures. windows 32 and 64 bit mac osx 10.4, 10.5 on ppc mac osx 10.5, 10.6 on intel linux 32 and 64 bit solaris 10 on sparc android 2.2 on arm windows mobile 6.5 mips (linux) sh4 (linux) getting the tamarin source the tamarin source resides in mercurial at tamarin central. active development source resides at tamarin redux. ...
...rial can be found here. building tamarin building tamarin will create all the libraries for the avmplus and garbage collector (mmgc), and create a standalone executable (shell) for executing files in the abc file format. running the shell without any arguments will list the available options. note that additional command-line arguments are only available in the debug configuration. the tamarin codebase contains a cross-platform build system for mozilla developers. the cross-platform build system is used for daily automated build testing so it is the most reliable system. the tamarin codebase has the ability to build additional code which supports debugging hooks. in the xcode project, this is the debug_debugger and release_debugger configurations. the flash player builds tamarin with the d...
... cross-platform build (general instructions - non-android) prerequisites: you need python 2.5 or later and gnu make 3.81 or later. ...
...And 6 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
om toolbar button in seamonkey 1.x. (for seamonkey 2, firefox, thunderbird and sunbird, see the page: custom toolbar button) you do not need any special technical skills or tools, and almost all the information you need is on this page. introduction the technique described here does not involve any hacking. instead, you make your custom button as a self-contained extension. you can use the sample code provided here to make buttons that do various useful things. if you know how to program in javascript, then you can write your own code that does other things. you can use this page if all you really want is a button for some special purpose. you can also use this page to learn about extensions, and as a starting point if you plan to write a more complex extension. note that this extension is ver...
......
...8 encoding. to check your text editor, create a plain text file named test.txt. in the file, type some of the special characters that your language uses. save the file. open the file in seamonkey (for example, by dragging it and dropping it in the navigator window, or by choosing file – open file... from seamonkey's menu bar). from seamonkey's menu bar, choose view – character encoding – unicode (utf-8). check that the text you typed looks ok with this setting. if your text editor does not support utf-8, search the internet for a better one that you can download. optional tools you can optionally use any image editor to customize the images. you can optionally use a jar tool or zip tool to package your button as a cross-platform installable (xpi) for other people to install and use. maki...
...And 6 more matches
The Implementation of the Application Object Model - Archive of obsolete content
working on our standards story. forget xul and rdf? we don't need any of this complicated nonsense! just let us go off and make our widgets and build our applications the old-fashioned way! we're still cross-platform, since we'd only have to write widgets like trees and toolbars once! i say, forget this whole thing! let's just ship a product! that would be the unwisest decision of all. ...
...nonsense! just let us go off and make our widgets and build our applications the old-fashioned way! we're still cross-platform, since we'd only have to write widgets like trees and toolbars once! i say, forget this whole thing! let's just ship a product! that would be the unwisest decision of all. why? code bloat. if nglayout's formatting objects aren't used to render the widgetry, then drawing code has to be written for each and every widget. look at the difference between the two tree widgets that exist in nglayout today as an example. the tree widget that is extending the table code has no drawing code, and even by the time it has matched and far outstripped the capabilities of the old gfx-based tree widget, it will still contain no drawing code. individual widgets, even complex widgets l...
...it is a given that nglayout will ship with its own non-native form element widgets. ...
...And 6 more matches
RDF in Mozilla FAQ - Archive of obsolete content
will create an rdf/xml datasource and asynchronously parse it. the datasource will remain "cached" until the last reference to the datasource is released. if the uri argument refers to a built-in datasource, the rdf service will use the xpcom component manager to load a component whose contractid is constructed using the "special" uri and the well-known prefix@mozilla.org/rdf/datasource;1?name=</code>. for example, rdf:foo would load: @mozilla.org/rdf/datasource;1?name=foo as with rdf/xml datasources, a datasource that is retrieved this way is "cached" by the rdf service until the last reference is dropped. how do i create a datasource from an rdf/xml file? you can either create an rdf/xml datasource using the rdf service's getdatasource() method: // get the rdf service var rdf = ...
...rdfservice); // ...and from it, get the datasource. make sure that your web server // dishes it up as text/xml (recommended) or text/rdf! var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // note that ds will load asynchronously, so assertions will not // be immediately available alternatively, you can create one directly using the xpcom component manager, as the following code fragment illustrates: // create an rdf/xml datasource using the xpcom component manager var ds = components .classes["@mozilla.org/rdf/datasource;1?name=xml-datasource"] .createinstance(components.interfaces.nsirdfdatasource); // the nsirdfremotedatasource interface has the interfaces // that we need to setup the datasource. var remote = ds.queryinterface(components.interfaces.nsirdfrem...
...e wasn't loaded, and is loading asynchronously. using this api and javascript's settimeout(), one could set up a polling loop that would continually check the loaded property. this is kludgy, and even worse, won't detect a failed load, for example, if there wasn't any data at the url! for this reason, there is an observer interface that allows you to spy on a datasource's progress. ...
...And 6 more matches
Building up a basic demo with PlayCanvas editor - Game development
creating an account the playcanvas editor is free — all you have to do to begin with is register your account and login: when you first sign up, you are taken straight into the editor and given a simple starter tutorial involving editing a 3d rolling ball game. ...
...ember what this material is for — we will add more later! to change its color we'll use the diffuse option in the entity inspector. click diffuse, then select the colored box next to the color label — it will open a color wheel. from here you can click your desired color or enter it in the bottom text field as a hex value. we've chosen a blue color with a hex value of 0095dd — enter this code in the text field and press return for it to be accepted. note: yes, you read that right — you need to enter the hex value without the hash/pound symbol. now we can apply the colored material to the shape by clicking and dragging its icon from the bottom part of the screen (the little dot on the left hand side of the material's name — it can be a bit fiddly to select; just persevere) on...
...e the below screenshot. animating our scene animating 3d models might be considered an advanced thing to do, but all we want to do is to control a few properties of a given object — we can use a script component to do that. click on the plus button in the assets panel, select the script option, and name your new script file boxanimation.js. ...
...And 6 more matches
Building up a basic demo with Three.js - Game development
to. html structure here's the html structure we will use: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: three.js demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="three.min.js"></script> <script> var width = window.innerwidth; var height = window.innerheight; /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element, that three.js will insert on the page to 100% to fill the entire available viewport space. the first <script> element includes the three.js library in the page, and we will write our example code inside the second. there are two h...
... renderer a renderer is a tool which displays scenes right in your browser. ...
...erer.domelement); we are creating a new webgl renderer, setting its size to fit the whole available space on the screen, and appending the dom structure to the page. you might have noticed the antialias parameter in the first line — this renders the edges of shapes more smoothly. the setclearcolor() method sets our background to a light gray colour, instead of the default black one. add this code into our second <script> element, just below the javascript comment. scene a scene is the place where everything happens. when creating new objects in the demo, we add them all inside the scene to become visible on the screen. in three.js, the scene is represented by a scene object. let's create it, by adding the following line below our previous lines: var scene = new three.scene(); later, ...
...And 6 more matches
Initialize the framework - Game development
« previousnext » this is the first of 16 tutorials to learn how to use gamedev phaser. after completing this tutorial you can find the source code for this section at gamedev-phaser-content-kit/demos/lesson01.html. before we can start writing the game's functionality, we need to create a basic structure to render the game inside. this can be done using html — the phaser framework will generate the required <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element generated by the framework. ...
... the game inside. this can be done using html — the phaser framework will generate the required <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element generated by the framework. ...
...this tutorial uses phaser v2 — it won't work with the current version on phaser (v3). the v2 library is still available on the phaser download page, below the links for the v3 download. go to the phaser download page. choose an option that suits you best — i would recommend...
...And 6 more matches
Web fonts - Learn web development
w you to download custom fonts along with your web page, to allow for more varied, custom text styling. prerequisites: basic computer literacy, html basics (study introduction to html), css basics (study introduction to css), css text and font fundamentals. objective: to learn how to apply web fonts to a web page, using either a third party service, or by writing your own code. font families recap as we looked at in fundamental text and font styling, the fonts applied to your html can be controlled using the font-family property. this takes one or more font family names, and the browser travels down the list until it finds a font it has available on the system it is running on: p { font-family: helvetica, "trebuchet ms", verdana, sans-serif; } this system w...
...ts for decent cross-browser support. for example, most modern browsers support woff/woff2 (web open font format versions 1 and 2), the most efficient format around, but older versions of ie only support eot (embedded open type) fonts, and you might need to include an svg version of the font to support older versions of iphone and android browsers. we'll show you below how to generate the required code. fonts generally aren't free to use. you have to pay for them, and/or follow other license conditions such as crediting the font creator in the code (or on your site). you shouldn't steal fonts and use them without giving proper credit. note: web fonts as a technology have been supported in internet explorer since version 4! you can use the firefox font editor to investigate and manipulate ...
...ctive learning: a web font example with this in mind, let's build up a basic web font example from first principles. it is difficult to demonstrate this using an embedded live example, so instead, we would like you to follow the steps detailed in the below sections, to get an idea of the process. you should use the web-font-start.html and web-font-start.css files as a starting point to add your code to (see the live example). make a copy of these files in a new directory on your computer now. in the web-font-start.css file, you'll find some minimal css to deal with the basic layout and typesetting of the example. finding fonts for this example, we'll use two web fonts, one for the headings, and one for the body text. to start with, we need to find the font files that contain the fonts. fon...
...And 6 more matches
HTML Cheatsheet - Learn web development
while using html it can be very handy to have an easy way to remember how to use html tags properly and how to apply them. mdn provides you with an extended html documentation as well as a deep instructional html how-to. however, in many cases we just need some quick hints as we go. that's the whole purpose of the cheatsheet, to give you some quick accurate ready to use code snippets for common usages. remember that html tags must be used for their semantic, not their appearance. it's always possible to totally change the look and feel of a given tag using css so, when using html, take the time to focus on the meaning rather than the appearance. inline elements an "element" is a single part of a webpage. some elements are large and hold smaller elements like containers. some elements a...
...ler elements like containers. some elements are small and are "nested" inside larger ones. by default, "inline elements" appear next to one another in a webpage. they take up only as much width as they need in a page and fit together horizontally like words in a sentence or books shelved side-by-side in a row.all inline elements can be implemented within the <body></body> tags. ...
... this text is in predefined format. embedded audio <audio controls="controls" src="https://udn.realityripple.com/samples/b7/193cb038d0.mp3">your browse...
...And 6 more matches
JavaScript object basics - Learn web development
ics an object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods when they are inside objects.) let's work through an example to understand what they look like. to begin with, make a local copy of our oojs.html file. ...
...you should get a result similar to one of the below lines: [object object] object { } { } congratulations, you've just created your first object. ...
...the live version will give you a blank screen, but that's ok — again, open your devtools and try typing in the above commands to see the object structure. so what is going on here? well, an object is made up of multiple members, each of which has a name (e.g. name and age above), and a value (e.g. ['bob', 'smith'] and ...
...And 6 more matches
Object-oriented JavaScript for beginners - Learn web development
simplistic, because oop can quickly get very complicated, and giving it a full treatment now would probably confuse more than help. the basic idea of oop is that we use objects to model real world things that we want to represent inside our programs, and/or provide a simple way to access functionality that would otherwise be hard or impossible to make use of. objects can contain related data and code, which represent information about the thing you are trying to model, and functionality or behavior that you want it to have. object data (and often, functions too) can be stored neatly (the official word is encapsulated) inside an object package (which can be given a specific name to refer to, which is sometimes called a namespace), making it easy to structure and access; objects are also common...
...is process of creating an object instance from a class is called instantiation — the object instance is instantiated from the class. specialist classes in this case we don't want generic people — we want teachers and students, which are both more specific types of people. in oop, we can create new classes based on other classes — these new child classes can be made to inherit the data and code features of their parent class, so you can reuse functionality common to all the object types rather than having to duplicate it. where functionality differs between classes, you can define specialized features directly on them as needed. this is really useful — teachers and students share many common features such as name, gender, and age, so it is convenient to only have to define those f...
...cally saying that whenever one of these object instances is created, the object's name property will be equal to the name value passed to the constructor call, and the greeting() method will use the name value passed to the constructor call too. note: a constructor function name usually starts with a capital letter — this convention is used to make constructor functions easier to recognize in code. ...
...And 6 more matches
Handling common accessibility problems - Learn web development
nt. i think it is more interesting than the last one.</p> in addition, your content should make logical sense in its source order — you can always place it where you want using css later on, but you should get the source order right to start with. as a test, you can turn off a site's css and see how understandable it is without it. you could do this manually by just removing the css from your code, but the easiest way is to use browser features, for example: firefox: select view > page style > no style from the main menu. safari: select develop > disable styles from the main menu (to enable the develop menu, choose safari > preferences > advanced > show develop menu in menu bar). chrome: install the web developer toolbar extension, then restart the browser. click the gear icon that wi...
...ccessibility certain html features can be selected using only the keyboard — this is default behavior, available since the early days of the web. the elements that have this capability are the common ones that allow user to interact with web pages, namely links, <button>s, and form elements like <input>. you can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused. you can then press enter/return to follow a focused link or ...
...s-browser video player for some good examples of this. create keyboard shortcuts via javascript, so functionality is activated when you press certain keys on the keyboard. see desktop mouse and keyboard controls for some game-related examples that can be adapted for any purpose. use some interesting tactics to fake button behaviour. take for example our fake-div-buttons.html example (see source code). here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0" (see webaim's tabindex article for more really useful details). this allows us to tab to the buttons, but not to activate them via the enter/return key. to do that, we had to add the following bit of javascript trickery: document.onkeydown = function(e) { if(e.
...And 6 more matches
Introduction to cross browser testing - Learn web development
number of web browsers", we don't mean 100% of the browsers in the world — this is just about impossible. you can make some informed calls as to what browsers and devices your users will be using (as we'll discuss in the second article in the series — see gotta test 'em all?), but you can't guarantee everything. as a web developer, you need to agree on a range of browsers and devices that the code definitely needs to work on with the site owner, but beyond that, you need to code defensively to give other browsers the best chance possible of being able to use your content. this is one of the great challenges of web development. note: we'll cover defensive coding later in the module too. why do cross browser issues occur? there are many different reasons why cross browser issues occur, ...
...ment. note: we'll cover defensive coding later in the module too. why do cross browser issues occur? there are many different reasons why cross browser issues occur, and note that here we are talking about issues where things behave different across different browsers / devices / browsing preferences. before you even get to cross browser issues, you should have already fixed out bugs in your code (see debugging html, debugging css, and what went wrong? troubleshooting javascript from previous topics to refresh your memory if needed). cross browser issues commonly occur because: sometimes browsers have bugs, or implement features differently. this situation is a lot less bad than it used to be; back when ie4 and netscape 4 were competing to be the dominant browser in the 1990s, browser...
...you have to support really old browsers that are no longer being developed, which may have been frozen (i.e. no more new work done on them) a long time before a new feature was even invented. as an example, if you want to use cutting edge javascript features in your site, they might not work in older browsers. if you need to support older browsers, you might have to not use those, or convert your code to old fashioned syntax using some kind of cross-compiler where needed. some devices may have constraints that cause a web site to run slowly, or display badly. for example, if a site has been designed to look nice on a desktop pc, it will probably look tiny and be hard to read on a mobile device. if your site includes a load of big animations, it might be ok on a high spec tablet, but might be ...
...And 6 more matches
Simple Instantbird build
after completing setup for your os, and before you get the source, you can opt to add the progressextension to your mercurial.ini (for windows) or .hgrc (for *nix / mac) file. this will provide status feedback during the lengthy clone / download process. see: configure mercurial .hgrc file for progress extension. get the source note: on windows, you won't be able to build the instantbird source code if it's under a directory with spaces in the path (e.g., don't use "documents and settings"). you can pick any other location, such as a new directory c:\instantbird-src. note: parts of the build process also have problems when the source code is in a directory where the path is long (nested many levels deep). on linux, this can manifest as problems setting up the virtualenv for running tests (f...
...d not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it close to the root of your machine and re-building. ...
...ecause the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it close to the root of your machine and re-building. ...
...And 6 more matches
JavaScript-DOM Prototypes in Mozilla
= div.constructor.prototype non standard no browser is required to provide modifiable __proto__, nor a global node, nor provide any way to get at host objects nor their associated prototypes. if such objects are provided, they are not guaranteed by any specification to have any effect on the environment. results in other browsers is not guaranteed. so how does all this work in the mozilla dom code? it all happens in xpconnect and nsdomclassinfo.{cpp,h} in the dom code. during startup, the nsdomclassinfo code registers two different types of "global names", these are names of properties of the global object with special meaning to the dom code. the two types of "global names" are class constructor names and class prototype names. what's the difference? class constructor names are names of ...
...typeclassproto), the nsscriptnamespacemanager is given the nsiid of the interface that is inherited by the class which the registered name is a prototype of (e.g. ns_get_iid(nsidomnode) for node). nsscriptnamespacemanager also deals with other types of names, but those are unrelated to the dom object prototype setup, so we will ignore those here. ...
...om object prototype setup, so we will ignore those here. once the registration is done, the nsdomclassinfo code uses the registry every time a named property is resolved on a global object (because of this, the nsscriptnamespacemanager needs to be pretty fast at looking things up in its registry; that's why it is a hash table). when a property is resolved on the global object, the nsdomclassinfo code will ask the nsscriptnamespacemanager if the name is a known name (in nswindowsh::globalresolve()), and if the name is known, the code will look at the type of the name and act accordingly. if a class constructor or class prototype name is resolved, the class info code will define the constructor for that class, and also define the prototype property of that constructor (i.e. htmlimageelement.pr...
...And 6 more matches
Application Translation with Mercurial
"de" for german). the localization lead for your language knows the branch. the default localization branch is aurora. next check what is still untranslated by going to localization status page and click on the page for your language. in the section "applications & sign-offs", you will find different products and branches which are currently in translation. ...
... text editor or word processor or any other tool in which you can attach different kind of states to the individual texts to translate. the firefox extension scrapbook is used in this guide. install it into your default firefox profile (you will have more than one profile when following this guide). getting the current texts in english and your locale obtaining the english texts with the source code get the source code by downloading the following file: firefox desktop or firefox for android: download the mozilla-<branch>.hg file (e.g. mozilla-aurora.hg) from https://ftp.mozilla.org/pub/mozilla.org/firefox/bundles/ the file is not small, but after initially downloading it, you only need to download the latest changes in the future. thunderbird, lightning or seamonkey: download the comm-...
...-aurora.hg) from https://ftp.mozilla.org/pub/mozilla.org/firefox/bundles/ the file is not small, but after initially downloading it, you only need to download the latest changes in the future. thunderbird, lightning or seamonkey: download the comm-<branch>.hg file (e.g. comm-aurora.hg) from https://ftp.mozilla.org/pub/mozilla.org/thunderbird/bundles/ in the next step, we will unpack the source code: open an input shell, e.g. by pressing the windows key and r on the keyboard or by calling the "run..." command from the windows "start" button, and then typing cmd and pressing the enter key. launch the installed mozillabuild toolset by launching it with its path, e.g. c:\mozilla\coding\buildtools\mozillabuild\start-shell-msvc2010.bat you can autocomplete the file path after typing a few ch...
...And 6 more matches
Index
oducts, it’s important to be aware of the encoding of the files that you generate. 5 index localization found 42 pages: 6 l10n checks internationalization, localization, localization:tools, tools l10n checks is a python script and library similar to compare-locales. it allows mozilla localizers to easily check their work. 7 l10n testing with xcode firefox for ios, localization once you have your l10n testing environment set up in xcode, testing your firefox on ios localization is a breeze. 8 localization and plurals internationalization, localization you're likely here because you're localizing a .properties file and it had a link to this page. this page is to help explain how to localize these strings so tha...
...rties file and it had a link to this page. this page is to help explain how to localize these strings so that the correct plural form is shown to the user. for example, "1 page" vs "2 pages". 9 localization content best practices apps, extensions, internationalization, localization, mozilla, l10n, l12y this document provides best practices for developers to create localizable code, and describes how to avoid some localizability (l12y) common mistakes. 10 localization notes guide, internationalization, localization, mozilla localizers usually work on the localizable files without the context of the source files including the localized strings; it is important to add comments to the localizable files themselves, too. these comments are generally referre...
... fine, and on windows, mozillabuild should get you everything you need. 12 localization quick start guide guide, translation this guide is filled with all of the basic, technical information you need to get involved in the mozilla l10n program. 13 initial setup localization as a pre-requisite to contributing to the l10n program, you need to have access to code, tools, and a properly configured local environment (i.e., your personal computer). you also need to determine if a localization effort already exists for your locale. here we'll go over the accounts you need as well as the tools and their configurations you need to set up before contributing. 14 qa phase localization after all of your hard work localizing we're sure that you...
...And 6 more matches
Certificate functions
the public functions listed here are used to interact with certificate databases. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
... for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
...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 mxr 3.3 and later cert_comparename mxr 3.2 and later cert_comparevaliditytimes mxr 3.11 and later cert_completecrldecodeentries mxr 3.6 and later cert_convertanddecodecertificate mxr 3.9.3 and later cert_copyname mxr 3.4 and later cert_copyrdn mxr 3.5 and later cert_createava mxr 3.2.1 and later cert_createcertificate mxr 3.5 and later cert_createcertificaterequest mxr 3.2 and later cert_createname mxr 3.2...
...And 6 more matches
Enc Dec MAC Output Public Key as CSR
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...\n", header); pr_fprintf(outfile, "%s\n", buf); pr_fprintf(outfile, "%s\n\n", trailer); return secsuccess; break; default: return secfailure; } pr_fprintf(outfile, "%s\n", header); printasascii(outfile, buf, len); pr_fprintf(outfile, "%s\n\n", trailer); return secsuccess; } /* * initialize for encryption or decryption - common code */ pk11context * cryptinit(pk11symkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(type, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return...
...And 6 more matches
NSS tools : crlutil
defined as follows: -g create new certificate revocation list(crl).- -d delete certificate revocation list from cert database. -i import a crl to the cert database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. -m modify existing crl which can be located in cert db or in arbitrary file. if located in file it should be encoded in asn.1 encode format. -g arguments option arguments modify an action and are lowercase. -b bypass ca signature checks. -p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db). this option is provided as a special case. changing the names of the certificate and key databases is not recommended. -a use ascii format or allow th...
...sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
... crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...And 6 more matches
NSS Tools crlutil
-e erase all crls of specified type from the cert database -l list existing crl located in cert database file. -m modify existing crl which can be located in cert db or in arbitrary file. if located in file it should be encoded in asn.1 encode format. arguments -b bypass ca signature checks. -p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db). this option is provided as a special case. changi...
...issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...And 6 more matches
NSS tools : crlutil
Mozilla › Projects › NSS › tools › crlutil
delete certificate revocation list from cert database. -i import a crl to the cert database -e erase all crls of specified type from the cert database -l list existing crl located in cert database file. -m modify existing crl which can be located in cert db or in arbitrary file. if located in file it should be encoded in asn.1 encode format. -g arguments option arguments modify an action and are lowercase. -b bypass ca signature checks. -p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db). this option is provided as a special case. changing the names of the certificate and k...
...a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...ssuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...And 6 more matches
JSAPI reference
pidermonkey 1.8.1 obsolete since jsapi 16 js_entercrosscompartmentcall added in spidermonkey 1.8.1 obsolete since jsapi 18 js_leavecrosscompartmentcall added in spidermonkey 1.8.1 obsolete since jsapi 18 locale callbacks: struct jslocalecallbacks js_getlocalecallbacks js_setlocalecallbacks locale callback types: jslocaletouppercase jslocaletolowercase jslocalecompare jslocaletounicode scripts just running some javascript code is straightforward: class js::compileoptions added in spidermonkey 17 class js::owningcompileoptions added in spidermonkey 31 class js::readonlycompileoptions added in spidermonkey 31 class js::sourcebufferholder added in spidermonkey 31 js::evaluate added in spidermonkey 17 js_evaluatescript obsolete since jsapi 36 js_evaluateucscript obso...
... class jsscript js::compile added in spidermonkey 17 js::compileoffthread added in spidermonkey 31 js::cancompileoffthread added in spidermonkey 31 js::finishoffthreadscript added in spidermonkey 31 js_compilescript js_compileucscript js_bufferiscompilableunit js_executescript js::cloneandexecutescript added in spidermonkey 31 ...
...8 js_compileucscriptforprincipals obsolete since jsapi 28 js_compilescriptforprincipalsversion obsolete since jsapi 19 js_compileucscriptforprincipalsversion obsolete since jsapi 19 js_getscriptobject obsolete since jsapi 8 js_newscriptobject obsolete since jsapi 8 js_executescriptpart obsolete since javascript 1.9.3 js_destroyscript obsolete since jsapi 8 you can also compile javascript code into a function: struct jsfunction js::compilefunction added in spidermonkey 17 js_decompilefunction js_decompilefunctionbody js_compilefunction obsolete since jsapi 36 js_compilefunctionforprincipals obsolete since jsapi 28 js_compileucfunction obsolete since jsapi 36 js_compileucfunctionforprincipals obsolete since jsapi 28 error handling struct jserrorformatstring added in sp...
...And 6 more matches
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
the current position in the array. enumerators are used to access the elements in an ordered way, without relying on the underlying array type. these enumerators include: nsisimpleenumerator - an enumerator for com objects. nsistringenumerator / nsiutf8stringenumerator - enumerators for strings obsolete arrays / enumerators there are some deprecated classes which should not be used by new code. nsisupportsarray - obsoleted by nsiarray and nsimutablearray, use those instead. nsienumerator - obsoleted by nsisimpleenumerator, use that instead. nsibidirectionalenumerator - obsoleted by nsisimpleenumerator, use that instead. which array should i use? do not use nsisupportsarray; it is deprecated. does your array need to be scriptable? if so, use nsiarray. example: an array a...
...e pointers to instances of the same interface? if so, use nscomarray. example: a content node's list of nsicontent children. otherwise use nsiarray and make liberal use of queryelementat(). the point of nscomarray is that it's a template, and all the pointers in it must be pointers to the same type; it's nice to be able to use it because you get type-safety and don't have to spend time and code qiing (like you have to with nsiarray). array guidelines here are a few simple rules which will keep your code clean and your developers happy: use typesafe arrays like nscomarray<t> nstarray<t> wherever possible. avoid all obsolete arrays and enumerators. avoid creating temporary arrays. scriptable arrays nsiarray / nsimutablearray usage nsiarray is useful if you need to pass arrays...
...cessed list processlist(fooitems); // fooitems will release all its members // when it goes out of scope } access to elements nscomarray<t> is a concrete c++ class, and so the [] operator is used to access its members. when using the [] operator, the reference count is unchanged. this allows direct processing of array elements without worrying about calling release(). for example, this code calls the same method on each member: void notifyobservers(const nscomarray<nsimyobserver>& observers) { // using [] doesn't leak! for (print32 i = observers.count() - 1; i >= 0 ; i--) observers[i]->observe(); } be careful with this though, you could end up with a weak pointer if you're converting from non-nscomarray code. // old version, relied on automatic addref // melements is an ...
...And 6 more matches
Component Internals
tion process. xxx mediawiki...xxx sucks creating components in c++ let's start by examining how xpcom components are written in c++. the most common type of component is one that is written in c++ and compiled into a shared library (a dll on a windows system or a dso on unix). the illustration below shows the basic relationship between the shared library containing the component implementation code you write and the xpcom framework itself. in this diagram, the outer boundary is that of the module, the shared library in which a component is defined. a component in the xpcom framework when you build a component or module and compile it into a library, it must export a single method named nsgetmodule. this nsgetmodule function is the entry point for accessing the library. it gets called du...
...e nsimodule and nsifactory interfaces that control the actual creation of the component, and also the string and xpcom glue parts, which we'll discuss in some detail in the next section (see xpcom glue). these latter supply ease-of-development utilities like smart pointers, generic modules support, and simple string implementations. the largest and possibly most complex part of a component is the code specific to the component itself. but where are the components? components reside in modules, and those modules are defined in shared library files that typically sit in the components directory of an xpcom application. a set of default libraries stored in this components directory makes up a typical gecko installation, providing functionality that consists of networking, layout, composition,...
...ists of networking, layout, composition, a cross-platform user interface, and others. another, even more basic view of this relationship of components to the files and interfaces that define them is shown in onion peel view of xpcom component creation in the next chapter. the component is an abstraction sitting between the actual module in which it is implemented and the objects that its factory code creates for use by clients. xpcom initialization to understand why and when your component library gets called, it is important to understand the xpcom initalization process. when an application starts up, that application may initialize xpcom. the sequence of events that kicks off this xpcom initialization may be triggered by user action or by the application startup itself. a web browser tha...
...And 6 more matches
Using writable streams - Web APIs
ptional, and allows you to specify a custom queueing strategy to use for your stream, which takes the form of an instance of bytelengthqueuingstrategy or countqueuingstrategy. the first object can contain up to four members, all of which are optional: start(controller) — a method that is called once, immediately after the writablestream is constructed. inside this method, you should include code that sets up the stream functionality, e.g. getting access to the underlying sink. write(chunk,controller) — a method that is called repeatedly every time a new chunk is ready to be written to the underlying sink (specified in the chunk parameter). close(controller) — a method that is called if the app signals that it has finished writing chunks to the stream. it should do whatever is neces...
...hod that is called if the app signals that it has finished writing chunks to the stream. it should do whatever is necessary to finalize writes to the underlying sink, and release access to it. abort(reason) — a method that will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. ...
... if the app signals that it has finished writing chunks to the stream. it should do whatever is necessary to finalize writes to the underlying sink, and release access to it. abort(reason) — a method that will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. ...
...And 6 more matches
SubtleCrypto.wrapKey() - Web APIs
r another aes mode such as aes-gcm is that aes-kw does not require an initialization vector. to use aes-kw, the input must be a multiple of 64 bits. aes-kw is specified in rfc 3394. examples note: you can try the working examples out on github. raw wrap this example wraps an aes key. it uses "raw" as the export format and aes-kw, with a password-derived key, to encrypt it. ...
... this example wraps an aes key. it uses "raw" as the export format and aes-kw, with a password-derived key, to encrypt it. see the complete code on github. let salt; /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-kw key using pbkdf2. */ function getkey(keymaterial, salt) { return window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, ...
...crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ) .then((secretkey) => { return wrapcryptokey(secretkey); }) .then((wrappedkey) => { console.log(wrappedkey); }); pkcs #8 wrap this example wraps an rsa private signing key. it uses "pkcs8" as the export format and aes-gcm, with a password-derived key, to encrypt it. ...
...And 6 more matches
A basic 2D WebGL animation example - Web APIs
an be done easily enough by multiplying by a scaling factor that's based on the context's aspect ratio. we'll see that computation shortly. we're also rotating the shape, and we can do that here, by applying a transform. we'll do that first. the rotated position of the vertex is computed by applying the rotation vector, found in the uniform urotationvector, that's been computed by the javascript code. then the final position is computed by multiplying the rotated position by the scaling vector provided by the javascript code in uscalingfactor. the values of z and w are fixed at 0.0 and 1.0, respectively, since we're drawing in 2d. the standard webgl global gl_position is then set to the transformed and rotated vertex's position. fragment shader next comes the fragment shader. its role is ...
...onally simple: <script id="fragment-shader" type="x-shader/x-fragment"> #ifdef gl_es precision highp float; #endif uniform vec4 uglobalcolor; void main() { gl_fragcolor = uglobalcolor; } </script> this starts by specifying the precision of the float type, as required. ...
... let gl = null; let glcanvas = null; // aspect ratio and coordinate system // details let aspectratio; let currentrotation = [0, 1]; let currentscale = [1.0, 1.0]; // vertex information let vertexarray; let vertexbuffer; let vertexnumcomponents; let vertexcount; // rendering data shared with the // scalers. ...
...And 6 more matches
Starting up and shutting down a WebXR session - Web APIs
represents the overall webxr device suite available to you through the hardware and drivers available on the user's equipment. there is a global xrsystem object available for use by your document through the the navigator property xr, which returns the xrsystem object if suitable xr hardware is available for your use given the hardware available and your document's environment. thus the simplest code that fetches the xrsystem object is: const xr = navigator.xr; the value of xr will be null or undefined if webxr isn't available. webxr availability as a new and still in development api, webxr support is limited to specific devices and browsers; and even on those, it may not be enabled by default. there may be options available to allow you to experiment with webxr even if you don't have a c...
...and oculus quest, samsung gear, and google cardboard. with the extension in place, you can open up a developer tools panel that lets you control the position and orientation of the headset and any hand controllers, as well as button presses on the controllers. emulator usage while somewhat awkward compared to using an actual headset, this makes it possible to experiment with and developer webxr code on a desktop computer, where webxr isn't normally available. it also lets you perform some basic testing before taking your code to a real device. be aware, however, that the emulator does not yet completely emulate all of the webxr api, so you may run into problems you're not expecting. again, carefully read the readme file and make sure you're aware of the limitations before you begin. importa...
...bxr isn't normally available. it also lets you perform some basic testing before taking your code to a real device. be aware, however, that the emulator does not yet completely emulate all of the webxr api, so you may run into problems you're not expecting. again, carefully read the readme file and make sure you're aware of the limitations before you begin. important: you should always test your code on actual ar and/or vr hardware before releasing or shipping a product! emulated, simulated, or polyfilled environments are not an adequate substitute for actual testing on physical devices. getting the extension download the webxr api emulator for your supported browser below: google chrome mozilla firefox the source code for the extension is also available on github. emulator issues an...
...And 6 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
're going to be looking at a very simple step sequencer: in practice this is easier to do with a library — the web audio api was built to be built upon. if you are about to embark on building something more complex, tone.js would be a good place to start. however, we want to demonstrate how to build such a demo from first principles, as a learning exercise. note: you can find the source code on github as step-sequencer; see the step-sequencer running live also. the interface consists of master controls, which allow us to play/stop the sequencer, and adjust the bpm (beats per minute) to speed up or slow down the "music". there are four different sounds, or voices, which can be played. each voice has four buttons, which represent four beats in one bar of music. when they are enabled...
...the sounds are based on a dial-up modem. if you are unaware of how one sounds you can listen to one here. creating an audio context as you should be used to by now, each web audio api app star...
...the sounds are based on a dial-up modem. ...
...And 6 more matches
Background audio processing using AudioWorklet - Web APIs
when the web audio api was first introduced to browsers, it included the ability to use javascript code to create custom audio processors that would be invoked to perform real-time audio manipulations. the drawback to scriptprocessornode was simple: it ran on the main thread, thus blocking everything else going on until it completed execution. this was far less than ideal, especially for something that can be as computationally expensive as audio processing. enter audioworklet. an audio context's audio worklet is a worklet which runs off the main thread, executing audio processing code added to it by calling the context's audioworklet.addmodule() method. calling addmodule() loads the specified javascript file, which should contain the implementation of the audio processor. with the processor...
... the process of creating an audio processor using javascript, establishing it as an audio worklet processor, and then using that processor within a web audio application is the topic of this article. ...
... that you wish to configure. these are defined in the audio worklet processor module. connect the created audioworkletnodes into your audio processing pipeline as you would any other node, then use your audio pipeline as usual. throughout the remainder of this article, we'll look at these steps in more detail, with examples (including working examples you can try out on your own). ...
...And 6 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
the setinterval() method, offered on the window and worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. it returns an interval id which uniquely identifies the interval, so you can remove it later by calling clearinterval(). this method is defined by the windoworworkerglobalscope mixin. syntax var intervalid = scope.setinterval(func, [delay, arg1, arg2, ...]); var intervalid = scope.setinterval(function[, delay]); var intervalid = scope.setinterval(code, [delay]); parameters func a function to be executed every delay milliseconds. the function is not passed any arguments, and no return value is expected. ...
...(). this method is defined by the windoworworkerglobalscope mixin. syntax var intervalid = scope.setinterval(func, [delay, arg1, arg2, ...]); var intervalid = scope.setinterval(function[, delay]); var intervalid = scope.setinterval(code, [delay]); parameters func a function to be executed every delay milliseconds. the function is not passed any arguments, and no return value is expected. code an optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. this syntax is not recommended for the same reasons that make using eval() a security risk. delayoptional the time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. see delay restrictions belo...
... 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. ...
...And 6 more matches
Using CSS animations - CSS: Cascading Style Sheets
rgin is set to 0% and the width of the element is set to 100%. this causes the header to finish its animation flush against the left edge of the content area. <p>the caterpillar and alice looked at each other for some time in silence: at last the caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice.</p> note: reload page to see the animation, or click the codepen button to see the animation in the codepen environment. adding another keyframe let’s add another keyframe to the previous example’s animation. let’s say we want the header’s font size to increase as it moves from right to left for a while, then to decrease back to its original size. that’s as simple as adding this keyframe: 75% { font-size: 300%; margin-left: 25%; width:...
...e animation in the codepen environment. adding another keyframe let’s add another keyframe to the previous example’s animation. let’s say we want the header’s font size to increase as it moves from right to left for a while, then to decrease back to its original size. ...
... } } <p>the caterpillar and alice looked at each other for some time in silence: at last the caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice.</p> this tells the browser that 75% of the way through the animation sequence, the header should have its left margin at 25% and the width should be 150%. note: reload page to see the animation, or click the codepen button to see the animation in the codepen environment. making it repeat to make the animation repeat itself, simply use the animation-iteration-count property to indicate how many times to repeat the animation. in this case, let’s use infinite to have the animation repeat indefinitely: p { animation-duration: 3s; animation-name: slidein; animation-iteration-count: infinite; } ...
...And 6 more matches
overflow-wrap - CSS: Cascading Style Sheets
mation typediscrete formal syntax normal | break-word | anywhere examples comparing overflow-wrap, word-break, and hyphens this example compares the results of overflow-wrap, word-break, and hyphens when breaking up a long word. html <p>they say the fishing is excellent at lake <em class="normal">chargoggagoggmanchauggagoggchaubunagungamaugg</em>, though i've never been there myself. ...
...screte formal syntax normal | break-word | anywhere examples comparing overflow-wrap, word-break, and hyphens this example compares the results of overflow-wrap, word-break, and hyphens when breaking up a long word. html <p>they say the fishing is excellent at lake <em class="normal">chargoggagoggmanchauggagoggchaubunagungamaugg</em>, though i've never been there myself. ...
...ak, and hyphens when breaking up a long word. html <p>they say the fishing is excellent at lake <em class="normal">chargoggagoggmanchauggagoggchaubunagungamaugg</em>, though i've never been there myself. (<code>normal</code>)</p> <p>they say the fishing is excellent at lake <em class="ow-anywhere">chargoggagoggmanchauggagoggchaubunagungamaugg</em>, though i've never been there myself. ...
...And 6 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
haracter that isn't valid for the specified number format, then return the number parsed up to that point. however the "+" operator simply converts the string to nan if there is an invalid character contained within it. just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better. strings strings in javascript are sequences of unicode characters. this should be welcome news to anyone who has had to deal with internationalization. more accurately, they are sequences of utf-16 code units; each code unit is represented by a 16-bit number. each unicode character is represented by either 1 or 2 code units. if you want to represent a single character, you just use a string consisting of that single character. to find the length of...
...his should be welcome news to anyone who has had to deal with internationalization. more accurately, they are sequences of utf-16 code units; each code unit is represented by a 16-bit number. each unicode character is represented by either 1 or 2 code units. if you want to represent a single character, you just use a string consisting of that single character. ...
...} return sum; } add(2, 3, 4, 5); // 14 that's really not any more useful than writing 2 + 3 + 4 + 5 though. let's create an averaging function: function avg() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum / arguments.length; } avg(2, 3, 4, 5); // 3.5 this is pretty useful, but it does seem a little verbose. to reduce this code a bit more we can look at substituting the use of the arguments array through rest parameter syntax. in this way, we can pass in any number of arguments into the function while keeping our code minimal. the rest parameter operator is used in function parameter lists with the format: ...variable and it will include within that variable the entire list of uncaptured arguments that the function was ...
...And 6 more matches
Using Promises - JavaScript
ing how to create them. essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. imagine a function, createaudiofileasync(), which asynchronously generates a sound file given a configuration record and two callback functions, one called if the audio file is successfully created, and the other called if an error occurs. ...
...pared to only once at the end of the promise chain: dosomething() .then(result => dosomethingelse(result)) .then(newresult => dothirdthing(newresult)) .then(finalresult => console.log(`got the final result: ${finalresult}`)) .catch(failurecallback); if there's an exception, the browser will look down the chain for .catch() handlers or onrejected. ...
... will look down the chain for .catch() handlers or onrejected. this is very much modeled after how synchronous code works: try { const result = syncdosomething(); const newresult = syncdosomethingelse(result); const finalresult = syncdothirdthing(newresult); console.log(`got the final result: ${finalresult}`); } catch(error) { failurecallback(error); } this symmetry with asynchronous code culminates in the async/await syntactic sugar in ecmascript 2017: async function foo() { try { const result = await dosomething(); const newresult = await dosomethingelse(result); const finalresult = await dothirdthing(newresult); console.log(`got the final result: ${finalresult}`); } catch(error) { failurecallback(error); } } it builds on promises, e.g. dosomething()...
...And 6 more matches
String length - JavaScript
ecmascript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. previously, no maximum length was specified. in firefox, strings have a maximum length of 2**30 - 2 (~1gb). ...
... ecmascript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. previously, no maximum length was specified. in firefox, strings have a maximum length of 2**30 - 2 (~1gb). ...
... ecmascript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. previously, no maximum length was specified. in firefox, strings have a maximum length of 2**30 - 2 (~1gb). ...
...And 6 more matches
Performance fundamentals - Web Performance
ools and processes you can use to test and improve it. what is performance? ultimately, user-perceived performance is the only performance that matters. users provide inputs to the system through touch, movement, and speech. in return, they perceive outputs through sight, touch, and hearing. performance is the quality of system outputs in response to user inputs. all other things being equal, code optimized for some target besides user-perceived performance (hereafter upp) loses when competing against code optimized for upp. users prefer, say, a responsive, smooth app that only processes 1,000 database transactions per second, over a choppy, unresponsive app that processes 100,000,000 per second. of course, it's by no means pointless to optimize other metrics, but real upp targets come fir...
...d so forth. developers draw to canvases using either a familiar 2d drawing api, or webgl, a "close to the metal" binding that mostly follows opengl es 2.0. gecko rendering the gecko javascript engine supports just-in-time (jit) compilation. this enables application logic to perform comparably to other virtual machines — such as java virtual machines — and in some cases even close to "native code". the graphics pipeline in gecko that underpins html, css, and canvas is optimized in several ways. the html/css layout and graphics code in gecko reduces invalidation and repainting for common cases like scrolling; developers get this support "for free". pixel buffers painted by both gecko "automatically" and applications to canvas "manually" minimize copies when being drawn to the display fram...
...tion becomes interactive — for example, users are able to tap a button and the application responds the final event is full load — for example when all the user's albums have been listed in a music player the key to fast startup is to keep two things in mind: upp is all that matters, and there's a "critical path" to each user-perceived event above. ...
...And 6 more matches
page-mod - Archive of obsolete content
ontentscriptfile: data.url("my-script.js") }); var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: [data.url("jquery-1.7.min.js"), data.url("my-script.js")] }); from firefox 34, you can use "./my-script.js" as an alias for self.data.url("my-script.js"). so you can rewrite the above code like this: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: "./my-script.js" }); unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscript...
...od = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: "./my-script.js" }); unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. a page-mod only attaches scripts to documents loaded in tabs. it will not attach scripts to add-on panels, page-workers, sidebars, or firefox hidden windows. to stop a page-mod from making any more modifications, call its destroy() method. the pagemod constructor takes a number of other options to control its behavior: contentstyle li...
...ng messages. to do this, you'll need to listen to the page-mod's attach event. this event is triggered every time the page-mod's content script is attached to a document. the listener is passed a worker object that your add-on can use to send and receive messages. for example, the following add-on retrieves the html content of specific tags from documents that match the pattern. the main add-on code sends the desired tag to the content script, and the content script replies by sending the html content of all the elements with that tag. /lib/main.js: var tag = "p"; var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: data.url("element-getter.js"), onattach: function(worker) { worker.port.emit("g...
...And 5 more matches
Creating annotations - Archive of obsolete content
the annotation text itself. selector page-mod selector content scripts the content script for the selector page-mod uses jquery to examine and manipulate the dom. its main job is to maintain a matched element: this is the page element that is the current candidate for an annotation. the matched element is highlighted and has a click handler bound to it which sends a message to the main add-on code. the selector page mod can be switched on and off using a message from the main add-on code. it is initially off: var matchedelement = null; var originalbgcolor = null; var active = false; function resetmatchedelement() { if (matchedelement) { (matchedelement).css('background-color', originalbgcolor); (matchedelement).unbind('click.annotator'); } } self.on('message', function onme...
...gible if it, or one of its ancestors in the dom tree, has an attribute named "id". the idea here is to make it more likely that the annotator will be able to identify annotated elements correctly later on. if the page element is eligible for annotation, then the selector highlights that element and binds a click handler to it. the click handler sends a message called show back to the main add-on code. the show message contains: the url for the page, the id attribute value, and the text content of the page element. $('*').mouseenter(function() { if (!active || $(this).hasclass('annotated')) { return; } resetmatchedelement(); ancestor = $(this).closest("[id]"); matchedelement = $(this).first(); originalbgcolor = $(matchedelement).css('background-color'); $(matchedelement).css...
...ent).bind('click.annotator', function(event) { event.stoppropagation(); event.preventdefault(); self.port.emit('show', [ document.location.tostring(), $(ancestor).attr("id"), $(matchedelement).text() ] ); }); }); conversely, the add-on resets the matched element on mouseout: $('*').mouseout(function() { resetmatchedelement(); }); save this code in a new file called selector.js in your add-on's data directory. because this code uses jquery, you'll need to download that as well, and save it in data. updating main.js go back to main.js and add the code to create the selector into the main function: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), ...
...And 5 more matches
Unit Testing - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm and followed the tutorial on writing reusable modules. if you're migrating test code from cfx to jpm, see the guide to migrating from cfx, in particular the section on loading modules from test code. the sdk provides a framework to help create and run unit tests for your code. to demonstrate how it works we'll write some unit tests for a simple base64 encoding module. a simple base64 module in a web page, you can perform base64 encoding and decoding using the btoa() and atob() functions. unfortunately these functions are attached to the window object: since this object is not available in your main add-on code, atob() and btoa() aren't available either. so we'll create a base64 module to expose these functions from ...
... so we'll create a base64 module to expose these functions from the platform (see creating reusable modules). to begin with, create a new directory, navigate to it, and run jpm init. ...
...you could download this icon: . ...
...And 5 more matches
Localization - Archive of obsolete content
it doesn't, yet, support localization of css or content scripts, or the add-on's title and description that appear in the add-ons manager. see limitations below. localized strings translated strings are kept in a directory called "locale" under your main add-on directory, one file for each locale. ...
... import the l10n module, and assign its get function to "_" (underscore). wrap all references to localizable strings with the...
...in this scheme a language maps each distinct range of numbers on to one of up to six forms, identified by the following categories: zero, one, two, few, many, and other. english has two forms, whic...
...And 5 more matches
File I/O - Archive of obsolete content
vailable: xpcom/io/nsappdirectoryservicedefs.h, xpcom/io/nsdirectoryservicedefs.h. other such keys as the "profd" key are available; check the known locations. enumerating drives on windows while you can use initwithpath("/") on unix-like systems (linux, mac) to get the root of the file system, there's no such root on windows. however, you can enumerate available drives using the following code: components.utils.import("resource://gre/modules/fileutils.jsm"); var root = new fileutils.file("\\\\."); var drivesenum = root.directoryentries, drives = []; while (drivesenum.hasmoreelements()) { drives.push(drivesenum.getnext(). queryinterface(components.interfaces.nsilocalfile).path); } creating folders fileutils.getdir() can create a folder automatically if it doesn't exist yet: ...
...te that generally you don't need to use nsifile::path. use nsifile directly wherever possible. an example below shows how you should save a path in user prefs. storing nsifile in preferences the following two snippets show the right way to store a file path in user preferences (more about preferences in mozilla): absolute path (nsifile) to store an arbitrary path in user preferences, use this code: // |file| is nsilocalfile. uses services.jsm. // 1. write path to prefs var prefs = services.prefs.getbranch("extensions.myext."); prefs.setcomplexvalue("filename", components.interfaces.nsifile, file); // 2. read path from prefs var file = prefs.getcomplexvalue("filename", components.interfaces.nsilocalfile); relative path (nsirelativefilepref) to store paths relative to one of the predefi...
...rvices.prefs.getbranch("extensions.myext."); prefs.setcomplexvalue("filename", components.interfaces.nsifile, file); // 2. read path from prefs var file = prefs.getcomplexvalue("filename", components.interfaces.nsilocalfile); relative path (nsirelativefilepref) to store paths relative to one of the predefined folders listed above, for example file relative to profile folder, use the following code: // 1. write to prefs var relfile = components.classes["@mozilla.org/pref-relativefile;1"]. createinstance(components.interfaces.nsirelativefilepref); relfile.relativetokey = "profd"; // or any other string listed above relfile.file = file; // |file| is nsilocalfile prefs.setcomplexvalue("filename", components.interfaces.nsirelativefilepref, relfile); // 2. read f...
...And 5 more matches
Displaying web content in an extension without security issues - Archive of obsolete content
one of the most common security issues with extensions is execution of remote code in privileged context. a typical example is an rss reader extension that would take the content of the rss feed (html code), format it nicely and insert into the extension window. the issue that is commonly overlooked here is that the rss feed could contain some malicious javascript code and it would then execute with the privileges of the extension — meaning that it would get full access to the browser (cookies, history etc) and to user’s files. these issues can easily be avoided by making use of the existing security mechanisms in the mozilla codebase. the following article explains these security mechanisms, ideally an extension that needs to display web content (which is always potentially danger...
...s it loads (the "type" attribute is ignored at that point). so if we look at the frame hierarchy there is a boundary between chrome and content, and at that boundary a number of security mechanisms apply. in particular, a content document can only go up in the frame hierarchy until the topmost content document, it cannot access the chrome documents above it. this means for example that javascript code top.location.href = "about:blank" will only unload the content document but won’t have any effect on the chrome. note: this has really nothing to do with the source of the document. if you open "chrome://foo/content/foo.xul" in the browser, it will open as a content document despite having extended privileges. this also means that you won’t be able to establish a security boundary between you...
...restricting what documents that contain untrusted data can do there are several restrictions that can be applied per frame. here it is most important to disable javascript and plugins. it won’t harm disabling everything else as well unless...
...And 5 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
r anything else gecko 17+, such as seamonkey 2.14+). this is two esrs back (as of this writing), which should be plenty. using the current firefox esr, stable version, or nightly is generally a better idea if given the option, but some users take forever to upgrade. there will be no usage of the add-on sdk or any other external libraries here. everything will use apis available in firefox 17+ or code provided here. step 1: use services.jsm if you load one of mozilla's internal jsm files, for example services.jsm, you'll do so via privileged javascript code like this: components.utils.import("resource://gre/modules/services.jsm"); from here on out, it is assumed you've imported services.jsm somewhere at the top of whatever file you're in and will be using it in all code examples. the examp...
...irefox 38, which looked bad, but only because mozilla is still using resource:// uris internally and in examples. resource mappings for files in the mozilla distribution, such as services.jsm (above), will continue to work. in overlay extensions, you can place a resource mapping in the chrome.manifest for your add-on and load your own jsm from resource:// uris. it's a great way to modularize your code that's been available since firefox 3. you can use chrome:// uris with "components.utils.import()" just fine; in fact you've been able to since firefox 4. however, because it was implemented first for only file:// and resource:// but not chrome://, everyone who learned of this new feature learned that you had to load jsm from resource:// uris and just stuck with that forever. it does still work i...
...: no more nsifile access for files internal to your bundle for an extractionless extension, access to files internal to your bundle will not be possible using the nsifile interface. if you need to read data, or otherwise access files within your bundle, there are two options. the first is to use the nsizipreader interface which permits continuing to use nsiinputstreams, etc. the second is to re-code to use xmlhttprequest. a file:// uri to the install location, or .xpi file, is available in installpath property of the bootstrap data structure passed to the startup(), shutdown(), install(), and uninstall() functions in what will be your bootstrap.js file (see below). how to get and load the data of of your add-on's files using the add-on manager api: // this is the old way of getting one of...
...And 5 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
strings the most obvious change required by frozen linkage is using the frozen string api. ...
...strings the most obvious change required by frozen linkage is using the frozen string api. ...
...rator functions instead of a virtual comparator class. unicharutils has been modified to provide a frozen-linkage comparator: nsstring mystring = somestring; - if (mystring.equals(otherstring, nscaseinsensitivestringcomparator())) + if (mystring.equals(otherstring, caseinsensitivecompare)) return ns_ok; // woot, we're equal in all things but case when using unicharutils from frozen-linkage code, link against the unicharutil_external_s static library. the frozen string api doesn't implement the left(), mid(), or right() signatures. use stringhead(), substring(), and stringtail() instead: nsstring buffer = somestring; - nscautostring prefix;- buffer.left(prefix, 4); + const nsdependentsubstring prefix = stringhead(buffer, 4); the frozen string api doesn't use nssubstringtuple objects a...
...And 5 more matches
Signing an extension - Archive of obsolete content
the following instructions also apply to a theme and other xpi files. these instructions assume you're working on mac and you've already got a valid certificate from ca. ...
...low. the certificate which the author purchased from verisign was directly installed to firefox. click the firefox button and select options. in the options window, open the advanced panel, then select the encryption tab. click view certificates. in the certificate manager, select the your certificates tab. select your organization's certificate and click backup. enter the file name, e.g. codesign.p12. enter the password to protect your certificate backup and click ok. a p12 file will be exported on your desktop. create a certificate database first, create a certificate database that will be used for signing. mkdir keystore cd keystore nss-certutil -n -d . you will be asked for the password. use a strong password to protect your database. then cert8.db, key3.db and secmod.db wil...
... and click ok. a p12 file will be exported on your desktop. create a certificate database first, create a certificate database that will be used for signing. mkdir keystore cd keystore nss-certutil -n -d . you will be asked for the password. use a strong password to protect your database. then cert8.db, key3.db and secmod.db will be generated. next, import your certificate. nss-pk12util -i codesign.p12 -d . show the certificate list in your database. nss-certutil -l -d . set the trust for the root and intermediate certificates. here's an example of verisign: nss-certutil -m -n "verisign class 3 public primary certification authority" -t "c,c,c" -d . nss-certutil -m -n "verisign class 3 public primary certification authority - g5 - verisign, inc." -t "c,c,c" -d . nss-certutil -m -n "...
...And 5 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
in two flavors, the file itself and the text name of the file. if the file is dragged and dropped onto a directory, the file flavor will be used. if the file is dropped onto a textbox, the text name flavor will be used. the text is therefore used to insert the name of the file when files can't be dropped directly. a flavor object has a name, which is a formatted like a mime type, such as 'text/unicode'. within the ondragstart function, you specify what flavours are available for the item being dragged. to do this, add data and flavours to the transferdata object, which is the second argument to ondragstart. an example should help here. the ondragstart function adds data to the transferdata object. var textobserver = { ondragstart: function (event, transferdata, action) { var htmltext = ...
...xample should help here. the ondragstart function adds data to the transferdata object. var textobserver = { ondragstart: function (event, transferdata, action) { var htmltext = "<strong>cabbage</strong>"; var plaintext = "cabbage"; transferdata.data = new transferdata(); transferdata.data.adddataforflavour("text/html",htmltext); transferdata.data.adddataforflavour("text/unicode",plaintext); } } here, an observer has been declared and stored in the variable textobserver. it has one property called ondragstart. (in javascript, properties can be declared with the syntax name : value). this property is a function which sets the data that is being dragged. once called, it starts a drag for the string data "cabbage". of course, you would want to calculate this value from t...
...avour will be used and the text will appear bold. otherwise, the plain text version will be used instead. usually you will want to provide a text version of the data so that more applications can accept the data. the order that you define the flavours should be from the best match to the weakest match. ...
...And 5 more matches
Writing textual data - Archive of obsolete content
this article describes how to write textual data to streams, files and sockets in an internationalization-aware way. when writing textual data to an output stream or to a file, you need to pick a character encoding. some character encodings (utf-8, utf-16, utf-32) can represent "all" characters (the full repertoire of unicode) while others can only represent a subset of the full repertoire. when the file is to be read only by the application/extension itself, using utf-8 is often the best choice — it can represent all characters, and ascii characters are represented efficiently. writing to a stream in gecko 1.8 (seamonkey 1.0, firefox 1.5), you can use nsiconverteroutputstream: var charset = "utf-8"; // can be any character encoding name that mozilla supports var os = componen...
... .createinstance(components.interfaces.nsiconverteroutputstream); // this assumes that fos is the nsioutputstream you want to write to os.init(fos, charset, 0, 0x0000); os.writestring("umlaute: \u00fc \u00e4\n"); os.writestring("hebrew: \u05d0 \u05d1\n"); // etc. os.close(); you can also write character arrays using the write function, although using writestring is simpler from javascript code. the example above passes 0 as the third argument, which disables buffering (note: the implementation of the converter stream might not support buffering). passing 0 ensures that data will be immediately written to the underlying stream; however, for better perfomance you should pass a value like 4096 instead. unsupported characters you can specify what should happen with characters that are n...
... that data will be immediately written to the underlying stream; however, for better perfomance you should pass a value like 4096 instead. unsupported characters you can specify what should happen with characters that are not supported by the selected character encoding. the last argument to init specifies that: 0x0000 means that writing unsupported characters throws an exception (with an error code of ns_error_loss_of_significant_data), and no data will be written. to instead write a replacement character in such cases, specify the character instead of 0x00: os.init(fos, charset, 0, "?".charcodeat(0)); you can, of course, replace the "?" in that example with any other character. you can also specify any unicode character u+abcd directly as 0xabcd. note: if the replacement character is ...
...And 5 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
163 instantapply xul attributes, xul reference no summary! 164 inverted xul attributes, xul reference no summary! 165 iscontainer xul attributes, xul reference no summary! 166 isempty xul attributes, xul reference no summary! 167 key xul attributes, xul reference no summary! 168 keycode xul attributes, xul reference no summary! 169 keytext xul attributes, xul reference no summary! 170 label xul attributes, xul reference no summary! 171 label.value xul attributes, xul reference no summary! 172 last-tab xul attributes, xul reference no summary! 173 lastselected xul attribut...
...d-line options add-ons, command line, extensions, guide, xulrunner extensions and xul applications can modify the way command line parameters are handled by writing a component that implements the nsicommandlinehandler interface and registering it in a category. 891 notes no summary! 892 sorting and filtering a custom tree view this is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via javascript. this will not work for other types of trees, for example rdf-backed or ones created with dom methods. 893 style classes xul reference, xul_style_classes no summary! 894 alert-icon xul reference, xul_style_classes no summary! 895 chromeclass-too...
... an element into a xul document, the element is checked to see if it has a datasources attribute. if so, a template builder will be created for the element and attached to the element. if the element is a <tree> element and has the flags attribute set to "dont-build-content", a tree builder will be created. otherwise, a content builder will be created. both types of builder share much of the same code except for how they generate output to be displayed. both types of builders implement the nsixultemplatebuilder interface, while the tree builder also implements the nsixultreebuilder interface.</tree> 946 template logging debugging problems with a template can be difficult as many problems are logic errors that are often not possible to determine automatically. for example,...
...And 5 more matches
Introduction to XUL - Archive of obsolete content
plication ui at all. widgets will have predefined behaviour, set at compilation. buttons will respond to the mouse; toolbars will act as containers for buttons. the effect a widget will have on its application will be defined as a combination of predefined application behaviour and linkage between the widgets. this linkage can be accomplished by including javascript in the xul, or by application code which walks the content model after it has been built from xul, and hooks up event listeners. generally a real application will use some combination of the two. applications, for instance, will have preconceived notions of what to do when they receive an "open file" command. an "open" button is simply a button. it will send its command to the application for processing, generally using some simp...
...ned below. most of the details of writing a xul document are identical to those for writing an xml document, a description of which we will leave to other excellent xml documentation which we assume must exist but have never seen. this document will concentrate on xul-specific features. a word on case and namespaces, and filetypes xml is of course case sensitive. xul is equally so. our current code tends not to be strict about enforcing this, especially for tags and attributes in the html namespace. this will change: tags and attributes will, as a rule, always be lower case as suggested in the xhtml working draft. mozilla gives a special meaning to xul files; it expects to find ui descriptions within. for this reason, we've defined a mime type "text/xul" mapped to files with the extension ...
...echanism at packages, but for now there's a good but somewhat out of date document at configurable chrome available for more information. scripting a xul interface is only a collection of disconnected widgets until it has been programmed. "programming" can be as simple as some javascript to tie the widgets together and perhaps to give them extra functionality, or as complex as application (c++) code which is free to do ... anything. this paper will concentrate on javascript, deeming application programming to be beyond its scope. javascript xul can contain html content, including javascript. javascript functions may be added in a fashion similar to html. there is no <head> section of a xul file, so script is just mixed in with the other content, delimited by a script element in the html na...
...And 5 more matches
Keyboard Shortcuts - Archive of obsolete content
is a solution. the modifier accel refers to the special platform-specific key used for shortcuts. it works just like the other modifiers, but won't be the same on every platform. ...
...a table of the keys is listed below. not all of the keys are available on all keyboards. ...
...a table of the keys is listed below. not all of the keys are available on all keyboards. ...
...And 5 more matches
textbox - Archive of obsolete content
to use of the attribute, as it may need to update additional state. focused type: boolean this attribute is true if the element is focused. emptytext deprecated since gecko 2 type: string a string that appears in the textbox when it has no value. this is superseded by the placeholder attribute in gecko 2.0. the old name is retained for compatibility, but you should update your code. hidespinbuttons type: boolean if true, the number box does not have arrow buttons next to it to allow the user to adjust the value. the value may still be adjusted with the keyboard. the default value is false. increment type: integer the amount by which the curpos (for scroll bars) or value (for number boxes and scale) attribute changes when the arrows are click...
...etofirst paste text up to the first newline, dropping the rest of the text replacewithcommas pastes the text with the newlines replaced with commas replacewithspaces pastes the text with newlines replaced with spaces strip pastes the text with the newlines removed stripsurroundingwhitespace pastes the text with newlines and adjacent whitespace removed onblur type: script code this event is sent when a textbox loses keyboard focus. note: the behavior of this event has evolved over time. prior to gecko 1.9 (firefox 3), the script code would execute in the context of the anonymous html <input> element inside the textbox binding. from gecko 1.9 to gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9), the script code would actually execute twice, once in the conte...
... the context of the anonymous html <input> element inside the textbox binding. from gecko 1.9 to gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9), the script code would actually execute twice, once in the context of the anonymous html <input> element and once in the context of the <textbox> element itself. as of gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10), the script code only runs in the context of the <textbox> element, matching the behavior of all other event handlers. onchange type: script code this event is sent when the value of the textbox is changed. the event is not sent until the focus is moved to another element. onfocus type: script code this event is sent when a textbox receives keyboard focus. note: the behavior of this event has evolve...
...And 5 more matches
Developing cross-browser and cross-platform pages - Archive of obsolete content
reliable approach this approach, still commonly used nowadays, attempts to identify the browser and makes the web author at design time decide what that implies in terms of capabilities of the visiting browser. such approach is fraught with problems and difficulties. it requires from the web author to have knowledge of the capabilities of all current browsers that may visit the page and then to code appropriately for these. it requires from the web author to make assumptions about what will happen with future browsers or to decide to provide future browsers a safe fallback service. it assumes that web authors are able to correctly identify browsers and browser versions in the first place... which is far from being a reliable and easy task to achieve. the browser identification approach reli...
...nd browser versions in the first place... which is far from being a reliable and easy task to achieve. the browser identification approach relies on functions that check the browser type string value and browser version string value and that search for certains characters or sub-strings in the navigator.useragent property string. once "detected", the web author then uses different functions (aka code branching) or points the user to different pages (aka site branching) or web content. site branching can be particularly dangerous as people may enter a page through a link, bookmark, search engine or cache with a "wrong" browser. let's see a basic example of this approach. // bad sample if (navigator.appversion.charat(0) == "8") { if (navigator.appname == "netscape") { isns8 = true; ...
..., bookmark, search engine or cache with a "wrong" browser. let's see a basic example of this approach. ...
...And 5 more matches
The Business Benefits of Web Standards - Archive of obsolete content
om presentation. by locating all the style and design issues in one document - the style sheet - whole sites can be rethemed in one go. the blogging community are particularly dynamic in this respect where on many platforms including wordpress, textpattern and habari, the site theme is a complete and discrete entity in its own right. improved user experience: less bandwidth and fast loads html code is often much more compact (therefore easier to read and maintain) when used in conjunction with css. according to various reports, case studies, and andy king, author of speed up your web site: web site optimization, css has made it possible to transform table-based layouts into css-based layouts. typically this reduces page size by 25 to 50%. this translates into better user experience, accordi...
...ay that standards hugely reduce the concern we need to have for browser differences, they also reduce the differences between the way search engines rank pages. there should be little need to plunge into the increasing costs and uncertain quality and integrity of proprietary pay per click campaigns. increase website traffic maintain contact with your user on multiple platforms standards-based code and cross-platform go hand in hand. while some browsers have quirks that cause different behavior by platform, mozilla-based browsers are designed to behave identically on all supported platforms (mac, linux, unix, windows...) web content is increasingly being accessed by a growing number of user agents other than browsers, or by browsers on different platforms - for example mobile telephones. f...
...this is a very powerful management tool. this is the power of web standards. it supplies a far better development framework, for content providers, for web developers, and for css stylists alike. it is simply not possible for everybody not to gain and share in the huge benefits of standards. customers, developers, digital media creators, can be freed from the tyranny of graphics led development, code generators, and incomprehensible markup. but the real value is at the bottom line. the message to accountants, executives and shareholders alike should be irresistible. benefits of css over javascript specifically, graphics and javascript are often used for special effects on text fragments. as style sheet technology gives designers good typographic control and permits effects such as roll-ov...
...And 5 more matches
Bounce off the walls - Game development
it is nice to see our ball moving, but it quickly disappears from the screen, limiting the fun we can have with it! to overcome that we will implement some very simple collision detection (which will be explained later in more detail) to make the ball bounce off the four edges of the canvas. ...
...ounce off the four edges of the canvas. simple collision detection to detect the collision we will check whether the ball is touching (colliding with) the wall, and if so, we will change the direction of its movement accordingly. to make the calculations easier let's define a variable called ballradius that will hold the radius of the drawn circle and be used for calculations. add this to your code, somewhere below the existing variable declarations: var ballradius = 10; now update the line that draws the ball inside the drawball() function to this: ctx.arc(x, y, ballradius, 0, math.pi*2); bouncing off the top and bottom there are four walls to bounce the ball off — let's focus on the top one first. we need to check, on every frame, whether the ball is touching the top edge of the ca...
...omething like this: if(y + dy < 0) { dy = -dy; } if the y value of the ball position is lower than zero, change the direction of the movement on the y axis by setting it equal to itself, reversed. if the ball was moving upwards with a speed of 2 pixels per frame, now it will be moving "up" with a speed of -2 pixels, which actually equals to moving down at a speed of 2 pixels per frame. ...
...And 5 more matches
Create the Canvas and draw on it - Game development
« previousnext » this is the 1st 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/lesson1.html. before we can start writing the game's functionality, we need to create a basic structure to render the game inside. this can be done using html and the <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element. ...
...the game's functionality, we need to create a basic structure to render the game inside. this can be done using html and the <canvas> element. the game's html the html document structure is quite simple, as the game will be rendered entirely on the <canvas> element. ...
... as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev canvas workshop</title> <style> * { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="mycanvas" width="480" height="320"></canvas> <script> // javascript code goes here </script> </body> </html> we have a charset defined, <title> and some basic css in the header. the body contains <canvas> and <script> elements — we will render the game inside the first one and write the javascript code that controls it in the second one. the <canvas> element has an id of mycanvas to allow us to easily grab a reference to it, and it is 480 pixels wide and 320 pixe...
...And 5 more matches
Move the ball - Game development
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. ...
...ge sprite positions, etc. you can run a function over and over again using a javascript timing function such as setinterval() or requestanimationframe(). delete all the javascript you currently have inside your html file except for the first two lines, and add the following below them. ...
...function draw() { // drawing code } setinterval(draw, 10); thanks to the infinite nature of setinterval the draw() function will be called every 10 milliseconds forever, or until we stop it. now, let's draw the ball — add the following inside your draw() function: ctx.beginpath(); ctx.arc(50, 50, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); try your updated code now — the ball should be repainted on every frame. making it move you won't notice the ball being repainted constantly at the moment, as it's not moving. let's change that. first, instead of a hardcoded position at (50,50) we will define a starting point at the bottom center part of the canvas in variables called x and y, then use those to define the position the circle is drawn at. first, a...
...And 5 more matches
Accessible multimedia - Learn web development
d a large head with lots of sharp teeth."> accessible audio and video controls implementing controls for web-based audio/video shouldn't be a problem, right? let's investigate. the problem with native html5 controls html5 video and audio instances even come with a set of inbuilt controls that allow you to control the media straight out of the box. for example (see native-controls.html source code and live): <audio controls> <source src="viper.mp3" type="audio/mp3"> <source src="viper.ogg" type="audio/ogg"> <p>your browser doesn't support html5 audio. here is a <a href="viper.mp3">link to the audio</a> instead.</p> </audio> <br> <video controls> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html5...
...rols'); doing it this way round rather than just not including the controls attribute in the first place has the advantage that if our javascript fails for any reason, the user still has some controls available. wiring up our buttons first, let's set up the play/pause button. we can get this to toggle between play and pause with a simple conditional function, like the following. ...
...ons first, let's set up the play/pause button. we can get this to toggle between play and pause with a simple conditional function, like the following. ...
...And 5 more matches
Test your skills: HTML accessibility - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html accessibility 1 in this task we will test your understanding of text semantics, and why they are good for accessibility. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html accessibility 1 in this task we will test your understanding of text semantics, and why they are good for accessibility. ...
...n this task we will test your understanding of text semantics, and why they are good for accessibility. the given text is a simple information panel with action buttons, but the html is really bad. we want you to update it use appropriate semantic html. you don't need to worry too much about recreating the exact same look and text sizing, as long as the semantics are good. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html accessibility 2 in the second task, you have a form containing three input fields. you need to: semantically associate the input with their labels. assume that these inputs will be part of a larger form, and wrap them in an element that associates th...
...And 5 more matches
Organizing your CSS - Learn web development
portant. keep it consistent if you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent. consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one method of describing color, or maintaining consistent formatting (for example will you use tabs or spaces to indent your code? if spaces, how many spaces?) having a set of rules you always follow reduces the amount of mental overhead needed when writing css, as some of the decisions are already made. formatting readable css there are a couple of ways you will see css formatted. some developers put all of the rules onto a single line, like so: .box { background-color: #567895; } h2 { background-color: black; color: w...
...when you come back to the project after a break. /* this is a css comment it can be broken onto multiple lines. */ a good tip is to add a block of comments between logical sections in your stylesheet too, to help locate different sections quickly when scanning through, or even give you something to search for to jump right into that part of the css. if you use a string which won't appear in the code you can jump from section to section by searching for it — below we have used ||. /* || general styles */ ... /* || typography */ ... /* || header and main navigation */ ... you don't need to comment every single thing in your css, as much of it will be self-explanatory. what you should comment are the things where you made a particular decision for a reason. you may have used a css p...
...ay — it has entered our understanding as a good way to approach things in general. bem bem stands for block element modifier. in bem a block is a standalone entity such as a button, menu, or logo. an element is something like a list item or a title that is tied to the block it is in. a modifier is a flag on a block or element that changes the styling or behavior. you will be able to recognise code that uses bem due to the extensive use of dashes and underscores in the css classes. for example, look at the classes applied to this html from the page about bem naming conventions: <form class="form form--theme-xmas form--simple"> <input class="form__input" type="text" /> <input class="form__submit form__submit--disabled" type="submit" /> </form> the additional classes are similar...
...And 5 more matches
Test your skills: Selectors - Learn web development
the aim of this task is to help you check your understanding of selectors in css. note: you can try out solutions in the interactive editors below, however, it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. selectors one without changing the html, use css to do the following things: make h1 headings blue. give h2 headings a blue background and white text. ...
...fiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. selectors one without changing the html, use css to do the following things: make h1 headings blue. give h2 headings a blue background and white text. cause text wrapped in a span to have a font-size of 200%. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. selectors two without changing the html, make the following changes to the look of the content in this example: give the element with an id of special a yellow background. give the element with a class of alert a 1...
...l, make the following changes to the look of the content in this example: give the element with an id of special a yellow background. give the element with a class of alert a 1px grey border. if the element with a class of alert also has a class of stop, make the background red. if the element with a class of alert also has a class of go, make the background green. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. selectors three in this example, try making the following changes without adding to the html. style links, making the link-state orange, visited links green, and remove the underline on hover. make the first elemen...
...And 5 more matches
Legacy layout methods - Learn web development
systems" using these legacy methods from time to time. it is worth understanding how they work, and why they are different to css grid layout. this lesson will explain how grid systems and grid frameworks based on floats and flexbox work. having studied grid layout you will probably be surprised how complicated this all seems! this knowledge will be helpful to you if you need to create fallback code for browsers that do not support newer methods, in addition to allowing you to work on existing projects which use these types of systems. it is worth bearing in mind, as we explore these systems, that none of them actually create a grid in the way that css grid layout creates a grid. they work by giving items a size, and pushing them around to line them up in a way that looks like a grid. a tw...
...create a grid in the way that css grid layout creates a grid. they work by giving items a size, and pushing them around to line them up in a way that looks like a grid. a two column layout let's start with the simplest possible example — a two column layout. you can follow along by creating a new index.html file on your computer, filling it with a simple html template, and inserting the below code into it at the appropriate places. at the bottom of the section you can see a live example of what the final code should look like. first of all, we need some content to put into our columns. replace whatever is inside the body currently with the following: <h1>2 column layout example</h1> <div> <h2>first column</h2> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit. nulla luctus ...
...ths — this is quite a good strategy, as it creates a liquid layout, one that adjusts to different screen sizes and keeps the same proportions for the column widths at smaller screen sizes. try adjusting the width of your browser window to see for yourself. this is a valuable tool for responsive web design. note: you can see this example running at 0_two-column-layout.html (see also the source code). 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 5 more matches
Practical positioning examples - Learn web development
cludes information-heavy apps like strategy/war games, mobile versions of websites where the screen is narrow and space is limited, and compact information boxes where you might want to make lots of information available without having it fill the whole ui. ...
...ample will look like this once we are finished: note: you can see the finished example running live at info-box.html (source code). check it out to get an idea of what you will be building in this section of the article. you might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each separate "page" view would actually be a newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger ui design. in addition, so-called "single page apps" are becoming very popular — especially for mobile web uis — because having everything served as a single file cuts down on the number of htt...
...put them below). again, we'll add this class using javascript at the appropriate time. .info-box article { position: absolute; top: 0; left: 0; height: 352px; padding: 10px; color: white; background-color: #a60000; } .info-box .active-panel { z-index: 1; } adding our javascript the final step to getting this feature working is to add some javascript. ...
...And 5 more matches
Fundamental text and font styling - Learn web development
ign 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 also the source code.) color the color property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other 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 ...
...ive names are defined as follows: term definition example serif fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces) my big red elephant sans-serif fonts that don't have serifs. my big red elephant monospace fonts where every character has the same width, typically used in code listings. my big red elephant cursive fonts that are intended to emulate handwriting, with flowing, connected strokes. my big red elephant fantasy fonts that are intended to be decorative. my big red elephant font stacks since you can't guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), yo...
...e would look like this: font: italic normal bold normal 3em/1.5 helvetica, arial, sans-serif; active learning: playing with styling text in this active learning session, we don't have any specific exercises for you to do: we'd just like you to have a good play with some font/text layout properties, and see what you can produce! ...
...And 5 more matches
Test your skills: Links - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...f you also set it so that the subject line of the email is automatically filled in as "question about whales". note: the first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens the page in a new tab. this is not strictly best practice, but we've done it here so that the page doesn't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. links 2 in this task we want you to fill in the four links so that they link to the appropriate places: the first link should link to an image called blue-whale.jpg, which is located in a directory called blue i...
...And 5 more matches
What’s in the head? Metadata in HTML - Learn web development
or news headline, or whatever is appropriate to your usage.) the <title> element is metadata that represents the title of the overall html document (not the document's content.) active learning: inspecting a simple example to start off this active learning, we'd like you to go to our github repo and download a copy of our title-example.html page. to do this, either copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place. press the "raw" button on the github page, which causes the raw code to appear (possibly in a new browser tab). next, choose your browser's file > save page as... menu and choose a sensible place to save the file. now open the file in your browser. you should see something like this: it shou...
...have some fun with it. the <title> element contents are also used in other ways. ...
...have some fun with it. the <title> element contents are also used in other ways. for example, if you try bookmarking the page (bookmarks > bookmark this page or the star icon in the url bar in firefox), you will see the <title> contents filled in as the suggested bookmark name. ...
...And 5 more matches
Image gallery - Learn web development
line editors. if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements inside the html page. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief you have been provided with some html, css and image assets and a few lines of javascript code; you need to write the necessary javascript to turn this into a working program. the html body looks like this: <h1>image gallery example</h1> <div class="full-img"> <img class="displayed-img" src="images/pic1.jpg"> <div class="overlay"></div> <button class="dark">darken</button> </div> <div class="thumb-bar"> </div> the example looks like this: the most interesting parts of the ...
...he thumb-bar <div> so that when they are clicked, the corresponding image is displayed in the displayed-img <img> element. attach an onclick handler to the <button> so that when it is clicked, a darken effect is applied to the full-size image. when it is clicked again, the darken effect is removed again. ...
... in each loop iteration, replace the xxx placeholder value with a string that will equal the path to the image in each case. we are setting the value of the src attribute to this value in each case. ...
...And 5 more matches
Test your skills: Events - Learn web development
this aim of this skill test is to assess whether you've understood our introduction to events article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...ction to events article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). ...
...help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the ...
...And 5 more matches
Test your skills: Functions - Learn web development
this aim of this skill test is to assess whether you've understood our functions — reusable blocks of code, build your own function, and function return values articles. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below r...
...help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript. we haven't explicitly taught this yet in the course, but you'll have seen some examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the ...
... it, and we'd like you to do some research into what dom apis you need to successfully answer the questions. a good starting place is our manipulating documents tutorial. functions 1 for the first task, you have to create a simple function — choosename() — that prints a random name from the provided array (names) to the provided paragraph (para), and then run it once. 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 2 for our second functions-related task, 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 th...
...And 5 more matches
Object building practice - Learn web development
)) + min; return num; } this function takes two numbers as arguments, and returns a random number in the range between the two. modeling a ball in our program our program will feature lots of balls bouncing around the screen. since these balls will all behave in the same way, it makes sense to represent them with an object. let's start by adding the following constructor to the bottom of our code. function ball(x, y, velx, vely, color, size) { this.x = x; this.y = y; this.velx = velx; this.vely = vely; this.color = color; this.size = size; } here we include some parameters that define the properties each ball needs in order to function in our program: x and y coordinates — the horizontal and vertical coordinates where the ball starts on the screen. this can range betwee...
... to specify this in radians). that gives us a complete circle. if you had specified only 1 * pi, you'd get a semi-circle (180 degrees). last of all, we use the fill() method, which basically states "finish drawing the path we started with beginpath(), and fill the area it takes up with the color we specified earlier in fillstyle." you can start testing your object out already. save the code so far, and load the html file in a browser. open the browser's javascript console, and then refresh the page so that the canvas size changes to the smaller visible viewport that remains when the console opens. type in the following to create a new ball instance: let testball = new ball(50, 100, 4, 4, 'blue', 10); try calling its members: testball.x testball.size testball.color testball.
...all instance: let testball = new ball(50, 100, 4, 4, 'blue', 10); try calling its members: testball.x testball.size testball.color testball.draw() when you enter the last line, you should see the ball draw itself somewhere on the canvas. updating the ball's data we can draw the ball in position, but to actually move the ball, we need an update function of some kind. ...
...And 5 more matches
Test your skills: JSON - Learn web development
this aim of this skill test is to assess whether you've understood our working with json article. note: you can try out the solution in the interactive editor below. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the example below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). json 1 the one and only task in this article concerns accessing json data and using it in your page. json data about some mother cats and their kittens is available in sample.json. the json is loaded into the page as a text string and made available in the catstring par...
... details to the kitteninfo variable string. the last mother cat name should have an "and" before it, and a full stop after it. how do you make sure this can work, no matter how many cats are in the json? why are the para1.textcontent = motherinfo; and para2.textcontent = kitteninfo; lines inside the displaycatinfo() function, and not at the end of the script? this has something to do with async code. ...
...iable string. the last mother cat name should have an "and" before it, and a full stop after it. how do you make sure this can work, no matter how many cats are in the json? why are the para1.textcontent = motherinfo; and para2.textcontent = kitteninfo; lines inside the displaycatinfo() function, and not at the end of the script? this has something to do with async code. ...
...And 5 more matches
Test your skills: Object basics - Learn web development
this aim of this skill test is to assess whether you've understood our javascript object basics article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property ...
...he case of the downloadable version). object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property inside the catname variable, using bracket notation. run the greeting() method using dot notation (it will log the greeting to the browser devtools' console). update the color property value to black. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 2 in our next task, we want you to have a go at creating your own object literal to represent one of your favourite bands. the required members are: name: a string representing the band name. nationality: a string representing the country th...
...name of the album. released: a number representing the year the album was released. include at least two albums in the albums array. once you've done this, you should then write a string to the variable bandinfo, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 3 finally for our object basics assessment, we want you to return to the cat object literal from task #1. we want you to rewrite the greeting() method so that it logs "hello, said bertie the cymric." to the browser devtools' console, but in a wa...
...And 5 more matches
Ember interactivity: Events, classes and state - Learn web development
previous overview: client-side javascript frameworks next at this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. along the way, we'll look at using events in ember, creating component classes to contain javascript code to control interactive features, and setting up a service to keep track of the data state of our app. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to learn how to create component...
... are. in the below sections we’ll do this for each component, and then walk you through how the functionality can be implemented. creating todos for our card-header / todo input, we'll want to be able to submit our typed in todo task when we press the enter key and have it appear in the todos list. we want to be able to capture the text typed into the input. we do this so that our javascript code knows what we typed in, and we can save our todo and pass that text along to the todo list component to display. we can capture the keydown event via the on modifier, which is just ember syntactic sugar around addeventlistener and removeeventlistener (see this explanation if needed). add the new line shown below to your header.hbs file: <input class='new-todo' aria-label='what needs to be ...
...e: <input class='new-todo' aria-label='what needs to be done?' placeholder='what needs to be done?' autofocus {{on 'keydown' this.onkeydown}} > this new attribute is inside double curly braces, which tells you it is part of ember's dynamic templating syntax. the first argument passed to on is the type of event to respond to (keydown), and the last argument is the event handler — the code that will run in response to the keydown event firing. as you may expect from dealing with vanilla javascript objects, the this keyword refers to the "context" or "scope" of the component. one component's this will be different from another component's this. we can define what is available inside this by generating a component class to go along with your component. this is a vanilla javascript c...
...And 5 more matches
Strategies for carrying out testing - Learn web development
en doing cross-browser testing, you need to work out a list of browsers you will need to test on to start with. there is no way you can test on every combination of browser and device your users might use to view your site — there are just too many, and new ones appear all the time. instead, you should try to make sure your site works on the most important target browsers and devices, and then code defensively to give your site the widest support reach it can be expected to have. by coding defensively, we mean trying to build in intelligent fallbacks so that if a feature or style doesn't work in a browser, the site will be able to downgrade to something less exciting that still provides an acceptable user experience — the core information is still accessible, for example, even if it does...
... (web) option, and click the sign up button. enter your web site/app details into the signup page. this is fairly intuitive to set up; the most important field to get right is the website url. this needs to be your site/app's root url. once you've finished filling in everything, press the get tracking id button, then accept the terms of service that appear. the next page provides you with some code snippets and other instructions. for a basic website, what you need to do is copy the website tracking code block and paste it into all the different pages you want to track using google analytics on your site. you could place the snippets below your closing </body> tag, or somewhere else appropriate that keeps it from getting muddled up with your application code. upload the changes to the deve...
... that's it! your site should now be ready to start reporting analytics data. ...
...And 5 more matches
Mozilla accessibility architecture
of an object. examples of accessible role constants are role_button, role_checkbox and role_list, although they can have slightly different names and values in each api. in general, the accessibility apis use similar concepts, but use different method, constant and interfaces names. given that there is a fair amount of commonality between accessibility api toolkits, it made sense to write of the code in a cross platform manner, and then deal with the platform differences on a consistent manner. the shared code makes itself available to the toolkit-specific code via generic xpcom interfaces that return information about objects we want to expose. all focusable nodes, tables and text have accessibility interfaces. we call these objects "accessible nodes". each of these accessible nodes supports...
... objects "accessible nodes". each of these accessible nodes supports at minimum the generic cross-platform accessibility interface nsiaccessible (which provides a text name, enumerated role identifier and a set of state flags) and sometimes additional interfaces. for example, tables support nsiaccessibletable, text supports nsiaccessibletext and edit boxes support nsieditabletext., although this code has been moved into the atk specific directories because it is not currently used in windows. we will not rule out the possibility of supporting some of the rich atk interfaces on windows. the toolkit-specific classes then use these xpcom interfaces to gather information about the objects they want to expose, make any necessary changes, and then expose the information using microsoft com on windo...
...h to provide everything the assistive technologies on their platform will need. accessibility api module directory structure general rules for the directory structure: interfaces, both internally-used cross-platform and toolkit-specific interfaces exist in accessible/public. the implementations for each kind of object (document, text, table, edit box, button, etc.) exist in accessible/src. code and interfaces for specific toolkits should go in the appropriate directoy. toolkit specific implementations should have "wrap" appended to the class name. for example, document specific code for each toolkit goes in nsdocaccessiblewrap: public nsdocaccessible. directory purpose accessible/public common interfaces shared by all toolkits ...
...And 5 more matches
Old Thunderbird build
complete the instructions for your os and then continue following these build instructions. to build on windows, please read the prerequisites so you don't skip preparing the mapi headers needed to compile thunderbird. ...
...on linux, this can manifest as problems setting up the virtualenv for running tests (failure to install pip or virtualenv because of os access denied errors, where access is denied not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). ...
...d not because of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it close to the root of your machine and re-building. ...
...And 5 more matches
Simple Thunderbird build
eded. do not copy mapi.h, it is already in c:\program files (x86)\windows kits\10\include\10.0.17134.0\um\mapi.h. as of april 2019, 10.0.17134.0 is needed to compile thunderbird. assuming standard installation locations, copy these 17 files to c:\program files (x86)\windows kits\10\include\10.0.17134.0\shared. ...
...6/2009 17:02 54,395 mapitags.h 02/06/2009 17:02 26,467 mapiutil.h 02/06/2009 17:02 97,301 mapival.h 02/06/2009 17:02 9,334 mapiwin.h 02/06/2009 17:02 1,906 mapiwz.h 02/06/2009 17:02 18,277 mapix.h 02/06/2009 17:02 5,012 mspst.h get the source note: on windows, you won't be able to build the thunderbird source code if it's under a directory with spaces in the path (e.g., don't use "documents and settings"). you can pick any other location, such as a new directory c:/thunderbird-src (where "c:/", with a forward slash, is intentional to clarify you are in the mozillabuild command prompt per windows build prerequisite). note: parts of the build process also have problems when the source code is in a directory...
...ause of permission problems, but because the paths being accessed have been truncated, and so do not exist). having the source deep in a filesystem hierarchy can also cause problems with pymake builds on windows. if you run into seemingly arbitrary problems in building and the source is deeply nested, try moving it closer to the root of your machine and re-building. ...
...And 5 more matches
Performance best practices for Firefox front-end engineers
this guide will help firefox developers working on front-end code produce code which is as performant as possible—not just on its own, but in terms of its impact on other parts of firefox. always keep in mind the side effects your changes may have, from blocking other tasks, to interfering with other user interface elements. avoid the main thread where possible the main thread is where we process user events and do painting. it's also important to note that most of our javascript runs on the main thread, so it's easy for script to cause delays in event processing or painting. that means that the more code we can get off of the main thread, the more that thread can respond to user events, paint, and generally be responsive to the user. you might want to consider using a worker if you need...
... attribute to true by default. by doing so, you cause the binding applied on demand rather than at load time, which makes initial construction of the xul document faster. get familiar with the pipeline that gets pixels to the screen learn how pixels you draw make their way to the screen. knowing the path they will take through the various layers of the browser engine will help you optimize your code to avoid pitfalls. the rendering process goes through the following steps: the above image is used under creative commons attribution 3.0, courtesy of this page from our friends at google, which itself is well worth the read. for a very down-to-earth explanation of the style, layout, paint and composite steps of the pipeline, this hacks blog post does a great job of explaining it. to achi...
... or style information. detecting and avoiding synchronous style flushes what are style flushes? when css is applied to a document (html or xul, it doesn’t matter), the browser does calculations to figure out which css styles will apply to each element. this happens the first time the page loads and the css is initially applied, but can happen again if javascript modifies the dom. javascript code might, for example, change dom node attributes (either directly or by adding or removing classes from elements), and can also add, remove, or delete dom nodes. because styles are normally scoped to the entire document, the cost of doing these style calculations is proportional to the number of dom nodes in the document (and the number of styles being applied). it is expected that over time, scri...
...And 5 more matches
WebRequest.jsm
se this api to implement a content policy in an add-on (for example, an ad or script blocker), as you could using nsicontentpolicy. more generally, you can also use this api instead of http request observers. you can use webrequest.jsm in either the chrome or content processes. the webrequest api is modeled on chrome's webrequest extension api, which makes it easier to write cross-browser add-on code. ...
...can also use this api instead of http request observers. you can use webrequest.jsm in either the chrome or content processes. the webrequest api is modeled on chrome's webrequest extension api, which makes it easier to write cross-browser add-on code. there are some differences between this api and chrome's, though: see chrome incompatibilities for the details. ...
...browser into which the resource will be loaded, or null if the resource will not be loaded into a xul browser. method string the http method to be used (get, post, etc). responseheaders array of http headers. the http response headers that were received. this is only included if you set "responseheaders" in the opt_extrainfospec argument. statuscode number http response code. onresponsestarted triggered once the browser has started to receive the response body. note that you can't pass "blocking" for this event, so you can't modify or cancel the request from this event: it's informational only. opt_extrainfospec values name description "responseheaders" include response headers in the argument pass...
...And 5 more matches
Gecko Profiler FAQ
d by people in preparation for a tutorial session about the gecko profiler. mstange and ehsan tried to respond to some of the questions in advance in writing, and you can find the answers below. is it possible to locate hot spots occurring within a single function? the gecko profiler currently doesn’t have the ability to show you information about line numbers, neither for js code nor for native code. for js code, the profiler platform doesn’t capture any information about lines. it only knows what function was executed and what line this function starts at. for native code, the profiler captures the necessary information but doesn’t have a way to display it. similarly it also can’t show you instruction level information about wher...
... therefore the gecko profiler is not a suitable tool for finding hotspots within a single function. ...
... platform of choice (for example xperf/vtune on windows, instruments on osx, and perf/zoom on linux.) one workaround is to break the hot function into several explicitly-non-inline helpers, recompile, and re-profile. this can change some performance characteristics, but is a decent way to get a sense of which parts of a large function are expensive. how to profile startup code that regresses just a little (<10-15ms ts_paint/tpaint) [mstange] we currently don’t have a good way to do that. you can write your own tools to assist you in this process, though. i did something like this a few years ago with the old profiler and i think something similar would work here: i think there are three main challenges here. you need deterministic profiles tha...
...And 5 more matches
Profiling with the Firefox Profiler
faster by recognizing patterns. also note that you can click on timeline elements (the selected element gets darker when selected) and the tree view (see below) reflects the selected element. 2. call tree the call tree shows the samples organized by 'running time' which will show the data by wall clock time. there are lighter grey names to the right of tree elements that indicate where the code comes from. be aware that elements can be from javascript, gecko, or system libraries. note that if some functions are not yet named properly, symbolication may not yet be finished. tip: you can right-click on a function name to get an option to copy its name to the clipboard. a significant portion of time can be spent in idle, blocking calls like waiting for events. this is ideal for a respo...
...s when a function has 2 or more non-trivial calls: the running time will be split between its children. tip: focus on one section of the tree by clicking on the "arrow-in-a-circle" icon that appears to the right of the tree element as you hover over it. a "tree breadcrumb" will appear similar to the range breadcrumbs noted above. clicking the "javascript only" option will only show javascript code in the call tree. you could compare the time with this option checked and the total time to get an idea of how much time was spent running js. note that long-running js function execution may not actually be taking as long as you think because further down the call stack there may be something like painting happening. clicking the "invert call stack" option will sort by the time spent in a funct...
.....", some of the data may be excluded, click "publish". if you select a different time range, the url revealed by pressing "permalink" will change so that you can be sure the recipient of the url will see the same things you are seeing. tips understanding profiles can be difficult. if you're unfamiliar with gecko's internals, you can click the javascript only button to see where your javascript code is slow. each entry in the call tree shows a call stack and how much time is spent in that call stack. for example:in the results above we can see that we're spending ~287 milliseconds in startup::xre_initchildprocess, 194 ms of which are spent in pvsync::msg_notify and all child functions that it calls. it is useful to scan down the "running time" column and look for when the time changes. while...
...And 5 more matches
Performance
documentation reporting a performance problem a user friendly guide to reporting a performance problem. a development environment is not required. benchmarking tips on generating valid performance metrics. performance best practices in extensions a performance "best practices" guide for extension developers. measuring add-on startup performance a guide for add-on developers on how to set up a performance testing environment. ...
...sing a gpu. scroll-linked effects information on scroll-linked effects, their effect on performance, related tools, and possible mitigation techniques. automated performance testing and sheriffing information on automated performance testing and sheriffing at mozilla. best practices for front-end engineers tips for reducing impacts on browser performance in front-end code. ...
...it also lets you do other memory-related operations like trigger gc and cc, dump gc & cc logs, and dump dmd reports. about:memory is built on top of firefox's memory reporting infrastructure. dmd dmd is a tool that identifies shortcomings in about:memory's measurements, and can also do multiple kinds of general heap profiling. ...
...And 5 more matches
Introduction to NSPR
the netscape portable runtime (nspr) api allows compliant applications to use system facilities such as threads, thread synchronization, i/o, interval timing, atomic operations, and several other low-level services in a platform-independent manner. this chapter introduces key nspr programming concepts and illustrates them with sample code. the current implementation of nspr allows developers to compile a single source code base on macintosh (ppc), win32 (nt 3.51, nt 4.0, win'95), and over twenty versions of unix. nspr does not provide a platform for porting existing code. it must be used from the beginning of a software project. nspr naming conventions naming of nspr types, functions, and macros follows the following conventions: types exported by nspr begin with pr and are followed by...
...ometimes constrained by the underlying operating system. therefore, priorities are not rigidly defined. for more information, see thread scheduling. in general, it's preferable to create local user threads with normal priority and let nspr take care of the details as appropriate for each host os. it's usually not necessary to create a global thread explicitly unless you are planning to port your code only to platforms that provide threading services with which you are familiar or unless the thread will be executing code that might directly call blocking os functions. threads can also have "per-thread-data" attached to them. each thread has a built-in per-thread error number and error string that are updated when nspr operations fail. it's also possible for nspr clients to define their own pe...
...the ready queue for its appropriate priority, then simply running the scheduling algorithm to find the most appropriate thread. the chosen thread may be of higher priority, of the same priority, or even the same thread. it will not be a thread of lower priority. some operating systems cannot be made preemptable (for example, mac os and win 16). this puts them at some risk in supporting arbitrary code, even if the code is interpreted (java). other systems are not thread-aware, and their runtime libraries not thread-safe (most versions of unix). these systems can support local level thread abstractions that can be made preemptable, but run the risk of library corruption (libc). still other operating systems have a native notion of threads, and their libraries are thread-aware and support lockin...
...And 5 more matches
NSS_3.12.1_release_notes.html
grams you also need to download the nspr 4.7.1 binary distributions to get the nspr 4.7.1 header files and shared libraries, which nss 3.12.1 requires. nspr 4.7.1 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.7.1/. new in nss 3.12.1 new functions in the nss shared library: cert_nametoasciiinvertible (see cert.h) convert an certname into its rfc1485 encoded equivalent. returns a string that must be freed with port_free(). caller chooses encoding rules. cert_encodesubjectkeyid (see cert.h) encode certificate skid (subject key id) extension. pk11_getallslotsforcert (see pk11pub.h) pk11_getallslotsforcert returns all the slots that a given certificate exists on, since it's possible for a cert to exist on more than one pkcs#11 token. levels of stan...
...ertt.h) cert_n2a_readable (maximum human readability) cert_n2a_strict (strict rfc compliance) cert_n2a_invertible (maximum invertibility) bugs fixed the following bugs have been fixed in nss 3.12.1. bug 67890: create self-signed cert with existing key that signed csr bug 129303: nss needs to expose interfaces to deal with multiple token sources of certs. ...
...csr bug 129303: nss needs to expose interfaces to deal with multiple token sources of certs. ...
...And 5 more matches
GCIntegration - SpiderMonkey Redirect 1
the spidermonkey garbage collector (gc) will be changing a lot in the future. this page is intended to explain the changes that are happening, with a focus on how they will affect gecko code that uses jsapi. at a high level, there are three issues to be aware of: interactions between the garbage collector and the cycle collector incremental garbage collection moving garbage collection the apis for gc/cc interaction and incremental gc are already in place. development of moving gc (both generational and compacting) is under way, but only in the javascript shell so far. ...
...cremental garbage collection moving garbage collection the apis for gc/cc interaction and incremental gc are already in place. development of moving gc (both generational and compacting) is under way, but only in the javascript shell so far. we're still thinking about how the apis for moving gc should work. overview before digging too deep, here are some quick rules of thumb for how to write code that will work smoothly with the gc regardless of changes that happen in the future. avoid having c++ objects that point to js objects (unless it's just to their own wrapper--that's okay). it's safe for js objects to point to other js objects or to c++ objects. if there is a choice between storing a gc thing inside a c++ object or its js corresponding representation, prefer to store it in the ...
... above, there should be no need for them. this should be obvious by now, but never ever allow a gc thing point to a gc thing in a different compartment unless it's a wrapper that's registered in the cross-compartment wrapper map. now, on to the details... gc/cc interaction <to be done later.> incremental gc incremental gc divides gc marking into time slices. ...
...And 5 more matches
Self-hosted builtins in SpiderMonkey
since firefox 17, spidermonkey has the ability to self-host built-in functions in javascript. these docs describe the current state as of nightly 45. differences from normal javascript all self-hosted code is strict, so self-hosted functions invoked in a null or undefined scope won't be run in the scope of the global object. self-hosted code has access to some functionality that's not available to normal js code. ...
...so instead of receiver.fun(arg1, ..., argn) you have to use callfunction(fun, receiver, arg1, ... argn). ...
...so instead of receiver.fun(arg1, ..., argn) you have to use callfunction(fun, receiver, arg1, ... argn). ...
...And 5 more matches
JIT Optimization Strategies
objects which are global-like in that there is only one instance of them per program. this includes global objects, object literals defined at the top-level of a script, and top-level function objects. this optimization makes the assumption that a property that has not changed after it was first assigned, is likely a constant property. it then directly inlines the value of the property into hot code that accesses it. for example, in the following code: var constants = {}; constants.n = 100; function testarray(array) { for (var i = 0; i < array.length; i++) { if (array[i] > constants.n) return true; } return false; } will have the loop compiled into the following when testarray gets hot. for (var i = 0; i < array.length; i++) { if (array[i] > 100) return true; } w...
...erminable from the object's shape, but the property is not definite (see: getprop_definiteproperty), then this optimization may be used. alternatively, if the property access is polymorphic, but only has a few different shapes observed at the access site, this optimization may be used. this optimization compiles down to one or more shape-guarded direct loads from the object. the following pseudocode describes the kind of machine code generated by this optimization: if obj.shape == shape1 then obj.slots[0] elif obj.shape == shape2 then obj.slots[5] elif obj.shape == shape3 then obj.slots[2] ... end getprop_innerize attempts to optimize a situation where a property access of the form window.prop can be directly translated into a property access on the inner global object. this optim...
...not on the window object. it is useful because accessing global names via the 'window' object is a common idiom in web programming. getprop_inlinecache this is the worst-case scenario for a property access optimization. this strategy is used when all the others fail. the engine simply inserts an inline cache at the property access site. inline caches start off as a jump to a separate piece of code called a "fallback". the fallback calls into the interpreter vm (which is very slow) to perform the operation, and then decides if the operation can be optimized in that particular case. if so, it generates a new "stub" (or freestanding piece of jitcode) and changes the inline cache to jump to the stub. the stub attempts to optimize further occurrences of that same kind of operation. inline cach...
...And 5 more matches
JSAutoByteString
string and free it later. syntax jsautobytestring str; jsautobytestring(jscontext *cx, jsstring *str); name type description cx jscontext * the context in which to add the root. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...ntext * the context in which to add the root. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * a pointer to jsstring to get initial content by calling js_encodestring(cx, str). methods method description void initbytes(char *bytes) take ownership of the given byte array. char *encodelatin1(jscontext *cx, jsstring *str) call js_encodestring and take ownership of the returned string, and return the string. char *encodelatin1(js::exclusivecontext *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. c...
...jscontext *cx, jsstring *str) call js_encodestring and take ownership of the returned string, and return the string. char *encodelatin1(js::exclusivecontext *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. th...
...And 5 more matches
Setting up CDT to work on SpiderMonkey
the full process of and requisites for doing so are described here. ...
...the full process of and requisites for doing so are described here. ...
...the full process of and requisites for doing so are described here. ...
...And 5 more matches
Avoiding leaks in JavaScript XPCOM components
ted to reflect the changes and the cases where they help. take every information on this site with a grain of salt, although most concepts and best practices still apply. using xpcom in javascript (also known as xpconnect) is an environment where memory management issues are not obvious. there are no calls to malloc and free and no reference counting. despite this, it's easy to write javascript code that leaks. it's easy to write leaky code in any garbage-collected language. but it's even easier in this environment because some of the objects you're dealing with are reference-counted behind the scenes. programmers writing and reviewing javascript code in mozilla should understand how code using xpcom in javascript can leak so that they can avoid leaks. this document attempts to help them do...
...bage-collected system the programmer can still create leaks by leaving objects reachable that are no longer needed. for example, if an object's constructor adds the object to a list that is reachable from a global variable and nothing ever removes it from the list, the object will never be destroyed since it is always reachable from the list. memory management in xpcom and javascript javascript code that uses xpcom through xpconnect uses two different memory management models. javascript uses garbage collection. xpcom uses reference counting. authors of javascript code that uses xpcom objects can't depend on all of the benefits of garbage collection. they face some of the disadvantages of reference counting. understanding how memory management works in xpconnect helps understand why this is ...
...els. javascript uses garbage collection. xpcom uses reference counting. authors of javascript code that uses xpcom objects can't depend on all of the benefits of garbage collection. they face some of the disadvantages of reference counting. understanding how memory management works in xpconnect helps understand why this is the case. xpconnect basically provides two features. it allows javascript code to access xpcom objects (i.e., it wraps native xpcom objects for javascript) and it allows javascript code to implement xpcom interfaces (i.e., it wraps javascript objects for xpcom). for javascript objects that implement xpcom interfaces, the interface between reference counting and garbage collection is quite simple. (the implementation is slightly more complicated, but only to optimize for sp...
...And 5 more matches
Using XPCOM Components
components from the interface the mozilla user interface uses javascript that has been given access to xpcom components in the application core with a technology called xpconnect. xpconnect allows interface methods defined via xpidl to be called from javascript, as part of javascript objects that represent instances of components like the cookiemanager. xpconnect is what binds the application code to the user interface of the mozilla browser, to other gecko-based xul, and to javascript environments like xpcshell, which is a command-line javascript interpreter and xpcom tool is built with mozilla. see http://www.mozilla.org/scriptable/ for more information about xpconnect and javascript. this isn't quite all there is to it, of course, but this shows an important aspect of xpcom. the cont...
..., and reuse xpcom components at runtime. and they make it possible to use components written in other languages - such as javascript, python, and others - and to use c++-based xpcom components from these other languages as well. in the mozilla browser, components are used as often from javascript in the interface as they are from c++ or any other language. in fact, a search of the mozilla source code reveals that this cookiemanager component is called only from javascript. we'll be using this component from javascript ourselves as part of this tutorial[cookie-manager-in-tutorial]. javascript and mozilla javascript is the lingua franca of the mozilla browser front-end, and the bindings between it and xpcom are strong and well-defined. scriptability, this ability to get and use xpcom compone...
... attempts to provide reference information for xpcom components and their interfaces that are frozen as of the time of this writing. the mozilla embedding project tracks the currently frozen interfaces. ...
...And 5 more matches
nsIContentViewer
void loadcomplete(in unsigned long astatus); void loadstart(in nsisupports adoc); void move(in long ax, in long ay); void open(in nsisupports astate, in nsishentry ashentry)...
...oryentry(); void close(in nsishentry historyentry); void destroy(); [noscript,notxpcom,nostdcall] nsiviewptr findcontainerview(); void getbounds(in nsintrectref abounds); native code only! [noscript,notxpcom] nsidocumentptr getdocument(); void hide(); void init(in nsiwidgetptr aparentwidget, [const] in nsintrectref abounds); native code only! void loadcomplete(in unsigned long astatus); void loadstart(in nsisupports adoc); void move(in long ax, in long ay); void open(in nsisupports astate, in nsishentry ashentry); void pagehide(in boolean isunload); boolean permitunload([optional] in boolean acallercloseswindow); boolean requestwindowclose(); void resetclo...
... [noscript,notxpcom,nostdcall] void setnavigationtiming(in nsdomnavigationtimingptr atiming); void setpagemode(in boolean apagemode, in nsiprintsettings aprintsettings); void show(); void stop(); void unload(); obsolete since gec...
...And 5 more matches
nsIDBFolderInfo
obsolete since gecko 1.8 astring getproperty(in string propertyname); nsidbfolderinfo gettransferinfo(); unsigned long getuint32property(in string propertyname, in unsigned long defaultvalue); void initfromtransferinfo(in nsidbf...
...oolean overriden); void getcharactersetoverride(out boolean charactersetoverride); obsolete since gecko 1.8 string getcharptrcharacterset(); string getcharptrproperty(in string propertyname); void getlocale(in nsstring result); native code only! obsolete since gecko 1.8 void getmailboxname(in nsstring boxname); native code only! obsolete since gecko 1.8 astring getproperty(in string propertyname); nsidbfolderinfo gettransferinfo(); unsigned long getuint32property(in string propertyname, in unsigned long defaultvalue); void initfromtransferinfo(in nsidbfolderinfo transferinfo); long orflags(in long flags); void setboolean...
...obsolete since gecko 1.8 void setproperty(in string propertyname, in astring propertystr); void setuint32property(in string propertyname, in unsigned long propertyvalue); attributes attribute type description ...
...And 5 more matches
nsIEditorIMESupport
editor/idl/nsieditorimesupport.idlscriptable please add a summary to this article. ...
... please add a summary to this article. ...
...ecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void begincomposition(in nstexteventreplyptr areply); native code only! obsolete since gecko 2.0 void endcomposition(); obsolete since gecko 2.0 void forcecompositionend(); void getpreferredimestate(out unsigned long astate); native code only! void getquerycaretrect(in nsquerycaretrecteventreplyptr areply); native code only! obsolete since gecko 1.9.1 void getreconversionstring(in nsreconversioneventreplyptr areply); native code only! obsolete since gecko 1.9.1 void notifyimeonblur(); obsolete since gecko 1.9.1 void notifyimeonfocus(); obsolete since gecko 1.9.1 void querycomposition(in nstexteventreplyptr areply); native code only! obsolete since gecko 2.0 void setcompositionstring(in domstring ac...
...And 5 more matches
Standard OS Libraries
(for linux) file with c functions that can be called from your add-on with js-ctypes. the dll/so/etc file you make must be shipped with your add-on. standard libraries offer the advantage of not having to ship anything. they are already available on the operating system for you. you just need to supply the path to appropriate files and set up the proper types of values/arguments in the js-ctypes code. this article allows you to find out what types to give to values/arguments by supplying links to the documentation of the os libraries. windows windows has many standard os libraries. the most common, found on all windows os version, is "winapi". windows also has the "winapilists" and ".net framework" (i'm not sure if it can be accessed jsctypes but probably). a complete list of windows apis c...
...re "bsd" because this means the bsd family such as freebsd, openbsd (who by the way made ssh), netbsd, etc. gtk+ and qt are graphic frameworks, the graphic stack under unix is xorg (x11/x). gtk+ builds over x11. xorg is being re-written at the moment, it is known as wayland. wayland is not considered stable, but it's supposed to replace xorg in the long term. gtk+ and qt have begun porting their code to wayland. as wayland is not out yet in the wild this article does not focus on wayland, it will focus on gtk+ and xorg(x11/x). gdk is a stack under gtk+. gtk+ is the toolkit to build apps, gdk is more low-level. to be precise, x is "just" like a display machine. on top of which everybody uses "window managers" (known as "wm"s) such as fluxbox, i3, awesome, openbox, mutter (used by gnome 3), p...
.... xcb is thread safe. resources for xcb github :: noitidart - ostypes / ostypes_x11.jsm - some method and type signatures xcb freedesktop :: xproto.h mac os x mac os x has two categories of c-based api (carbon, core foundation) and objective-c based api (cocoa). note: you cannot use carbon routines from your add-on; firefox is a 64-bit application, and you cannot use carbon from 64-bit code. core foundation to learn about all the mac os x apis and which library file you will need to call, go to the mac developer library website and find the function, then scroll down to "declared in" section, and find which framework contains the header file. the coregraphics framework is based on corefoundation framework, including coregraphics etc. the release, string, etc. comes from corefoun...
...And 5 more matches
Browser Console - Firefox Developer Tools
the browser console is like the web console, but applied to the whole browser rather than a single content tab. so it logs the same sorts of information as the web console - network requests, javascript, css, and security errors and warnings, and messages explicitly logged by javascript code. however, rather than logging this information for a single content tab, it logs information for all content tabs, for add-ons, and for the browser's own code. ...
...e web console - network requests, javascript, css, and security errors and warnings, and messages explicitly logged by javascript code. however, rather than logging this information for a single content tab, it logs information for all content tabs, for add-ons, and for the browser's own code. if you also want to use the other web developer tools in the regular web toolbox with add-on or browser code, consider using the browser toolbox. similarly, you can execute javascript expressions using the browser console. but while the web console executes code in the page window scope, the browser console executes them in the scope of the browser's chrome window. this means you can interact with all the browser's tabs using the gbrowser global, and even with the xul used to specify the browser's user...
...d 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 explicitly logged by javascript code using the console api). input/output messages: commands send to the browser via the command line, and the result of executing them. however, it displays such messages from: web content hosted by all browser tabs the browser's own code add-ons. messages from add-ons the browser console displays messages logged by all firefox add-ons. console.jsm to use the console api from a tradition...
...And 5 more matches
AddressErrors - Web APIs
contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. phone a domstring which, if present, indicates that the phone property of the paymentaddress could not be validated. the contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. postalcode a domstring which, if present, indicates that the postalcode property of the paymentaddress could not be validated. the contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. recipient a domstring which, if present, indicates that the recipient property of the paymentaddress could not be validated. the contents of ...
...ntents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. region a domstring which, if present, indicates that the region property of the paymentaddress could not be validated. the contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. regioncode a domstring which, if present, indicates that the regioncode property of the paymentaddress could not be validated. the contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. sortingcode a domstring which, if present, indicates that the sortingcode property of the paymentaddress could not be validated. the contents...
...the contents of the string provide a human-readable explanation of the validation failure, and ideally suggestions to correct the problem. usage notes keep in mind that some violation errors may be outside the ability of the user to fix. ...
...And 5 more matches
CSSStyleSheet.insertRule() - Web APIs
e document (it may be better practice * to dynamically change classes, so style information can be kept in * genuine stylesheets and avoid adding extra elements to the dom). * note that an array is needed for declarations and rules since ecmascript does * not guarantee a predictable object iteration order, and since css is * order-dependent. ...
...e sending the arguments to the default native insertrule(). ...
...tive insertrule(). ...
...And 5 more matches
Cache - Web APIs
Web › API › Cache
oth a request and its response and adds it to the given cache. cache.delete(request, options) finds the cache entry whose key is the request, returning a promise that resolves to true if a matching cache entry is found and deleted. if no cache entry is found, the promise resolves to false. cache.keys(request, options) returns a promise that resolves to an array of cache keys. ...
...ds the cache entry whose key is the request, returning a promise that resolves to true if a matching cache entry is found and deleted. if no cache entry is found, the promise resolves to false. cache.keys(request, options) returns a promise that resolves to an array of cache keys. examples this code snippet is from the service worker selective caching sample. ...
... is found and deleted. if no cache entry is found, the promise resolves to false. cache.keys(request, options) returns a promise that resolves to an array of cache keys. examples this code snippet is from the service worker selective caching sample. (see selective caching live) the code uses cachestorage.open() to open any cache objects with a content-type header that starts with font/. the code then uses cache.match() to see if there's already a matching font in the cache, and if so, returns it. if there isn't a matching font, the code fetches the font from the network and uses cache.put() to cache the fetched resource. the code handles exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an exception. it will return a normal respo...
...And 5 more matches
Basic animations - Web APIs
t(function, delay) executes the function specified by function in delay milliseconds. requestanimationframe(callback) tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. if you don't want any user interaction you can use the setinterval() function which repeatedly executes the supplied code. if we wanted to make a game, we could use keyboard or mouse events to control the animation and use settimeout(). by setting eventlisteners, we catch any user interaction and execute our animation functions. in the examples below, we'll use the window.requestanimationframe() method to control the animation. the requestanimationframe method provides a smoother and more efficient way for animati...
... if (x > (canvasxsize-imgw)) { ctx.drawimage(img, x - imgw + 1, y, imgw, imgh); } } // draw image ctx.drawimage(img, x, y,imgw, imgh); // amount to move x += dx; } below is the <canvas> in which the image is scrolled. note that the width and height specified here must match the values of the canvasxzsize and canvasysize variables in the javascript code. <canvas id="canvas" width="800" height="200"></canvas> mouse following animation <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>document</title> <script> var cn; //= document.ge...
..."arrowright" : "arrowdown" } }), object.defineproperty(e, "which", { get: functio...
...And 5 more matches
Binary strings - Web APIs
Web › API › DOMString › Binary
its purpose however is not to represent characters, but binary data. ...
...its purpose however is not to represent characters, but binary data. ...
...its purpose however is not to represent characters, but binary data. ...
...And 5 more matches
Transcoding assets for Media Source Extensions - Web APIs
when working with media source extensions, it is likely that you need to condition your assets before you can stream them. this article takes you through the requirements and shows you a toolchain you can use to encode your assets appropriately. getting started the first and most important step is to ensure that your files are comprised of a container and codec that users' browsers support. depending on the codec, you might need to fragment the file to comply with the iso bmff spec. (optional) if you decide to use dynamic adaptive streaming over http (dash) for adaptive bitrate streaming, you need to transcode your assets into multiple resolutions. most dash clients expect a corresponding media presentation description (mpd) manifest file, which is typically generated while gener...
...rectory in the same place as ffmpeg. python2 — bento4 uses it. get these installed successfully before moving to the next step. sample media should be placed in the bento4 utils directory and worked here. note: the prebuilt ffmpeg does not include libfdk_aac due to licensing reasons. bento4 uses this by default, so you need to compile ffmpeg if necessary. if you don't need it, add --audio-codec=aac to the mp4-dash-encode.py command line. container and codec support as specified in section 1.1 of the mse spec: goals, mse is designed not to require support for any particular media format or codec. while this is true on paper, browser support varies for specific container/codec combinations. to check if the browser supports a particular container, you can pass a string of the mime ty...
...edia format or codec. while this is true on paper, browser support varies for specific container/codec combinations. to check if the browser supports a particular container, you can pass a string of the mime type to the mediasource.istypesupported method: mediasource.istypesupported('audio/mp3'); // false mediasource.istypesupported('video/mp4'); // true mediasource.istypesupported('video/mp4; codecs="avc1.4d4028, mp4a.40.2"'); // true the string is the mime type of the container, optionally followed by a list of codecs. while the mime type is fairly simple to figure out, we can get the codec string using the mp4info utility. currently, mp4 containers with h.264 video and aac audio codecs have support across all modern browsers, while others don't. to convert our sample media from a quic...
...And 5 more matches
PerformanceResourceTiming.transferSize - Web APIs
er representing the size (in octets) of the fetched resource. the size includes the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. ...
...hed resource. the size includes the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. ...
...the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. ...
...And 5 more matches
SVGTransformList - Web APIs
scription numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgtransform newitem) svgtransform clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from it...
...clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgtransform returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. ...
... the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgtransform returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list befo...
...And 5 more matches
Adding 2D content to a WebGL context - Web APIs
this project uses the glmatrix library to perform its matrix operations, so you will need to include that in your project. we're loading a copy from a cdn in our html's <head>. ...
... this project uses the glmatrix library to perform its matrix operations, so you will need to include that in your project. we're loading a copy from a cdn in our html's <head>. ...
...gram, written using the opengl es shading language (glsl), that takes information about the vertices that make up a shape and generates the data needed to render the pixels onto the screen: namely, the positions of the pixels and their colors. there are two shader functions run when drawing webgl content: the vertex shader and the fragment shader. you write these in glsl and pass the text of the code into webgl to be compiled for execution on the gpu. together, a set of vertex and fragment shaders is called a shader program. let's take a quick look at the two types of shader, with the example in mind of drawing a 2d shape into the webgl context. vertex shader each time a shape is rendered, the vertex shader is run for each vertex in the shape. its job is to transform the input vertex from ...
...And 5 more matches
Using textures in WebGL - Web APIs
« previousnext » now that our sample program has a rotating 3d cube, let's map a texture onto it instead of having its faces be solid colors. 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>. loading textures the first thing to do is add code to load the textures. in our case, we'll be using a single texture, mapped onto all six sides of our rotating cube, but the same technique can be used for any number of textures. note: it's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has cors approval. see cross-domain textures be...
...ad the textures. in our case, we'll be using a single texture, mapped onto all six sides of our rotating cube, but the same technique can be used for any number of textures. note: it's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has cors approval. see cross-domain textures below for details. the code that loads the texture looks like this: // // initialize a texture and load an image. // when the image finished loading copy it into the texture. // function loadtexture(gl, url) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because images have to be download over the internet // they might take a moment until they are ready. // until then put a sin...
...r main() function. this can be added after the initbuffers(gl) call. // load texture const texture = loadtexture(gl, 'cubetexture.png'); mapping the texture onto the faces at this point, the texture is loaded and ready to use. but before we can use it, we need to establish the mapping of the texture coordinates to the vertices of the faces of our cube. this replaces all the previously existing code for configuring colors for each of the cube's faces in initbuffers(). const texturecoordbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, texturecoordbuffer); const texturecoordinates = [ // front 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // back 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // top 0.0, 0.0, 1.0, 0.0, 1.0,...
...And 5 more matches
text-transform - CSS: Cascading Style Sheets
text-transform: full-width; text-transform: full-size-kana; /* global values */ text-transform: inherit; text-transform: initial; text-transform: unset; capitalize is a keyword that converts the first letter of each word to uppercase. other characters remain unchanged (they retain their original case as written in the element's text). a letter is defined as a character that is part of unicode's letter or number general categories ; thus, any punctuation marks or symbols at the beginning of a word are ignored. authors should not expect capitalize to follow language-specific title casing conventions (such as skipping articles in english). the capitalize keyword was under-specified in css 1 and css 2.1. this resulted in differences between browsers in the way the first letter was ca...
...» *the* _css_ ¿capitalize? ?¡transform!</strong> </p> <p>text-transform: capitalize <strong><span>(this) “is” [a] –short– -test- «for» *the* _css_ ¿capitalize? ?¡transform!</span></strong> </p> span { text-transform: capitalize; } strong { float: right; } this demostrates how initial punctuations of a word are ignored. the keyword target the first letter, that is the first unicode character part of the letter or number general category. capitalize (symbols) <p>initial string <strong>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</strong> </p> <p>text-transform: capitalize <strong><span>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</span></strong> </p> span { text-transform: capitalize; } strong { float: right; } this demonstrates how initial symbols are ignored. the...
...y. capitalize (symbols) <p>initial string <strong>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</strong> </p> <p>text-transform: capitalize <strong><span>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</span></strong> </p> span { text-transform: capitalize; } strong { float: right; } this demonstrates how initial symbols are ignored. the keyword target the first letter, that is the first unicode character part of the letter or number general category. capitalize (dutch ij digraph) <p>initial string <strong lang="nl">the dutch word: "ijsland" starts with a digraph.</strong> </p> <p>text-transform: capitalize <strong><span lang="nl">the dutch word: "ijsland" starts with a digraph.</span></strong> </p> span { text-transform: capitalize; } strong { float: right; } this demonstrat...
...And 5 more matches
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
the new parser is faster, complies with the html5 standard, and enables a lot of new functionality as well. the new parser introduces these major improvements: you can now use svg and mathml inline in html5 pages, without xml namespace syntax. parsing is now done in a separate thread from firefox’s main ui thread, improving overall browser responsiveness. calls to innerhtml are a lot faster. ...
... tree. this will result in more consistent behavior across browser implementations. in other words, in supporting html5, gecko, webkit, and internet explorer (ie) will behave more consistently with each other. ...
...if you tested your site only with gecko 1.x or webkit (for example, firefox-only intranets or webkit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with gecko 2. ...
...And 5 more matches
<input type="password"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › password
this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the password field has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text entered into the field is greater than maxlength utf-16 c...
...e units) the user can enter into the password field. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the password field has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text entered into the field is greater than maxlength utf-16 code units long. minlength the minimum number of characters (as utf-16 code units) the user can enter into the password entry field. this must be an non-negative integer value smaller than or equal to the value specified by maxlength. if no minlength is specified, or an invalid value is specified, the password input has no minimum length. the input will fail constraint validation if the length of t...
... pattern the pattern attribute, when specified, is a regular expression that the input's value must match in order for the value to pass constraint validation. ...
...And 5 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
haring (cors) is a mechanism that uses additional http headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. a web application executes a cross-origin http request when it requests a resource that has a different origin (domain, protocol, or port) from its own. an example of a cross-origin request: the front-end javascript code served from https://domain-a.com uses xmlhttprequest to make a request for https://domain-b.com/data.json. for security reasons, browsers restrict cross-origin http requests initiated from scripts. for example, xmlhttprequest and the fetch api follow the same-origin policy. this means that a web application using those apis can only request resources from the same origin the application was load...
...ore specifically, this article is for web administrators, server developers, and front-end developers. modern browsers handle the client side of cross-origin sharing, including headers and policy enforcement. but the cors standard means servers have to handle new request and response headers. another article for server developers discussing cross-origin sharing from a server perspective (with php code snippets) is supplementary reading. what requests use cors? this cross-origin sharing standard can enable cross-site http requests for: invocations of the xmlhttprequest or fetch apis, as discussed above. web fonts (for cross-domain font usage in @font-face within css), so that servers can deploy truetype fonts that can only be cross-site loaded and used by web sites that are permitted to d...
...ting supported methods from the server with the http options request method, and then, upon "approval" from the server, sending the actual request. servers can also inform clients whether "credentials" (such as cookies and http authentication) should be sent with requests. cors failures result in errors, but for security reasons, specifics about the error are not available to javascript. all the code knows is that an error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. subsequent sections discuss scenarios, as well as provide a breakdown of the http headers used. examples of access control scenarios we present three scenarios that demonstrate how cross-origin resource sharing works. all these examples use xmlhttprequest, wh...
...And 5 more matches
Control flow and error handling - JavaScript
ext » javascript supports a compact set of statements, specifically control flow statements, that you can use to incorporate a great deal of interactivity in your application. this chapter provides an overview of these statements. the javascript reference contains exhaustive details about the statements in this chapter. the semicolon (;) character is used to separate statements in javascript code. any javascript expression is also a statement. see expressions and operators for complete information about expressions. block statement the most basic statement is a block statement, which is used to group statements. the block is delimited by a pair of curly brackets: { statement_1; statement_2; ⋮ statement_n; } example block statements are commonly used with control flow stat...
...in other words, block statements do not define a scope. "standalone" blocks in javascript can produce completely different results from what they would produce in c or java. for example: var x = 1; { var x = 2; } console.log(x); // outputs 2 this outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. (in c or java, the equivalent code would have outputted 1.) since ecmascript2015, the let and const variable declarations are block-scoped. see the let and const reference pages for more information. conditional statements a conditional statement is a set of commands that executes if a specified condition is true. javascript supports two conditional statements: if...else and switch. if...else statement use the if statement t...
...e block statements—especially when nesting if statements: if (condition) { statement_1_runs_if_condition_is_true; statement_2_runs_if_condition_is_true; } else { statement_3_runs_if_condition_is_false; statement_4_runs_if_condition_is_false; } it's unwise to use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. ...
...And 5 more matches
Regular expression syntax cheatsheet - JavaScript
a-z0-9_]. for example, /\w/ matches "a" in "apple", "5" in "$5.28", and "3" in "3d". \w matches any character that is not a word character from the basic latin alphabet. equivalent to [^a-za-z0-9_]. for example, /\w/ or /[^a-za-z0-9_]/ matches "%" in "50%". \s matches a single white space character, including space, tab, form feed, line feed, and other unicode spaces. equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches " bar" in "foo bar". \s matches a single character other than white space. equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches "foo" in "foo bar". \t matches a horizon...
...s a linefeed. \v matches a vertical tab. \f matches a form-feed. [\b] matches a backspace. if you're looking for the word-boundary character (\b), see boundaries. \0 matches a nul character. do not follow this with another digit. \cx matches a control character using caret notation, where "x" is a letter from a–z (corresponding to codepoints u+0001–u+001f). for example, /\cm/ matches "\r" in "\r\n". \xhh matches the character with the code hh (two hexadecimal digits). \uhhhh matches a utf-16 code-unit with the value hhhh (four hexadecimal digits). \u{hhhh} or \u{hhhhh} (only when the u flag is set.) matches the character with the unicode value u+hhhh or u+hhhhh (hexadecimal digits). ...
...eans match 0 or more "a"s. to match * literally, precede it with a backslash; for example, /a\*/ matches "a*". note that some characters like :, -, @, etc. neither have a special meaning when escaped nor when unescaped. escape sequences like \:, \-, \@ will be equivalent to their literal, unescaped character equivalents in regular expressions. however, in regular expressions with the unicode flag, these will cause an invalid identity escape error. this is done to ensure backward compatibility with existing code that uses new escape sequences like \p or \k. to match this character literally, escape it with itself. in other words to search for \ use /\\/. assertions if you are looking to contribute to this document, please also edit the original article boun...
...And 5 more matches
Regular expressions - JavaScript
and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions). character classes distinguish different types of characters. for example, distinguishing between letters and digits. groups and ranges indicate groups and ranges of expression characters. quantifiers indicate numbers of characters or expressions to match. unicode property escapes distinguish based on unicode character properties, for example, upper- and lower-case letters, math symbols, and punctuation. if you want to look at all the special characters that can be used in regular expressions in a single table, see the following: special characters in regular expressions. characters / constructs corresponding article \, ., \cx...
... escaping if you need to use any of the special characters literally (actually searching for a "*", for instance), you must escape it by putting a backslash in front of it. for instance, to search for "a" followed by "*" followed by...
... escaping if you need to use any of the special characters literally (actually searching for a "*", for instance), you must escape it by putting a backslash in front of it. for instance, to search for "a" followed by "*" followed by "b", you'd use /a\*b...
...And 5 more matches
this - JavaScript
object whether in strict mode or not. // in web browsers, the window object is also the global object: console.log(this === window); // true a = 37; console.log(window.a); // 37 this.b = "mdn"; console.log(window.b) // "mdn" console.log(b) // "mdn" note: you can always easily get the global object using the global globalthis property, regardless of the current context in which your code is running. function context inside a function, the value of this depends on how the function is called. since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. function f1() { return this; } // in a browser: f1() === window; // true // in node: f1() === globalthis; // true...
... static third(){} } new example(); // ['constructor', 'first', 'second'] note: static methods are not properties of this. they are properties of the class itself. derived classes unlike base class constructors, derived constructors have no initial this binding. calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the inherited class: this = new base(); warning: referring to this before calling super() will throw an error. derived classes must not return before calling super(), unless they return an object or have no constructor at all. class base {} class good extends base {} class alsogood extends base { constructor() { return {a: 5}; } } class bad extends base { constructo...
...ing used. function f() { return this.a; } var g = f.bind({a: 'azerty'}); console.log(g()); // azerty var h = g.bind({a: 'yoo'}); // bind only works once! console.log(h()); // azerty var o = {a: 37, f: f, g: g, h: h}; console.log(o.a, o.f(), o.g(), o.h()); // 37,37, azerty, azerty arrow functions in arrow functions, this retains the value of the enclosing lexical context's this. in global code, it will be set to the global object: var globalobject = this; var foo = (() => this); console.log(foo() === globalobject); // true note: if this arg is passed to call, bind, or apply on invocation of an arrow function it will be ignored. you can still prepend arguments to the call, but the first argument (thisarg) should be set to null. // call as a method of an object var obj = {func: foo}...
...And 5 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
previous overview: progressive web apps next now that we’ve seen what the structure of js13kpwa looks like and have seen the basic shell up and running, let's look at how the offline capabilities using service worker are implemented. in this article, we look at how it is used in our js13kpwa example (see the source code also). we examine how to add offline functionality. ...
...mine how to add offline functionality. service workers explained service workers are a virtual proxy between the browser and the network. they finally fix issues that front-end developers have struggled with for years — most notably how to properly cache the assets of a website and make them available when the user’s device is offline. they run on a separate thread from the main javascript code of our page, and don't have any access to the dom structure. this introduces a different approach from traditional web programming — the api is non-blocking, and can send and receive communication between different contexts. you are able to give a service worker something to work on, and receive the result whenever it is ready using a promise-based approach. they can do a lot more than "just" ...
...orming heavy calculations on a separate thread, etc. service workers are quite powerful as they can take control over network requests, modify them, serve custom responses retrieved from the cache, or synthesize responses completely. security because they are so powerful, service workers can only be executed in secure contexts (meaning https). if you want to experiment first before pushing your code to production, you can always test on a localhost or setup github pages — both support https. offline first the "offline first" — or "cache first" — pattern is the most popular strategy for serving content to the user. if a resource is cached and available offline, return it first before trying to download it from the server. if it isn’t in the cache already, download it and cache it fo...
...And 5 more matches
Content Processes - Archive of obsolete content
these are explained in the next section. ...
...these are explained in the next section. ...
... actually implemented, but by the time they were cancelled, the sdk was already designed with them in mind. to understand this article, it's probably best to read it as if content and add-on processes actually exist. to communicate between add-on and content processes, the sdk uses something called content scripts. these are explained in the first section. content scripts communicate with add-on code using something called event emitters. these are explained in the next section. content workers combine these ideas, allowing you to inject a content script into a content process, and automatically set up a communication channel between them. these are explained in the third section. in the next section, we will look at how content scripts interact with the dom in a content process. there are s...
...And 4 more matches
/loader - Archive of obsolete content
create commonjs module loaders. usage the code is intentionally authored so that it can be loaded in several ways. it can be loaded as a regular script tag in documents that have system principals (note: this does not appear to work as of 02.2016 due to "use strict" being added to the file): <script type='application/javascript' src='resource://gre/modules/commonjs/toolkit/loader.js'></script> this will expose a single loader object containing all of the api functions described in this document. ...
...ript tag in documents that have system principals (note: this does not appear to work as of 02.2016 due to "use strict" being added to the file): <script type='application/javascript' src='resource://gre/modules/commonjs/toolkit/loader.js'></script> this will expose a single loader object containing all of the api functions described in this document. ...
...js'); it can be required as a commonjs module from a module loaded in the loader itself: let { loader, require, unload } = require('toolkit/loader'); what is it good for ? create somewhat standardized js environments that people doing non-browser js are familiar with. provide an environment for loading commonjs style modules, which makes it possible to consume lots of interesting code that has already been developed. secure each module in an isolated js sandbox and makes any capability imports explicit via calls to the require() function. create task specific loaders with restricted module access. provide unload hooks that may be used to undo changes made by anything loaded into it. instantiation the loader module provides a loader() function that may be used to instanti...
...And 4 more matches
Miscellaneous - Archive of obsolete content
system info operating system detection // returns "winnt" on windows vista, xp, 2000, and nt systems; // "linux" on gnu/linux; and "darwin" on mac os x. ...
... always returns 0. and if you read it directly, you always got nothing. and here's how it's done postdata.queryinterface(ci.nsiseekablestream).seek(ci.nsiseekablestream.ns_seek_set, 0); var stream = cc["@mozilla.org/binaryinputstream;1"].createinstance(ci.nsibinaryinputstream); stream.setinputstream(postdata); var postbytes = stream.readbytearray(stream.available()); var poststr = string.fromcharcode.apply(null, postbytes); //do anything to your poststr alert(poststr); getting a string from the input stream is made somewhat simpler in firefox 4, by the addition of netutil.readinputstreamtostring() getting postdata of a request before the request is sent the above code will get the postdata for a page that has already loaded. to see what the postdata looks like before the request is even ...
...however, if you are not going to cancel the request, you need to "rewind" it by calling: postdata.queryinterface(ci.nsiseekablestream).seek(ci.nsiseekablestream.ns_seek_set, 0); adding custom certificates to a xulrunner application you need to ship a xulrunner application with your own ssl certificates? for firefox, you could use the...
...And 4 more matches
Windows - Archive of obsolete content
this article offers code snippets demonstrating common tasks you may wish to perform. opening new browser windows to open a new browser window, you can simply use window.open(). however, window.open() returns a window object for content, not for the browser window itself, so you should get the chrome window first. the simplest way to do that is to use nsiwindowmediator. ...
...orm. opening new browser windows to open a new browser window, you can simply use window.open(). however, window.open() returns a window object for content, not for the browser window itself, so you should get the chrome window first. the simplest way to do that is to use nsiwindowmediator. example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typeerror from firefox console. in particular the components.classes is undefined an...
...ndow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typeerror from firefox console. in particular the components.classes is undefined and the components object is deprecated. it will soon be removed. draggable windows to make a window draggable by clicking on the window's contents, you can use the mousedown and mousemove events. the following code does not care which element is clicked on, simply responding to all mousedown events equally. you could improve this code by checking the event.target element and only setting the startpos if the element matches some criteria. example var startpos = null; function mousedown(event) { startpos = [event.clientx, event.clienty]; } function mousemove(event) { if (startpos) { var newx = eve...
...And 4 more matches
Adding windows and dialogs - Archive of obsolete content
with the dialog. let somevalue = 2; let returnvalue = { accepted : false , result : "" }; window.opendialog( "chrome://xulschoolhello/content/somedialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", somevalue, returnvalue); // you can send as many extra parameters as you need. // if (returnvalue.accepted) { do stuff } the optional parameters are available in the dialog code through the window.arguments property: let somevalue = window.arguments[0]; let returnvalue = window.arguments[1]; // returnvalue.accepted = true; // returnvalue.result = "something"; the parameter named returnvalue is an object that the dialog will modify to reflect what the user did in it. this is the simplest way to have the dialog return something to its opener. note that the opener w...
...return something to its opener. note that the opener will wait until the dialog is closed. this means the opendialog function call will not return until the dialog has been closed by the user. common dialogs and the prompt service there are several types of dialogs that are fairly common, so there are ways to create them easily without having to reinvent the wheel and write all their xul and js code all over again. whenever you need a new dialog, you should ask yourself if it can be implemented using these common dialogs, and use them whenever it is possible. they have been thoroughly tested for os integration, accessbility and localization, so you save yourself a lot of work and favor them. using the prompt service is the recommended way to create common dialogs in an extension. read the a...
...on, so you save yourself a lot of work and favor them. using the prompt service is the recommended way to create common dialogs in an extension. read the article and its examples carefully, because there are many useful functions to use in the prompt service. there are some equivalent, simpler functions that are available in the window object, but those are meant for unprivileged html javascript code. alert the alert is the simplest form of dialog. all it does is display a text message that the user can read and then click the ok button to dismiss it. we have been using the window.alert function to open alert messages in our examples so far, but that's not the right way to do it. it's ok to use this function if you're just debugging some problem and want to see if the program reaches a spec...
...And 4 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
for add-ons targeting only the latest firefox, those wishing to support older browsers will need to provide fallbacks. for more information, see this blog post on the issues at hand. non-mutation triggers it is usually possible to tell when a mutation has occurred or is about to occur without resorting to mutation events or observers. most of these methods are specific to a particular site or codebase. hashchange and popstate events most ajax-heavy sites update the url when they significantly change their content, either via a change to the fragment identifier (hash) or more recently via the history.pushstate method. the former triggers a hashchange event while the latter triggers a popstate event. event listeners for those events are the preferred method for detecting dom modifications ...
...s, this must be used in combination with a slight delay, or even polling, via settimeout, for cases where the url change happens before the page is fully loaded. this method works particularly well with services like google instant, and the gawker family of sites. network listeners ajax-based page changes are almost universally tied to xmlhttprequests. these requests can be tracked from chrome code using a variety of methods, including web progress listeners, http observers, and content policies. while these are not exceptionally efficient (they run for every http request, and considerably more often for some methods), they work very well for certain applications pure css pure css can be more powerful than most people suspect. it is often possible to do things for which people have tradit...
...e event.target and its parents can be searched for a matching element. you can read more about event delegation here. it is important to note, however, that this method can have severe performance implications for certain events, namely mouseover, mouseout, and friends, which are fired very often while the mouse is moving. monkey patching in many instances, especially when dealing with chrome code, the best way to modify actions which result in dom mutations is by wrapping the functions that trigger those changes. for instance, when you want to modify the result of dom mutations that you know are the result of the doawesomedomstuff() function, you can wrap it as follows: { let originaldoawesomedomstuff = doawesomedomstuff; doawesomedomstuff = function _doawesomedomstuff() ...
...And 4 more matches
Intercepting Page Loads - Archive of obsolete content
s of the load process. which one you should use solely depends on your needs. we will start with the simplest one, which is also the most common to use. note: performance is very important when it comes to add-ons and page loads. read the recommendations in appendix a regarding performance if you're planning on implementing any of these. the easy way: load events this comes from the tabbrowser code snippets page. in a nutshell, from the chrome code in the overlay we add an event listener for the load event. this._loadhandler = function() {that._onpageload(); }; gbrowser.addeventlistener("load", this._loadhandler, true); gbrowser is a global object that corresponds to the tabbrowser element in the main browser window. it is full of useful functions, so you should always keep it in mind w...
...t windows. attaching the load event handler to gbrowser allows us to listen to these events for all tabs, without having to worry how many tabs are open. gbrowser exists in every browser window. we store the handler function in a private variable because later we want to remove it when we do not need it anymore. gbrowser.removeeventlistener("load", this._loadhandler, true); finally, the actual code for the handler, which is very simple: _onpageload : function(event) { // this is the content document of the loaded page. let doc = event.originaltarget; if (doc instanceof htmldocument) { // is this an inner frame? if (doc.defaultview.frameelement) { // frame within a tab was loaded. // find the root document: while (doc.defaultview.frameelement) { doc ...
...cept page loads before any content is downloaded, and before the user sees anything in the tab. http observers another common way of detecting and intercepting loads is using http observer topics. this is how the tamper data extension and others do it. http notifications are fired for all http requests originating from firefox. they are window-independent, so it is better to keep your observer code in non-chrome objects (your xpcom service or jsm module). otherwise you have to make sure to avoid duplicated work if you have 2 or more windows open. there are 2 http topics you can listen to, as specified in the observer notifications page: topic description http-on-modify-request called as an http request is made. the channel is available to allow you to modify header...
...And 4 more matches
List of Mozilla-Based Applications - Archive of obsolete content
mation about it. ...
... apicawatch site performance monitoring tool uses firefox as part of its monitoring package astyle css editor editing tool atmail webmail client aviva for java mainframe connectivity product uses mozilla rhino babelgum internet tv service basilisk pre-servo xul-based web browser uses most of the firefox 55 source code batik java-based toolkit uses mozilla rhino bitbox security focused browser seemingly based on firefox blackbird browser for african american community bluegriffon wysiwyg editor next generation version of composer buzzbird twitter client built on xulrunner camino browser 2.5m downloads and ~400,000 active ...
... font management tool firecast digital signage and interactive kiosk tools also used in firecast easystart mozilla firefox web browser web browser usage stats from global stats fossamail email client for wi...
...And 4 more matches
JavaScript Client API - Archive of obsolete content
overview this page describes how to use the internal client-side sync javascript api. this api is available in mozilla-based products that use sync, such as firefox desktop. this document is somewhat outdated, and the api isn't well-supported for use from add-ons; tread carefully. the best, and most up-to-date, reference to sync's internal apis is the source code. please note that usage of the sync apis is governed by a terms of service: by accessing or using the firefox sync apis in connection with the development of your own client software to access the firefox sync services (a “third party client”), you acknowledge that you will need to install and use a local version of the firefox sync server for multiple account testing and that any use of mozilla’s hosted firefox syn...
...ine the sync client ships with a number of engines out of the box (history, bookmarks, etc). it is possible for other components, including 3rd party extensions, to supplement the set of engines and synchronize their own data. a word of warning: the javascript client api is still a young component and is continuing to evolve. therefore, developers outside of the sync core should know that their code could require significant refactoring in future releases. before developing against the javascript api, it is recommended to speak to developers of the api. see https://wiki.mozilla.org/services/sync for their contact information. to create a custom sync engine to synchronize a new data you, you'll need to define an engine object that extends the base syncengine object. this involves writing typ...
...ou'll need to define an engine object that extends the base syncengine object. this involves writing types that extend the store, tracker, and record types as well. it will be very helpful to look at an existing sync engine for guidance. have a look at one of the following files: services/sync/modules/engines/bookmarks.js services/sync/modules/engines/history.js setting up a js module the code for your custom sync engine should live in a js module. first off we're going to import the files mentioned above at the top the file. we're also going to import ''util.js'' as it contains many useful helpers. const cu = components.utils; cu.import("resource://services-sync/engines.js"); cu.import("resource://services-sync/record.js"); cu.import("resource://services-sync/util.js"); the record ...
...And 4 more matches
Monitoring downloads - Archive of obsolete content
e status of the download. a tooltip is included that displays the full source url of the file. download the full sample. setting up when the extension loads, it will do some housekeeping chores. in particular, it needs to get an instance of the download manager's nsidownloadmanager interface and create the database into which its data will be stored. ...
...ened, and an sqlite create table command is executed to create the table. finally, the database is closed. note: the mozistorageconnection method close() is being added to firefox 3 alpha 8; in prior versions of firefox, there is no way to explicitly close the database. instead, it is closed when the garbage collector disposes of the connection object. ...
...dded to firefox 3 alpha 8; in prior versions of firefox, there is no way to explicitly close the database. instead, it is closed when the garbage collector disposes of the connection object. handling download state changes once the code above is run, our ondownloadstatechange() method is called whenever a download's state changes. this is part of the nsidownloadprogresslistener interface. that code looks like this: ondownloadstatechange: function(astate, adownload) { var statement; switch(adownload.state) { case components.interfaces.nsidownloadmanager.download_downloading: // add a new row for the download being started; each row includes the // source uri, size, and start time. the end time and download speed // are both set to 0 at first, since we don...
...And 4 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
ents, and even construct your own xml language for defining your ui. for instance imagine that you wanted to create a chess style game. you could easily create xml elements such as <chessboard> or <chesspiece> and via xbl map these to images and application logic. this is very powerful since you could make improvements to the underlying application logic without having to rewrite the higher level code. our platform also can take advantage of other internet standards such as xslt and rdf. rdf, a core element to the framework, allows you to define dynamic elements in your ui (elements that may change after you have completed the application, such as a "history" menu item). xslt could be used to translate information from web services, rss, soap, or other xml-based languages and convert them into...
...speed and industry leading standards support. gecko is the premier cross-platform, full-featured, mature and well-tested layout engine available, providing robust and high quality support for a massive array of standards. its ability to render web content correctly is exceptional. gecko consists roughly of an html parser and xml parser, a dom implementation, a css parser and style system, and the code for css-based and html-based layout and rendering. as personal connectivity expands from the desktop computer to new web-enabled products and devices, gecko is a browser engine that has been designed from the ground up to power a new generation of desktop browsers and browsing devices and to accelerate the growth and development of the next-generation internet. small, fast and standards compliant...
...orts make the development of browsers, applications and devices faster and easier than ever before. gecko is the first browser engine ever to deliver the full web standards support that developers have been calling for. this robust standards support for the first time makes it possible to implement powerful web applications with rich user interfaces without using proprietary or platform dependent code. because gecko has a cross-platform architecture, is easily embeddable and is open source, it and the rich web applications it supports will be usable on any supported platform or device. this will dramatically reduce the cost and complexity of developing and distributing rich web applications and full-functionality browsing devices that run them. by meeting the needs of developers and companies ...
...And 4 more matches
Custom toolbar button - Archive of obsolete content
eamonkey 2.0, thunderbird or sunbird. (for seamonkey 1.x, see the page custom toolbar button:seamonkey.) you do not need any special technical skills or tools, and almost all the information you need is on this page. introduction the technique described here does not involve any hacking. instead, you make your custom button as a self-contained extension in your profile. you can use the sample code provided here to make buttons that do various useful things. if you know how to program in javascript, then you can write your own code that does other things. you can use this page if all you really want is a button for some special purpose. you can also use this page to learn about extensions, and as a starting point if you plan to write a more complex extension. note that this extension is v...
...are not appropriate for them. required tools you will need two tools. your operating system normally provides them: a way to create and work with files and directories a text editor for plain text files character encoding some text editors have a setting for character encoding. if your language uses only plain latin (ascii) characters, set your text editor to use any encoding except unicode. if your language uses accents or other non-latin characters, set your text editor to save files using the utf-8 encoding. to check your text editor, create a plain text file named test.txt. in the file, type some of the special characters that your language uses. save the file. open the file in firefox (for example, by dragging it and dropping it in firefox, or by choosing file – open file.
...s using the utf-8 encoding. to check your text editor, create a plain text file named test.txt. in the file, type some of the special characters that your language uses. save the file. open the file in firefox (for example, by dragging it and dropping it in firefox, or by choosing file – open file... from firefox's menu bar). from firefox's menu bar, choose view – character encoding – unicode (utf-8). check that the text you typed looks ok with this setting. if your text editor does not support utf-8, search the internet for a better one that you can download. optional tools you can optionally use any image editor to customize the images. you can optionally use a jar tool or zip tool to package your button as a cross-platform installable (xpi) for other people to install and use. ...
...And 4 more matches
Document Object Model - Archive of obsolete content
pt itself is just a scripting language that can access these objects because mozilla provides these objects for use. in javascript, there is always a single global object that is always available. you can refer to the properties and methods of the global object without having to qualify them with an object. for example, if the global object has a 'name' property, you can change the name with the code 'name = 7', without having to specify any object to use. in a browser context, the window is the global object, and the same is also true for xul. naturally, this global object will be different for each window. each frame will also have a separate window object. the window is often referred to using the window property, although this is optional. sometimes, this is done just to clarify the scop...
...g two lines which open a new window are functionally equivalent: window.open("test.xul","_new"); open("test.xul","_new"); when you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object. in xul, each function you declare will be set as a property of the window object. for example, the following code will display the text 'message' in an alert twice. function gettext(){ return "message"; } alert(gettext()); alert(window.gettext()); thus, if you want to access variables or call a function declared in a script used by another window, you just need to access it using the other window's window object. for example, if we combined the last two examples into a single file, we might want to cal...
...ever, there are a few functions that are specific to one document type or the other. retrieving elements the most common method to retrieve an element in a document is to give the element an id attribute and the use the document's getelementbyid() method. we've added the id attribute to a number of elements in the find file dialog. for example, we could get the state of a check box by using the code below: var state = document.getelementbyid('casecheck').checked; the value casecheck corresponds to the id of the case sensitive checkbox. once we have an indication of whether it is checked or not, we can use the state to perform the search. we could do something similar for the other check box, or any other element that has an id. we'll need to get the text in the input field for example. ...
...And 4 more matches
Updating Commands - Archive of obsolete content
« previousnext » in this section, we will look at how to update commands. invoking commands if a command has an oncommand attribute, you can invoke it just by using the docommand method of the command or an element which links to it. for other commands, you will need to use a couple of additional lines of code. you will need to use these extra steps when invoking commands implemented by a controller. in addition, you will need to do this when creating your own menu commands, for instance to implement the edit menu commands in your own application. fortunately, the extra code is fairly simple. all we need to do is get the needed controller and call the command. a simple way of doing this is the following: var controller = document.commanddispatcher.getcontrollerforcommand("cmd_...
...then, it checks to see whether the command is enabled, and then executes the command using the docommand method of the controller. note that we don't need to figure out which element to use or which controller to use. ...
...patcher. then, it checks to see whether the command is enabled, and then executes the command using the docommand method of the controller. note that we don't need to figure out which element to use or which controller to use. the command dispatcher handles that part. also, we could just call docommand without checking if the command was enabled or not, although we probably shouldn't do that. the code above is generic enough that it can be a function that takes a command as an argument and executes that command. this function could then be reused for all commands. in fact, this is common enough that mozilla includes a library which does just that. if you include the script 'chrome://global/content/globaloverlay.js' in a xul file, you can call the godocommand method which executes the command p...
...And 4 more matches
XPCOM Interfaces - Archive of obsolete content
h modify the interface and perform tasks. however, there are quite a number of things that cannot be performed directly with javascript. for example, if we wanted to create a mail application, we would need to write scripts which would connect to mail servers to retrieve and send mail. javascript does not have the capability to do such things. the only way to handle this would be to write native code that would get mail. we also need to have a way for our scripts to call the native code easily. mozilla provides such a method which involves using xpcom (cross-platform component object model). mozilla provides many xpcom components and interfaces. so, in most cases, you don't need to write native code for yourself. after learning this section, you can search suitable interfaces using xulplanet...
... about xpcom mozilla is constructed from a collection of components, each of which performs a certain task. for example, there is a component for each menu, button and element. the components are constructed from a number of definitions called interfaces. an interface in mozilla is a definition of a set of functionality that could be implemented by components. components are what implement the code in mozilla that does things. each component implements the functionality as described by interfaces. a single component might implement multiple interfaces. and multiple components might implement the same interface. let's take an example of a file component. an interface would need to be created which describes properties and functions that can be performed on files. a file would need propertie...
...ted which describes properties and functions that can be performed on files. a file would need properties for its name, modification date and its size. functions of a file would include moving, copying and deleting it. the file interface only describes the characteristics of a file, it does not implement it. the implementation of the file interface is left to a component. the component will have code which can retrieve the file's name, date and size. in addition, it will have code which copies and renames it. we don't care how the component implements it, as long as it implements the interface correctly. of course, we'll have different implementations anyway, one for each platform. the windows and macintosh versions of a file component would be significantly different. however, they would bo...
...And 4 more matches
XUL accessibility guidelines - Archive of obsolete content
can't use a mouse. many screen reader users and those with physical disabilities rely on the keyboard as their primary input tool. these users require easy, predictable, and well-documented keyboard control. tab order provide a logical tab order and ensure that users can navigate all content using a keyboard. by default, the tab order is determined by the order of the elements in the underlying code. it can also be set programmatically with the tabindex attribute if needed, but this should be done sparingly and thoroughly tested whenever it is used. the navigation order should be logical, generally left to right, top to bottom. navigation order may vary depending on the nature of the application or the reading direction of the language. ensure that tab order is logical and all interactive e...
...s. mozilla's accesskey faq. a short reference for using the accesskey attribute. context menus the context menu is the small menu activated with a right mouse click on a content area or element (or with shift + f10 or vk_apps on windows and ctrl + click or ctrl + space on a mac). use the oncontextmenu event handler or the context attribute to create context menus. do not specifically code them to open on a click of the right mouse button. the oncontextmenu event and context attribute work with the correct platform-specific context menu triggers, including the keyboard button and appropriate mouse clicks. mouse dependent scripting functionality associated with mouse events such as onmouseover, onmousemove, and ondrag can only be activated with the use of the mouse. provide keyboa...
.... alternative text is not needed when an image serves a purely decorative function. use the "alt" attribute to describe html images and use the "tooltiptext" attribute on xul elements that use images (i.e. image elements, buttons with images). for toolbar buttons with images it is recommended to use both a text label in the label attribute and image alt text in the tooltiptext attribute. view the code examples below. <image src="stop.png" tooltiptext="stop" /> <html:img src="stop.jpg" alt="stop" /> <html:img src="decorative_image.jpg" alt="" /> <!-- in html the alt attribute is required. --> <toolbarbutton label="stop" image="stop.png" tooltiptext="stop loading the page" /> title provide unique titles to window container elements such as windows, wizards, and dialogs. titles provide user...
...And 4 more matches
key - Archive of obsolete content
Archive › Mozilla › XUL › key
« xul reference home [ examples | attributes | properties | methods | related ] the key element defines a window-global keyboard shortcut and must be placed inside a keyset element. when a key matching the attributes on the key element is pressed, the command will be fired on the key element. the key pressed must match the key attribute (or keycode attribute) as well as the modifiers attribute in order for the key element to be activated. for the shortcut defined using the key element to work, you must specify a command attribute (or an oncommand handler) on the key element. to display the shortcut defined with the key element in the ui, you can use <menuitem key="key element's id" command="command id" .../>. in order to use (non-default) key commands within specific e...
...d attribute (or an oncommand handler) on the key element. to display the shortcut defined with the key element in the ui, you can use <menuitem key="key element's id" command="command id" .../>. in order to use (non-default) key commands within specific elements, you will need to listen for key events. more information is available in the xul tutorial. attributes command, disabled, key, keycode, keytext, modifiers, oncommand, phase examples (example needed) attributes command type: id set to the id of a command element that is being observed by the element. 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,...
...ll, however, still respond to mouse events. to enable the element, leave this attribute out entirely. visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. key type: character the character that must be pressed. this should be set to a displayable character. keycode type: string key code for keys that do not have displayable characters, such as the enter key or function keys, use this attribute instead of the key attribute. valid keys are listed at keyboard shortcuts. keytext type: string a label for the keyboard shortcut. this text would appear next to a menuitem label if that menuitem is associated with the key element via its key attribute. ...
...And 4 more matches
nsIContentPolicy - Archive of obsolete content
type_subdocument 7 indicates a document contained within another document (for example, <iframe> and <frame> elements). note: gecko uses type_internal_frame and type_internal_iframe in order to discern the difference internally. these types are mapped to type_subdocument before being passed into the implementation of the content policy and should not be used outside gecko code. type_refresh 8 indicates a timed refresh. shouldload() will never get this, because it does not represent content to be loaded (the actual load triggered by the refresh will go through shouldload() as expected). shouldprocess() will get this for, for example <meta> refresh elements and http refresh headers. type_xbl 9 indicates an xbl binding ...
...g> (with the srcset attribute or <picture>. type_web_manifest 22 indicates a request to load a web manifest. type_internal_script 23 an internal constant used to represent scripts loaded using <script> elements. important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_worker 24 an internal constant used to represent scripts loaded through a dedicated worker. important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_shared_worker 25 an internal constant used to represent scrip...
...ript before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_shared_worker 25 an internal constant used to represent scripts loaded through a shared worker. important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_embed 26 an internal constant used to represent content loaded from <embed> elements. important: this type is mapped to type_object before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_object 27 an internal constant used to represent content loaded fro...
...And 4 more matches
Mozilla release FAQ - Archive of obsolete content
zilla? mozilla is a project to continue netscape communicator as an open project. the project is maintained by employees of netscape (now a division of aol), red hat, some other companies, as well as contributors from the community. on what is mozilla based? the mozilla project started near the end of life of the 4.x line of netscape communicator. originally, the plan was just to re-stabilize the code and release 5.0, but it was decided within the community that the more ambitious changes that were planned for later integration were close to being ready. the old layout engine, networking engine, and several of the older modules were gutted, and much later, the sources reached the point where netscape was comfortable making a release, and so netscape 6.0 was released. netscape 6.0 and above are...
...der modules were gutted, and much later, the sources reached the point where netscape was comfortable making a release, and so netscape 6.0 was released. netscape 6.0 and above are based off of the mozilla source. mozilla 1.0 (mozilla uses a different versioning system than netscape) is due for release soon. when was mozilla released? the source to mozilla was first released on 31 march 1998. the code has been continually available since then via cvs (see section 1.8), and occasional binary releases (first as milestones, and more recently as versioned releases) have been made. as of the time of this update, mozilla 1.0 release candicate 2 is the most recent release. what is the current version of mozilla? mozilla is continually available via cvs, and also is occasionally released as versioned ...
...st. take this into consideration when posting things) ftp see the mozilla ftp mirror section for ftp sites under which license terms was mozilla released? mozilla is released under the npl/mpl (netscape/mozilla public licenses) which are in some ways similar to the gnu gpl, and in some ways similar to a bsd-style license. take a look at mozilla.org's npl area for details. what are all of the codenames given to various netscape/mozilla projects? gecko (formerly raptor) is the new html rendering engine in mozilla. it features speed improvements, a more modular nature, and significantly less platform-dependant code. it is more suitable for being embedded in other applications than the previous rendering engine. gemini was a previous rendering engine project, renamed nglayout aurora is t...
...And 4 more matches
Extentsions FAQ - Archive of obsolete content
how to customizes toolbar button to coexist in a toolbar palette and status bar? option #3 install status buttons 1.0 <https://addons.mozilla.org/firefox/1272/> "lets you put toolbar buttons at either end of the status-bar. ...
...s you put toolbar buttons at either end of the status-bar. just drag them there from the toolbar customisation window, like you would when adding buttons to the toolbars." option #4 install toolbar control <http://webdesigns.ms11.net/chromeditp.html> asking for help with getting an extension to process windows messages. use wm_copydata how to creating an extension that can replace html code on a specific page that does not use greasemonkey? var newnode = document.createelement(" ... html content here ... "); var replaceme = document.getelementbyid("replaceme"); replaceme.parentnode.replacechild(newnode, replaceme); is it possible to place an image in the window that can be moved to anywhere in the window, and always remain on top of everything else?(similiar to using position:...
...needed to to release a mozilla extension on mozallia site? you must remove updateurl from the install.rdf and use a known to amo minversion/maxversion. no confirmation that the answer given worked yet. is it possible to open the url in a new tab? var tab = gbrowser.addtab( url ); // and if you want it to load in the foreground: gbrowser.selectedtab = tab; is it possible to read the html-code of the current url/site? yes, this is possible. use the dom api (http://www.w3schools.com/dom/default.asp has a good tutorial). not the best answer but a good starting point for the question asker to do some research towards the answer. why does his extension not able to read the contents of a folder and then produce a segmentation fault after his extension reads preferences in thunderbird? ...
...And 4 more matches
Audio for Web games - Game development
ile at zero volume could also work if the browser allows you to change volume (see below). also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played. note: adding a web app to your mobile's homescreen may change its capabilities. in the case of autoplay on ios, this appears to be the case currently. if possible, you should try your code on several devices and platforms to see how it works. volume programmatic volume control may be disabled in mobile browsers. the reason often given is that the user should be in control of the volume at the os level and this shouldn't be overridden. buffering and preloading likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before ...
...('click', function() { myaudio.currenttime = this.getattribute("data-start"); stoptime = this.getattribute("data-stop"); myaudio.play(); }, false); } myaudio.addeventlistener('timeupdate', function() { if (this.currenttime > stoptime) { this.pause(); } }, false); note: you can try out our audio sprite player live on jsfiddle. note: on mobile we may need to trigger this code from a user-initiated event such as a start button being pressed, as described above. note: watch out for bit rates. encoding your audio at lower bit rates means smaller file sizes but lower seeking accuracy. background music music in games can have a powerful emotional effect. you can mix and match various music samples and assuming you can control the volume of your audio element you coul...
.../ for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button. ...
...And 4 more matches
Collision detection - Game development
we have the bricks appearing on the screen already, but the game still isn't that interesting as the ball goes through them. we need to think about adding collision detection so it can bounce off the bricks and break them. it's our decision how to implement this, of course, but it can be tough to calculate whether the ball is touching the rectangle or not because there are no helper functions in canvas for this. ...
...me, and there are much more sophisticated ways to do collision detection, but this will work fine for teaching you the basic concepts. a collision detection function to kick this all off we want to create a collision detection function that will loop through all the bricks and compare every single brick's position with the ball's coordinates as each frame is drawn. ...
...all four of the following statements need to be true: the x position of the ball is greater than the x position of the brick. the x position of the ball is less than the x position of the brick plus its width. the y position of the ball is greater than the y position of the brick. the y position of the ball is less than the y position of the brick plus its height. let's write that down in code: function collisiondetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { var b = bricks[c][r]; if(x > b.x && x < b.x+brickwidth && y > b.y && y < b.y+brickheight) { dy = -dy; } } } } add the above block to your code, below the keyuphandler() function. making the bricks disappear aft...
...And 4 more matches
Build the brick field - Game development
building the brick field is a little bit more complicated than adding a single object to the screen, although it's still easier with phaser than in pure javascript. let's explore how to create a group of bricks and print them on screen using a loop. ...
...he loop, and brickinfo will store all the data we need. rendering the brick image next, let's load the image of the brick — add the following load.image() call just below the others: function preload() { // ... game.load.image('brick', 'img/brick.png'); } you also need to grab the brick image from github and save it in your /img directory. drawing the bricks we will place all the code for drawing the bricks inside an initbricks function to keep it separated from the rest of the code. add a call to initbricks at the end of the create() function: function create(){ // ... initbricks(); } now onto the function itself. add the initbricks() function at the end of our games code, just before the closing </script> tag, as shown below. to begin with we've included the bric...
... and the padding between each row and column of bricks. now, let's start creating the bricks themselves — add an empty group first to contain the bricks, by adding the following line at the bottom of the initbricks() function: bricks = game.add.group(); we can loop through the rows and columns to create new brick on each iteration — add the following nested loop below the previous line of code: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { // create new brick and add it to the group } } this way we will create the exact number of bricks we need and have them all contained in a group. now we need to add some code inside the nested loop stucture to draw each brick. fill in the contents as shown below: for(c=0; c<brickinfo.count.col; c++...
...And 4 more matches
2D maze game with device orientation - Game development
development process. you can check it out on github where it’s open sourced, read the online documentation and go through the big collection of examples. the phaser framework provides you with a set of tools that will speed up development and help handle generic tasks needed to complete the game, so you can focus on the game idea itself. starting with the project you can see cyber orb source code on github. the folder structure is quite straightforward: the starting point is the index.html file where we initialize the framework and set up an <canvas> to render the game on. you can open the index file in your favourite browser to launch the game and try it. there are also three folders in the directory: img: all the images that we will use in the game. src: the javascript files with...
...folder structure is quite straightforward: the starting point is the index.html file where we initialize the framework and set up an <canvas> to render the game on. you can open the index file in your favourite browser to launch the game and try it. there are also three folders in the directory: img: all the images that we will use in the game. src: the javascript files with all the source code of the game defined inside. audio: the sound files used in the game. setting up the canvas we will be rendering our game on canvas, but we won't do it manually — this will be taken care of by the framework. let’s set it up: our starting point is the index.html file with the following content. you can create this yourself if you want to follow along: <!doctype html> <html> <head> <met...
...tate.start('game'); } }; the howto state shows the gameplay instructions on the screen before starting the game. after clicking the screen the actual game is launched. game.js the game state from the game.js file is where all the magic happens. all the initialization is in the create() function (launched once at the beginning of the game). after that some functionality will require further code to control — we will write our own functions to handle more complicated tasks. in particular, take note of the update() function (executed at every frame), which updates things such as the ball position. ball.game = function(game) {}; ball.game.prototype = { create: function() {}, initlevels: function() {}, showlevel: function(level) {}, updatecounter: function() {}, manage...
...And 4 more matches
Test your skills: sizing - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one in this task, you have two boxes. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one in this task, you have two boxes. ...
... less content than would cause it to grow to that height, however, the content should not overflow if there is more content than fits in 100 pixels. test this box by removing the content from the html to make sure you still get a 100 pixel tall box even with no content. the second box should be fixed at 100 pixels tall, so that content will overflow if there is too much. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two this task has a box, which contains another box. your task is to make the inner box 60% of the width of the outer box. the value of the box-sizing property is set to border-box, which means that the total widt...
...And 4 more matches
Test your skills: Flexbox - Learn web development
the aim of this task is to get you working with flexbox and demonstrate your understanding of how flex items behave. below are four common design patterns which you might use flexbox to create, your task is to build them. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. ...
...s codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. flex layout one these list items are the navigation for a site. they should be laid out as a row, with an equal amount of space between each item. the finished example should look like the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout two these list items are all different sizes, but we want them to be displayed as three equal sized columns, no matter what content is in each item. ...
...w. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout two these list items are all different sizes, but we want them to be displayed as three equal sized columns, no matter what content is in each item. try updating the live code below to recreate the finished example: additional questions: can you now make the first item twice the size of the other items? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout three there are two elements in the html below, a div with a class of .parent which contains another div with a ...
...And 4 more matches
Test your skills: Grid Layout - Learn web development
this aim of this task is to get you working with css grid layout, and test that you understand how a grid and grid items behave. you will be working through three small tasks which use different elements of the material you have just covered. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. grid layout one in this task you should create a grid into which the four child elements will auto-place. the grid should have three columns sharing the available space equally, and a 20-pixel gap between the column and row tracks. try up...
... to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. grid layout one in this task you should create a grid into which the four child elements will auto-place. the grid should have three columns sharing the available space equally, and a 20-pixel gap between the column and row tracks. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout two in this example we already have a grid defined. by editing the css rules for the two child elements, cause them to span over several grid tracks each; the second item should overlay the first as in the ...
...e: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout two in this example we already have a grid defined. by editing the css rules for the two child elements, cause them to span over several grid tracks each; the second item should overlay the first as in the image below. try updating the live code below to recreate the finished example: additional questions: can you now cause the first item to display on top without changing the order of items in the source? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout three there are four direct children in this grid; the starting point has the...
...And 4 more matches
Test your skills: Multicol - Learn web development
is to get you working with the css column-count, column-width, column-gap, column-span and column-rule properties and values covered in our lesson on multiple-column layout. you will be working through three small tasks which use different elements of the material you have just covered. ...
...column-count, column-width, column-gap, column-span and column-rule properties and values covered in our lesson on multiple-column layout. you will be working through three small tasks which use different elements of the material you have just covered. ...
... multicol two create columns which have a minimum width of 200px. ...
...And 4 more matches
Styling lists - Learn web development
iliar with the best practices and properties related to styling lists. a simple list example to begin with, let's look at a simple list example. throughout this article, we'll look at unordered, ordered, and description lists — all have styling features that are similar, and some that are particular to their type of list. ...
...d bottom margin of 16px (1em), the same as the different list types. ...
...items a line-height of 1.5 of their font-size. give the ordered list lower alphabetical bullets. feel free to play with the list example as much as you like, experimenting with bullet types, spacing, or whatever else you can find. if you make a mistake, you can always reset it using the reset button. if you get really stuck, press the show solution button to see a potential answer. ...
...And 4 more matches
What are browser developer tools? - Learn web development
b inspector. if you can't see the develop menu, go to safari ➤ preferences ➤ advanced, and check the show develop menu in menu bar checkbox. opera: developer ➤ developer tools context menu: press-and-hold/right-click an item on a webpage (ctrl-click on the mac), and choose inspect element from the context menu that appears. (an added bonus: this method straight-away highlights the code of the element you right-clicked.) the inspector: dom explorer and css editor the developer tools usually open by default to the inspector, which looks something like the following screenshot. this tool shows what the html on your page looks like at runtime, as well as what css is applied to each element on the page. it also allows you to instantly modify the html and css and see the results...
...hows the fonts applied to the current element. find out more find more out about the inspector in different browsers: firefox page inspector ie dom explorer chrome dom inspector (opera's inspector works the same as this) safari dom inspector and style explorer the javascript debugger the javascript debugger allows you to watch the value of variables and set breakpoints, places in your code that you want to pause execution and identify the problems that prevent your code from executing properly. to get to the debugger: firefox: select ➤ web developer ➤ debugger or press ctrl + shift + s to open the javascript debugger. if the tools are already displayed, click on the debugger tab. chrome: open the developer tools and then select the sources tab. (opera works the same way.)...
...he developer tools and then select the debugger tab. exploring the debugger there are three panes in the javascript debugger on firefox. file list the first pane on the left contains the list of files associated with the page you are debugging. select the file you want to work with from this list. click on a file to select it and view its contents in the center pane of the debugger. source code set breakpoints where you want to pause execution. in the following image, the highlight on the number 18 shows that the line has a breakpoint set. watch expressions and breakpoints the right-hand pane shows a list of the watch expressions you have added and breakpoints you have set. in the image, the first section, watch expressions, shows that the listitems variable has been added. you ca...
...And 4 more matches
Sending form data - Learn web development
we'll discuss these headers later on. note: you can find this example on github — see post-method.html (see it live also). viewing http requests http requests are never displayed to the user (if you want to see them, yo...
...t['say']); $to = htmlspecialchars($_post['to']); echo $say, ' ', $to; ?> this example displays a page with the data we sent. you can see this in action in our example php-example.html file — which contains the same example form as we saw before, with a method of post and an action of php-example.php. when it is submitted, it sends the form data to php-example.php, which contains the php code seen in the above block. when this code is executed, the output in the browser is hi mom. note: this example won't work when you load it into a browser locally — browsers cannnot interpret php code, so when the form is submitted the browser will just offer to download the php file for you. to get it to work, you need to run the example through a php server of some kind. good options for loc...
... flask import flask, render_template, request app = flask(__name__) @app.route('/', methods=['get', 'post']) def form(): return render_template('form.html') @app.route('/hello', methods=['get', 'post']) def hello(): return render_template('greeting.html', say=request.form['say'], to=request.form['to']) if __name__ == "__main__": app.run() the two templates referenced in the above code are as follows (these need to be in a subdirectory called templates in the same directory as the python-example.py file, if you try to run the example yourself): form.html: the same form as we saw above in the the post method section but with the action set to {{ url_for('hello') }}. this is a jinja2 template, which is basically html but can contain calls to the python code that is running the...
...And 4 more matches
CSS basics - Learn web development
css basics walks through what you need to get started. we'll answer questions like: how do i make text red? how do i make content display at a certain location in the (webpage) layout? how do i decorate my webpage with background images and colors? what is css? like html, css is not a programming language. it's not a markup language either. css is a style sheet language. css is what you use to selectively style html elements. ...
...programming language. it's not a markup language either. css is a style sheet language. css is what you use to selectively style html elements. for example, this css selects paragraph text, setting the color to red: p { color: red; } let's try it out! using a text editor, paste the three lines of css (above) into a new file. save the file as style.css in a directory named styles. to make the code work, we still need to apply this css (above) to your html document. otherwise, the styling won't change the appearance of the html. (if you haven't been following our project, pause here to read dealing with files and html basics.) open your index.html file. paste the following line in the head (between the <head> and </head> tags): <link href="styles/style.css" rel="stylesheet"> save i...
...d dealing with files and html basics.) open your index.html file. paste the following line in the head (between the <head> and </head> tags): <link href="styles/style.css" rel="stylesheet"> save index.html and load it in your browser. you should see something like this: if your paragraph text is red, congratulations! your css is working. anatomy of a css ruleset let's dissect the css code for red paragraph text to understand how it works : the whole structure is called a ruleset. (the term ruleset is often referred to as just rule.) note the names of the individual parts: selector this is the html element name at the start of the ruleset. it defines the element(s) to be styled (in this example, <p> elements). to style a different element, change the selector. declaration ...
...And 4 more matches
Dealing with files - Learn web development
when you're building a website, you need to assemble these files into a sensible structure on your local computer, make sure they can talk to one another, and get all your content looking right before you eventually upload them to a server. dealing with files discusses some issues you should be aware of so you can set up a sensible file structure for your website. ...
...bsite at, test-site/myimage.jpg and then in a different file you try to invoke the image as test-site/myimage.jpg, it may not work. browsers, web servers, and programming languages do not handle spaces consistently. for example, if you use spaces in your filename, some systems may treat the filename as two filenames. some servers will replace the areas in your filenames with "%20" (the character code for spaces in uris), resulting in all your links being broken. it's better to separate words with dashes, rather than underscores: my-file.html vs. my_file.html. the short answer is that you should use a hyphen for your file names. the google search engine treats a hyphen as a word separator but does not regard an underscore that way. for these reasons, it is best to get into the habit of writi...
...our homepage content, that is, the text and images that people see when they first go to your site. using your text editor, create a new file called index.html and save it just inside your test-site folder. images folder: this folder will contain all the images that you use on your site. create a folder called images, inside your test-site folder. styles folder: this folder will contain the css code used to style your content (for example, setting text and background colors). create a folder called styles, inside your test-site folder. scripts folder: this folder will contain all the javascript code used to add interactive functionality to your site (e.g. buttons that load data when clicked). create a folder called scripts, inside your test-site folder. note: on windows computers, you mi...
...And 4 more matches
Test your skills: HTML images - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html images 1 in this task we want you to embed a simple image of some blueberries into the page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html images 1 in this task we want you to embed a simple image of some blueberries into the page. ...
...nd it is in a folder inside the current folder called images. add some alternative text to an appropriate attribute to describe the image, for people that cannot see it. give the <img> element an appropriate width and height so that it displays at the correct aspect ratio, and enough space is left on the page to display it. the image's intrinsic size is 615 x 419 pixels. ...
...And 4 more matches
Test your skills: Multimedia and embedding - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...mbed a simple audio file onto the page. you need to: add the path to the audio file to an appropriate attribute to embed it on the page. the audio is called audio.mp3, and it is in a folder inside the current folder called media. add an attribute to make browsers display some default controls. add some appropriate fallback text for browsers that don't support <audio>. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. multimedia and embedding 2 in this task we want you to mark up a slightly more complex video player, with multiple sources, subtitles, and other features besides. you need to: add an attribute to make browsers display some default controls. add some appro...
...And 4 more matches
General asynchronous programming concepts - Learn web development
ipt. you should understand these concepts before working through the other articles in the module. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand the basic concepts behind asynchronous programming, and how they manifest in web browsers and javascript. asynchronous? normally, a given program's code runs straight along, with only one thing happening at once. if a function relies on the result of another function, it has to wait for the other function to finish and return, and until that happens, the entire program is essentially stopped from the perspective of the user. mac users, for example, sometimes experience this as the spinning rainbow-colored cursor (or "beachball" as it is often ca...
...r something when you could let the other task chug along on another processor core and let you know when it's done. this lets you get other work done in the meantime, which is the basis of asynchronous programming. it is up to the programming environment you are using (web browsers, in the case of web development) to provide you with apis that allow you to run such tasks asynchronously. blocking code asynchronous techniques are very useful, particularly in web programming. when a web app runs in a browser and it executes an intensive chunk of code without returning control to the browser, the browser can appear to be frozen. this is called blocking; the browser is blocked from continuing to handle user input and perform other tasks until the web app returns control of the processor. let's l...
... } console.log(mydate); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); when running the example, open your javascript console then click the button — you'll notice that the paragraph does not appear until after the dates have finished being calculated and the console message has been logged. the code runs in the order it appears in the source, and the later operation doesn't run till the earlier operation has finished running. note: the previous example is very unrealistic. you would never calculate 10 million dates on a real web app! it does, however, serve to give you the basic idea. in our second example, simple-sync-ui-blocking.html (see it live), we simulate something slightly more r...
...And 4 more matches
Test your skills: Conditionals - Learn web development
the aim of this skill test is to assess whether you've understood our making decisions in your code — conditionals article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). conditionals 1 in this task you are provided with two variables: season — contains a string that says what...
... "summer", and if so assigns a string to response that gives the user an appropriate message about the season. if not, it should assign a generic string to response that tells the user we don't know what season it is. to finish off, you should then add another test that checks whether season contains the string "winter", and again assigns an appropriate string to response. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. conditionals 2 for this task you are given three variables: machineactive — contains an indicator of whether the answer machine is switched on or not (true/false) score — contains your score in an imaginary game. this score is fed into the answer mach...
...score of 0 to 19 — "that was a terrible score — total fail!" score of 20 to 39 — "you know some things, but it's a pretty bad score. needs improvement." score of 40 to 69 — "you did a passable job, not bad!" score of 70 to 89 — "that\'s a great score, you really know your stuff." score of 90 to 100 — "what an amazing score! did you cheat? are you for real?" try updating the live code below to recreate the finished example. after you've entered your code, try changing machineactive to true, to see if it works. download the starting point for this task to work in your own editor or in an online editor. conditionals 3 in this task you need to take the code you wrote for the second task, and rewrite the inner if...else if...else to use a switch statement instead. try upda...
...And 4 more matches
Test your skills: Strings - Learn web development
this aim of this skill test is to assess whether you've understood our handling text — strings in javascript and useful string methods articles. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). strings 1 in our first strings task, we start off small. you already have half of a famous...
...ok up the other half of the quote, and add it to the example inside a variable called quoteend. concatenate the two strings together to make a single string containing the complete quote. save the result inside a variable called finalquote. you'll find that you get an error at this point. can you fix the problem with quotestart, so that the full quote displays correctly? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. strings 2 in this task you are provided with two variables, quote and substring, which contain two strings. we would like you to: retrieve the length of the quote, and store it in a variable called quotelength. find the index position where substring appe...
... of the quote, and store it in a variable called quotelength. find the index position where substring appears in quote, and store that value in a variable called index. use a combination of the variables you have and available string properties/methods to trim down the original quote to "i do not like green eggs and ham.", and store it in a variable called revisedquote. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. strings 3 in the next string task, you are given the same quote that you ended up with in the previous task, but it is somewhat broken! we want you to fix and update it, like so: change the casing to correct sentence case (all lowercase, except for upper c...
...And 4 more matches
Adding features to our bouncing balls demo - Learn web development
ant to test your object-building skills by creating a generic shape() object that our balls and evil circle can inherit from. finally, we want to add a score counter to track the number of balls left to capture. the following screenshot gives you an idea of what the finished program should look like: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. creating our new objects first of all, change your existing ball() constructor so that it becomes a shape() constructor and add a new ball() constructor: the shape() constructor should define the x, y, velx, and vely properties in the same way as the ball() constructor did originally, but not the color and size proper...
... ball() constructor's prototype and constructor appropriately. the ball draw(), update(), and collisiondetect() method definitions should be able to stay exactly the same as they were before. you also need to add a new parameter to the new ball() ( ... ) constructor call — the exists parameter should be the 5th parameter, and should be given a value of true. at this point, try reloading the code — it should work just the same as it did before, with our redesigned objects. defining evilcircle() now it's time to meet the bad guy — the evilcircle()! our game is only going to involve one evil circle, but we are still going to define it using a constructor that inherits from shape() to give you some practice. you might want to add another circle to the app later on that can be controlle...
... to update velx/vely; we want to instead change the value of x/y so the evil circle is bounced back onto the screen slightly. adding or subtracting (as appropriate) the evil circle's size property would make sense. setcontrols() this method will add an onkeydown event listener to the window object so that when certain keyboard keys are pressed, we can move the evil circle around. ...
...And 4 more matches
Object prototypes - Learn web development
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 person(first, last, age, gender, interests) { // property and method definitions this.name = { 'first': first, 'last' : last }; this.age = age; this.gender = gender; //...see link in summary above for full definition } we have the...
...ed in an internal property, referred to as [[prototype]] in the specification for the javascript language (see ecmascript). most modern browsers, however, do offer property available called __proto__ (that's 2 underscores either side), which contains the object's constructor's prototype object. for example, try person1.__proto__ and person1.__proto__.__proto__ to see what the chain looks like in code! since ecmascript 2015, you can access an object's prototype object indirectly via object.getprototypeof(obj). the prototype property: where inherited members are defined so, where are the inherited properties and methods defined? if you look at the object reference page, you'll see listed in the left hand side a large number of properties and methods — many more than the number of inherite...
...ifying prototypes let's have a look at an example of modifying the prototype property of a constructor function — methods added to the prototype are then available on all object instances created from the constructor. at this point we'll finally add something to our person() constructor's prototype. go back to our oojs-class-further-exercises.html example and make a local copy of the source code. ...
...And 4 more matches
Website security - Learn web development
) sorts of attacks. the more formal definition of website security is the act/practice of protecting websites from unauthorized access, use, modification, destruction, or disruption. effective website security requires design effort across the whole of the website: in your web application, the configuration of the web server, your policies for creating and renewing passwords, and the client-side code. while all that sounds very ominous, the good news is that if you're using a server-side web framework, it will almost certainly enable "by default" robust and well-thought-out defense mechanisms against a number of the more common attacks. other attacks can be mitigated through your web server configuration, for example by enabling https. finally, there are publically available vulnerability sca...
... threats and how they are mitigated. as you read, note how threats are most successful when the web application either trusts, or is not paranoid enough about the data coming from the browser. cross-site scripting (xss) xss is a term used to describe a class of attacks that allow an attacker to inject client-side scripts through the website into the browsers of other users. because the injected code comes to the browser from the site, the code is trusted and can do things like send the user's site authorization cookie to the attacker. when the attacker has the cookie, they can log into a site as though they were the user and do anything the user can, such as access their credit card details, see contact details, or change passwords. note: xss vulnerabilities have been historically more com...
...lected and persistent, based on how the site returns the injected scripts to a browser. a reflected xss vulnerability occurs when user content that is passed to the server is returned immediately and unmodified for display in the browser. any scripts in the original user content will be run when the new page is loaded. for example, consider a site search function where the search terms are encoded as url parameters, and these terms are displayed along with the results. an attacker can construct a search link that contains a malicious script as a parameter (e.g., http://mysite.com?q=beer<script%20src="http://evilsite.com/tricky.js"></script>) and email it to another user. if the target user clicks this "interesting link", the script will be executed when the search results are displayed. a...
...And 4 more matches
Starting our Svelte Todo list app - Learn web development
t minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: to learn how to create a svelte component, render it inside another component, pass data into it using props, and save its state. ...
... repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/02-starting-our-todo-app or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/02-starting-our-todo-app remember to run npm install && npm run dev to start your app in development mode. repl to code along with us using the repl, start at https://svelte.dev/repl/b7b831ea3a354d3789cefbc31e2ca495?version=3.23.2 todo list app features this is how our todo list app wil look like once it's ready: using this ui our user will be able to: browse their tasks. mark tasks as completed/pending without deleting them. remove tasks. add new tasks. filter tasks by status: all tasks, active tasks...
...st beneath it. making this association gives the list a more informative context, which could help screen reader users better understand the purpose of it. this seems like a good time to talk about how svelte deals with accessibility; let's do that now. svelte accessibility support svelte has a special emphasis on accessibility. the intention is to encourage developers to write more accessible code "by default". being a compiler, svelte can statically analyze our html templates to provide accessibility warnings when components are being compiled. accessibility (shortened to a11y) isn't always easy to get right, but svelte will help by warning you if you write inaccessible markup. for example, if we add an <img> element to our todos.svelte component without its corresponding alt prop: <h1...
...And 4 more matches
Componentizing our Svelte app - Learn web development
ing components. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. you'll need a terminal with node + npm installed to compile and build your app. objective: to learn how to break our app into components and share information among them. ...
...epo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/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 your app in development mode. repl to code along with us using 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...
... but how do you know what should be split into its own component? there are no hard rules for this. ...
...And 4 more matches
Deployment and next steps - Learn web development
k briefly about the pros and cons of using typescript. even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. if you are not interested at all in typescript, you can skip to the next chapter, where we will look at different options for deploying our svelte applications, further resources, and more. ...
...ke this: 504 jul 13 02:43 bundle.css 21782 jul 13 02:43 bundle.js try running npm run build in your app's root directory now. you might get a warning, but you can ignore this for now. our whole app is now just 21 kb — 8.3 kb when gzipped. there are no additional runtimes or dependencies to download, parse, execute, and keep running in memory. svelte analyzed our components and compiled the code to vanilla javascript. a look behind the svelte compilation process by default, when you create a new app with npx degit sveltejs/template my-svelte-project, svelte will use rollup as the module bundler. note: there is also an official template for using webpack and also many community-maintained plugins for other bundlers. in the file package.json you can see that the dev and start scripts...
...e email sent to that address, for security purposes. ...
...And 4 more matches
Git and GitHub - Learn web development
the most popular vcs (at least among web developers) is git, along with github, a site that provides hosting for your repositories and several tools for working with them. this module aims to teach you what you need to know about both of them. ...
...s for working with them. this module aims to teach you what you need to know about both of them. overview vcses are essential for software development: it is rare that you will work on a project completely on your own, and as soon as you start working with other people you start to run the risk of conflicting with each other's work — this is when both of you try to update the same piece of code at the same time. you need to have some kind of mechanism in place to manage the occurences, and help avoid loss of work as a result. when working on a project on your own or with others, you'll want to be able to back up the code in a central place, so it is not lost if your computer breaks. you will also want to be able to roll back to earlier versions if a problem is later discovered. you mi...
...p avoid loss of work as a result. when working on a project on your own or with others, you'll want to be able to back up the code in a central place, so it is not lost if your computer breaks. you will also want to be able to roll back to earlier versions if a problem is later discovered. you might have started doing this in your own work by creating different versions of the same file, e.g. mycode.js, mycode_v2.js, mycode_v3.js, mycode_final.js, mycode_really_really_final.js, etc., but this is really error-prone and unreliable. ...
...And 4 more matches
Adding a new CSS property
see the gecko overview for more information about the style system. this document assumes that you have a specifcation for the property available. issues about how to write such a specification (including things such as whether it is appropriate to use prefixes or when properties should be inherited by default) are not covered here. ...
...d or comma-separated list of values that can be described by the variant_* flags (also in nscssprops.h), you should use css_property_parse_value or css_property_parse_value_list, and set the appropriate variant_* flags in the entry in nscssproplist.h (and maybe also css_property_value_list_uses_commas). otherwise, set the variant entry in the nscssproplist entry to 0. if you need custom parsing code, this can be inserted at one of two different places: you can override the entire property value parsing by using css_property_parse_function, which is generally the right thing to do for shorthand properties. or, preferably, you can still use css_property_parse_value or ..._value_list and just override the value parsing by setting css_property_value_parser_function. you must take the latter a...
...ant_none. if you add a shorthand property, you'll need to use the css_prop_shorthand macro. you'll need to use css_property_parse_function as described above; you can't use the other options for shorthands. and for shorthands you also need to include a subproperty table in nscssprops, whose name must match the "method" argument in the css_prop_shorthand macro. ...
...And 4 more matches
ESLint
meeting these rules before review will help reduce the amount of review time, and the revisions necessary to have a review granted. ...
...meeting these rules before review will help reduce the amount of review time, and the revisions necessary to have a review granted. ...
...meeting these rules before review will help reduce the amount of review time, and the revisions necessary to have a review granted. ...
...And 4 more matches
How to implement a custom autocomplete search component
a newer and slightly simplified mechanism that is used in "toolkit" applications such as firefox and xulrunner. ...
... can happen! so, get a uuid from http://www.famkruithof.net/uuid/uuidgen, for example, and paste it in. basic example for gecko 2.0 and up (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this example is your first best try because: it has no specific logic (it just returns a dummy array of choices) it doesn't care about compatibility with older gecko versions first copy the following javascript code into a file named basic_autocomplete.js into the components directory (or whatever components folder is appropriate in your case): warning: the uuid used below in chrome.manifest and assigned to class_id must be changed before use. const ci = components.interfaces; const cu = components.utils; cu.import('resource://gre/modules/xpcomutils.jsm'); const class_id = components.id('x753d830-ba1...
...= errordescription; this._results = results; this._comments = comments; } providerautocompleteresult.prototype = { _searchstring: "", _searchresult: 0, _defaultindex: 0, _errordescription: "", _results: [], _comments: [], /** * @return {string} the original search string */ get searchstring() { return this._searchstring; }, /** * @return {number} the result code of this result object, either: * result_ignored (invalid searchstring) * result_failure (failure) * result_nomatch (no matches found) * result_success (matches found) */ get searchresult() { return this._searchresult; }, /** * @return {number} the index of the default item that should be entered if * none is selected */ get defaultindex() { ...
...And 4 more matches
NetUtil.jsm
the netutil.jsm javascript code module provides easy-to-use apis for performing common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] acallback) void asyncfetch(asource, acallback) nsichannel newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attri...
... asink, acallback ); parameters asource the input stream from which to read the source data. this must be an nsiinputstream based object. asink the output stream to which to copy the data. this must be an nsioutputstream based object. acallback an optional function that will be called when the copy operation is completed. the callback receives a single parameter: the nsresult status code for the copy operation. return value returns the nsiasyncstreamcopier object that is handling the copy. exceptions thrown this method throws an exception with the message "must have a source and a sink" if either asource or asink is null. example this example writes a string to a file; it comes from the test suite for the netutil module. var file = cc["@mozilla.org/file/directory_service;...
...(ci.nsifileoutputstream); ostream.init(file, -1, -1, 0); // finally, we need an input stream to take data from. const test_data = "this is a test string"; let istream = cc["@mozilla.org/io/string-input-stream;1"]. createinstance(ci.nsistringinputstream); istream.setdata(test_data, test_data.length); netutil.asynccopy(istream, ostream, function(aresult) { if (!components.issuccesscode(aresult)) { // an error occurred! } }) asyncfetch() the asyncfetch() method opens an input source, asynchronously, and gives an nsiinputstream containing the data obtained to the callback provided. the callback may then consume data from the input stream passed to the callback. note: prior to gecko 2, the input source was required to be specified as an nsichannel. note: support for ...
...And 4 more matches
Midas
midas can be enabled via javascript on an html document. when midas is enabled, the document becomes editable by the user. scripting for midas is based on the dhtml commands supported by internet explorer. internet explorer supports the ability to make an entire document editable by setting the designmode property of the document object; this is how midas is invoked in gecko. internet explorer also supports the ability to edit specific elements using the contenteditable attribute; starting with firefox 3, gecko also supports contenteditable. once midas is invoked, a few more methods of the document object become available. you can try demo of this here. ...
... determines whether the current selection is in an indetermined state. document.querycommandstate determines whether the given command has been executed on the current selection. document.querycommandvalue determines the current value of the document, range, or current selection for the given command. supported commands command value description backcolor a color code. this command will set the background color of the document. bold if there is no selection, the insertion point will set bold for subsequently typed characters. if there is a selection and all of the characters are already bold, the bold will be removed. otherwise, all selected characters will become bold. contentreadonly this command will make the edito...
... web page. copy if there is a selection, this command will copy the selection to the clipboard. if there isn't a selection, nothing will happen. note: this command won't work without setting a pref or using signed js. see: more about security preferences note: the shortcut key will automatically trigger this command (typically accel-c) with or without the signed js or any code on the page to handle it. createlink a uri. this command will not do anything if no selection is made. if there is a selection, a link will be inserted around the selection with the url parameter as the href of the link. cut if there is a selection, this command will copy the selection to the clipboard and remove the selection from the edit control. if there isn...
...And 4 more matches
NSS Key Log Format
. (see bug 1188657.) notably, debian does not have this option enabled, see debian bug 842292. this key log file is a series of lines. comment lines begin with a sharp character ('#') and are ignored. secrets follow the format <label> <space> <clientrandom> <space> <secret> where: <label> describes the following secret. ...
...secrets follow the format <label> <space> <clientrandom> <space> <secret> where: <label> describes the following secret. <clientrandom> is 32 bytes random value from the client hello message, encoded as 64 hexadecimal characters. <secret> depends on the label (see below). ...
...ollowing secret. <clientrandom> is 32 bytes random value from the client hello message, encoded as 64 hexadecimal characters. <secret> depends on the label (see below). ...
...And 4 more matches
nss tech note4
also, this document does not attempt to be an exhaustive survey of all possible ways to do a certain task; it merely tries to show a certain way. ...
... background on cert extensions an extension has the following attributes object id (oid) : a unique oid represents an algorithm, a mechanism, a piece of information, etc. examples: x500 rsa encryption, certificate basic constraints, pkcs#7 digested data, etc. there is a long list of pre-defined oids, and new ones can be...
...s*/ static const unsigned char myoid[] = { 0xff, 0xff, 0xff, 0xff, .... ...
...And 4 more matches
NSS tools : certutil
extension oid. -e check a certificate's signature during the process of validating a certificate. --email email-address specify the email address of a certificate to list. used with the -l command option. --extgeneric oid:critical-flag:filename[,oid:critical-flag:filename]... ...
...t. used with the -l command option. --extgeneric oid:critical-flag:filename[,oid:critical-flag:filename]... add one or multiple extensions that certutil cannot encode yet, by loading their encodings from external files. · oid (example): 1.2.3.4 · critical-flag: critical or not-critical · filename: full path to a file containing an encoded extension -f password-file specify a file that will automatically supply the password to include in a certificate or to access a certificate database. this is a plain-text file containing one password. be sure to prevent unauthorized access to this file. -g keysize set a key size to use when generating new public and ...
... trust attributes to modify in an existing certificate or to apply to a certificate when creating it or adding it to a database. there are three available trust categories for each certificate, expressed in the order ssl, email, object signing for each trust setting. ...
...And 4 more matches
NSS tools : pk12util
binary) form. this must be saved as a der file. the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. -v enable debug logging when importing. -w p12filepasswordfile specify the text file containing the pkcs #12 file password. -w p12filepassword specify the pkcs #12 file password. ...
...s in the p12 file. -v enable debug logging when importing. -w p12filepasswordfile specify the text file containing the pkcs #12 file password. -w p12filepassword specify the pkcs #12 file password. ...
... containing the pkcs #12 file password. -w p12filepassword specify the pkcs #12 file password. ...
...And 4 more matches
NSS reference
pkcs5getpbealgorithm sec_pkcs5isalgorithmpbealg pkcs #12 functions based on "archived pkcs #12 functions documentation." used to exchange data such as private keys and certificates between two parties. ...
... pkcs #12 functions based on "archived pkcs #12 functions documentation." used to exchange data such as private keys and certificates between two parties. ...
...ed on "archived pkcs #12 functions documentation." used to exchange data such as private keys and certificates between two parties. ...
...And 4 more matches
SpiderMonkey 24
these release notes are an incomplete draft and were initially seeded from the spidermonkey 17 release notes, so they're not necessarily complete or fully accurate. the mozilla javascript team is pleased to announce the release of spidermonkey 24. you can download full source code here: https://ftp.mozilla.org/pub/mozilla.org/js/mozjs-24.2.0.tar.bz2 (sha1: ce779081cc11bd0c871c6f303fc4a0091cf4fe66) spidermonkey 24 is the javascript engine that shipped in firefox 24. it continues to improve performance over previous spidermonkey releases, with a significantly improved garbage collector, a new jit compilation mode, and other features. it also contains new language and api features described in detail below. please let us know about your experiences with this release by posting in the mozill...
...— dec 16, 2013 the download url still available, but spidermonkey not release alone! get it here mozilla-esr24 if the download url is outdate you will find it in "firefox extended support release 24" package on hg release platform support spidermonkey 24 is supported on all the platforms where firefox 24 runs. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. ...
...it's the same language, just not as fast. ...
...And 4 more matches
Mork
Mozilla › Tech › Mork
mork structure mork is a schema-less database format. ...
...mork structure mork is a schema-less database format. ...
...mork structure mork is a schema-less database format. ...
...And 4 more matches
Finishing the Component
in urls from loading are not frozen, and there is still some debate about how exactly this functionality should be exposed to embedders and component developers, so the apis are not ready to be published. this puts you in the same situation as many developers using mozilla - you want to use some specific functionality, but the interfaces seem to change on a daily basis. all of the mozilla source code is publicly available, and interfaces can be used easily enough. grab the right headers, use the component or 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 ...
...when it shuts down. * * @status frozen */ these frozen interfaces and functions are part of the gecko sdk. the rule of thumb is that interfaces outside of the sdk are considered "experimental" or unfrozen. see the following sidebar for information about how frozen and unfrozen interfaces can affect your component development, and for technical details about how interface changes beneath your code can cause havoc. the danger of using unfrozen interfaces suppose that you need to use the interface nsifoo that isn't frozen. you build your component using this interface, and it works great with the version of gecko that you have tested against. however, some point in the future, the nsifoo interface requires a major change, and methods are reordered, some are added, others are removed. more...
...an integer, 10. this works fine in any gecko installation where a contract guarantees that the interface that was compiled against has the same signature. however, when this same component is used in a gecko installation where this interface has changed, the method testa does not exist in the nsifoo interface; the first entry in the v-table is in fact isprime(). when this method call is made, the code execution treats the isprime method as testa. needless to say, this is a bad thing. furthermore, there is no way easy way to realize this error at runtime. gecko developers could change the interface's iid, and some do. this can prevent many errors like this. but unfrozen interfaces are not supported in any formal way, and relying upon a different iid for any change in the interface is not a g...
...And 4 more matches
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
it is not that sequence of characters, though: the characters may not all be available when you read from the stream. think of a water tank with a spout: the tank may be full, or it may be half-full, or it may be empty. the spout controls how much water you can get out of the tank at a time. the spout is a source of water. if we think of the water as data, then the spout represents an input stream: a controller for data coming out of something. at the same time, there may be some way to put water into the tank - say, a main water line. that water line represents an output stream: a controller for data going into something. ...
...g the stream's .finish() method overwrites the original file with the new file. using streams in c++ using streams in javascript input streams input streams are not scriptable - you cannot directly call .read() on them, for example. to solve this, there is a special nsiscriptableinputstream interface and "scriptable stream" wrapper. if you have an input stream called nativestream, you can use code like this: var stream = components.classes["@mozilla.org/scriptableinputstream;1"] .createinstance(components.interfaces.nsiscriptableinputstream); stream.init(nativestream); the stream provides .read(count), .available(), and .close() methods. output streams output streams are usually scriptable: you can call .write(chars, chars.length) as you wish. however, it is usu...
...ream); var data = "hello world"; instream.setdata(data, data.length); while (instream.available()) { outstream.writefrom(instream, instream.available()); } note this is an inefficient example: the only important part is how to feed the output stream. this is also a synchronous (blocking) operation, so if you're in javascript, consider using netutil.jsm as described below. a note about unicode strings versus nsiinputstream nsiinputstream and nsioutputstream work with 8-bit characters. however, javascript strings contain 16-bit characters. this can mean if you have characters beyond ascii code 255, you risk losing data using nsstringstream, for example. to get an input stream for javascript strings safely, try this. var converter = components.classes["@mozilla.org/intl/scriptableun...
...And 4 more matches
nsIAccessibleText
long read only. constants text offset constants constant value description text_offset_end_of_text -1 will be treated as the equal to the end of the text. text_offset_caret -2 will be treated as the caret position. text boundary constants constant value description boundary_char 0 boundary_word_start 1 boundary_word_end 2 boundary_sentence_start 3 do not use in new code. boundary_sentence_end 4 do not use in new code. boundary_line_start 5 boundary_line_end 6 boundary_attribute_range 7 coordinate type constants 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. constant value description coord_ty...
...around the given offset. this accessible get return the dom node and layout frame with the uniform attributes for this range of text. nsiaccessible getattributerange( in long offset, out long rangestartoffset, out long rangeendoffset ); parameters offset rangestartoffset rangeendoffset return value getcharacteratoffset() it would be better to return an unsigned long here, to allow unicode chars > 16 bits. wchar getcharacteratoffset( in long offset ); parameters offset return value getcharacterextents() returns the bounding box of the specified position. the virtual character after the last character of the represented text, that is the one at position length is a special case. it represents the current input position and will therefore typically be queried by at more often ...
...enced character. coordtype specifies if the coordinates are relative to the screen or to the parent window (see constants declared in nsiaccessiblecoordinatetype.constants. ...
...And 4 more matches
nsILocalFile
roduced gecko 1.0 deprecated gecko 14 inherits from: nsifile last changed in gecko 1.0 implemented by: @mozilla.org/file/local;1. ...
...ateinstance(components.interfaces.nsilocalfile); method overview void appendrelativenativepath(in acstring relativefilepath); native code only! void appendrelativepath(in astring relativefilepath); acstring getrelativedescriptor(in nsilocalfile fromfile); void initwithfile(in nsilocalfile afile); void initwithnativepath(in acstring filepath); native code only! void initwithpath(in astring filepath); void launch(); prlibrarystar load(); native code only! file openansifiledesc(in string mode); native code only! prfiledescstar opennsprfiledesc(in long flags, in long mode); native code only! void reveal(); void setrelativedescriptor(in nsilocalfile fromfile, in acstring relativedesc); ...
... persistentdescriptor acstring on some platforms, the value of nsifile.path may be insufficient to uniquely identify the file on the local file system. the persistent descriptor is intended to be used whenever a nsilocalfile needs to be serialized to disk and later recovered. this string is not intended for display to users. note: the value of the followlinks attribute is not encoded in the persistent descriptor. constants constant value description delete_on_close 0x80000000 optional parameter used by opennsprfiledesc(). methods native code only! appendrelativenativepath appends a relative, native character encoding, path to the current path of the nsilocalfile object. void appendrelativenativepath( in acstring rel...
...And 4 more matches
nsIMsgDBHdr
flags of the message. see nsmsgmessageflags for a list of what may or may not be set on this message. note that the elided flag should not be set on messages, as it is a flag strictly dealing with the database view. threadid nsmsgkey indicates the id of the thread to which this message belongs. this property does not change the state of any thread objects, so only internal database code should set this attribute. messagekey nsmsgkey indicates the database key for this message. setting this property will probably result in an inconsistent database representation, so only internal database code should set this attribute. threadparent nsmsgkey indicates the parent of this message in its thread. if this is the root of the thread, it will return nsmsgkey...
... header. author string indicates the author of this message; the equivalent header is the from: header. the value here will effectively be the unparsed version of the header. subject string indicates the subject of this message; the equivalent header is the subject: header. the value here will effectively be the unparsed header content, so it will contain full mime-encoded syntax. recipients string indicates the recipients of the message. this is the first non-empty value of the to: header, cc: header, or newsgroup: header. the value here will effectively be the unparsed header content; it may be easier to set this using setrecipientsarray. numreferences unsigned short readonly: indicates the number of references this header has. ...
... recipients string indicates the recipients of the message. this is the first non-empty value of the to: header, cc: header, or newsgroup: header. the value here will effectively be the unparsed header content; it may be easier to set this using setrecipientsarray. numreferences unsigned short readonly: indicates the number of references this header has. mime2decodedauthor astring readonly: indicates the author of this message. the value here will have been decoded by the mime converter service. mime2decodedsubject astring readonly: indicates the subject of this message. the value here will have been decoded by the mime converter service. mime2decodedrecipients astring readonly: indicates the recipients of this message. th...
...And 4 more matches
nsIMsgDatabase
nsisimpleenumerator enumeratemessages(); nsisimpleenumerator enumeratethreads(); void synccounts; nsimsgthread getthreadcontainingmsghdr(in nsimsgdbhdr msghdr); void markhdrread(in nsimsgdbhdr msghdr, in boolean bread, in nsidbchangelistener instigator); void markhdrreplied(in nsimsgdbhdr msghdr, in boolean breplied, in nsidbchangelistener instigator); void markhdrmarked(in ns...
... void markthreadignored(in nsimsgthread thread, in nsmsgkey threadkey, in boolean bignored, in nsidbchangelistener instigator); void markthreadwatched(in nsimsgthread thread, in nsmsgkey threadkey, in boolean bwatched, in nsidbchangelistener instigator); void markheaderkilled(in nsimsgdbhdr msg, in boolean bignored, in nsidbchangelistener instigator); boolean isread(in nsmsgkey key);...
... void deletemessage(in nsmsgkey key, in nsidbchangelistener instigator, in boolean commit); void deleteheader(in nsimsgdbhdr msghdr, in nsidbchangelistener instigator,in b...
...And 4 more matches
nsIMsgHeaderParser
mma-separated list of just the 'mailbox' portions. if any of the addresses doesn't have a mailbox, then the user name is used instead. autf8string extractheaderaddressmailboxes( in string line ); parameters line the header line to parse. return value a comma-separated list of just the mailbox parts of the addresses. exceptions thrown missing exception missing description native code only!extractheaderaddressnames given a string which contains a list of header addresses, returns a comma-separated list of just the 'user name' portions. if any of the addresses doesn't have a name, then the mailbox is used instead. autf8string extractheaderaddressnames( in string line ); parameters line the header line to parse. return value a comma-separated list of just the name ...
...urns a comma-separated list of just the 'user name' portions. if any of the addresses doesn't have a name, then the mailbox is used instead. autf8string extractheaderaddressnames( in string line ); parameters line the header line to parse. return value a comma-separated list of just the name parts of the addresses. exceptions thrown missing exception missing description native code only!extractheaderaddressname like extractheaderaddressnames(), but only returns the first name in the list, if there is more than one. autf8string extractheaderaddressname( in string line ); parameters line the header line to parse. return value the first name found in the list exceptions thrown missing exception missing description makefulladdress() given an e-mail address ...
...s them together into a single string, doing all the necessary quoting. astring makefulladdress( in astring aname, in astring aaddress ); parameters aname the name of the sender. this should be in utf-8. aaddress the address of the sender. this should be in utf-8. return value a string of the form name <address>. exceptions thrown missing exception missing description native code only!makefulladdressstring given an e-mail address and a person's name, cons them together into a single string, doing all the necessary quoting (const char* version). string makefulladdressstring( in string aname, in string aaddress ); parameters aname the name of the sender. this should be in utf-8. aaddress the address of the sender. this should be in utf-8. return value a s...
...And 4 more matches
nsISHEntry
boolean hasdetachededitor(); violates the xpcom interface guidelines boolean hasdynamicallyaddedchild(); boolean isd...
...orts cachekey, in acstring contenttype, in nsisupports owner, in unsigned long long docshellid, in boolean dynamiccreation); native code only! nsdocshelleditordataptr forgeteditordata(); violates the xpcom interface guidelines nsicontentviewer getanycontentviewer(out nsishentry ownerentry); void getscrollposition(out long x, out long y); void getviewerbounds(in nsintrect bounds); native code only! boolean hasdetachededitor(); violates the xpcom interface guidelines boolean hasdynamicallyaddedchild(); boolean isdynamicallyadded(); void seteditordata(in nsdocshelleditordataptr adata); violates the xpcom interface guidelines void setissubframe(in boolean aflag); void setscrollposition(in long x, in long y); void settitle(in astring atitle); void setuniquedocidentifi...
... contenttype acstring indicates the content-type of the document that this is a session history entry for. contentviewer nsicontentviewer content viewer, for fast restoration of presentation. docidentifier unsigned long long an integer that shou...
...And 4 more matches
xptcall FAQ
what is xptcall? xptcall is a small low level xpcom method call library. it is implemented using platform specific c/c++ and assembly language code. it is used to facilitate cross language and cross thread method calls. porting this code is required in order to make mozilla run on any given platform. why does xptcall exist? xptcall exists for two reasons: to support invoking arbitrary methods on xpcom interfaces. to support dynamically impersonating any xpcom interface. both of these facilities are required by xpconnect. these facilities are also used by xpcom/proxy. it may also be used by other subsystems in the future. the xptcall approach was chosen over an approach that would have required generating stub code for calling and implementing all interfaces. though the chosen...
...lly impersonating any xpcom interface. both of these facilities are required by xpconnect. these facilities are also used by xpcom/proxy. it may also be used by other subsystems in the future. the xptcall approach was chosen over an approach that would have required generating stub code for calling and implementing all interfaces. though the chosen approach requires some core platform specific code, it has minimal footprint and is extendable to work with any valid xpcom interface without requiring additional per platform compiled code to be distributed. what does xptcall really do? the core invoke function has the declaration: xptc_public_api(nsresult) xptc_invokebyindex(nsisupports* that, pruint32 methodindex, pruint32 paramcount, ...
...com interface. this is done by providing a vtbl full of generic function stubs in xptcall. these stubs forward calls to a shared function whose job it is to use the typelib information to extract the parameters from the platform specific calling convention to build an array of variants to hold the parameters and then call an inherited method which can then do whatever it wants with the call. ...
...And 4 more matches
Xptcall Porting Guide
overview xptcall is a library that supports both invoking methods on arbitrary xpcom objects and implementing classes whose objects can impersonate any xpcom interface. it does this using platform specific assembly language code. this code needs to be ported to all platforms that want to support xptcall (and thus mozilla). the tree mozilla/xpcom/reflect/xptcall +--public // exported headers +--src // core source | \--md // platform specific parts | +--mac // mac ppc | +--unix // all unix | \--win32 // win32 | +--test // simple tests to get started \--tests // full tests via api porters are free to create subdirectories under the base md directory for their given platforms and to integrate into the build system as appropriate for their platf...
... as appropriate for their platform. theory of operation there are really two pieces of functionality: invoke and stubs... the invoke functionality requires the implementation of the following on each platform (from xptcall/public/xptcall.h): xptc_public_api(nsresult) ns_invokebyindex(nsisupports* that, pruint32 methodindex, pruint32 paramcount, nsxptcvariant* params); calling code is expected to supply an array of nsxptcvariant structs. these are discriminated unions describing the type and value of each parameter of the target function. the platform specific code then builds a call frame and invokes the method indicated by the index methodindex on the xpcom interface that. here are examples of this implementation for win32 and linux x86, netbsd x86, and freebsd. these im...
...porters of this functionality implement ...
...And 4 more matches
CData
ing identifying the data. string tostring(); parameters none. return value a string identifying the data. methods available on string objects these methods must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character. readstring() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, a typeerror exception is thrown. string readstring(); parameters none. return value a new string object that is a copy of the original string contents. readstringreplacemalformed() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid en...
...d as utf-8. if the 8-bit string contains invalid encoded character, a typeerror exception is thrown. string readstring(); parameters none. return value a new string object that is a copy of the original string contents. readstringreplacemalformed() converts a character array to a javascript string. 8-bit strings are assumed to be encoded as utf-8. if the 8-bit string contains invalid encoded character, no exception is thrown. string readstringreplacemalformed(); parameters none. return value a new string object that is a copy of the original string contents. invalid encoded characters will be replaced by �(u+fffd). here is a method to read "malformed", it attempts to do readstring on it, if it errors then it tries to read it in another way, so this is an alternative to rea...
... var assumption_max_len = known_len ? ...
...And 4 more matches
Set a breakpoint - Firefox Developer Tools
at this point you can do useful things like studying the value of different variables at that point, allowing you to work out why a problem is occurring. ...
...at this point you can do useful things like studying the value of different variables at that point, allowing you to work out why a problem is occurring. ...
...ext menu over a line number. there are a few options available here: add breakpoint: add a standard unconditional breakpoint at this line number (see below). add condition: add a condition and create a conditional breakpoint (see below). add log: add a log point, which logs a value to your console rather than pausing execution as a breakpoint does. continue to here: when stepping through code, this option tells the debugging to continue execution through to this point. unconditional breakpoints an unconditional breakpoint is one where the code will always pause execution when it is reached. you can set an unconditional breakpoint using the context menu (see above), or by: clicking on the line number for the line you want to break at in the source pane. highlighting the line you...
...And 4 more matches
Debugger.Memory - Firefox Developer Tools
global that this object is allocated within the scope of. given a debugger.object instancedobj referring to some object, dobj.allocationsite returns a saved call stack indicating wheredobj’s referent was allocated. allocation logging ifdbg is a debugger instance, and dbg.memory.trackingallocationsites is set to true, then the javascript engine logs each object allocated bydbg’s debuggee code. you can retrieve the current log by calling dbg.memory.drainallocationslog. you can control the limit on the log’s size by setting dbg.memory.maxallocationsloglength. censuses a census is a complete traversal of the graph of all reachable memory items belonging to a particular debugger‘s debuggees. it produces a count of those items, broken down by various criteria. ifdbg is a debugger ins...
... than [maxallocationsloglength][#max-alloc-log] allocations since the last time [drainallocationslog][#drain-alloc-log] was called and some data has been lost. returns false otherwise. debugger.memory handler functions similar to debugger’s handler functions, debugger.memory inherits accessor properties that store handler functions for spidermonkey to call when given events occur in debuggee code. unlike debugger‘s hooks, debugger.memory’s handlers’ return values are not significant, and are ignored. the handler functions receive the debugger.memory’s owning debugger instance as their this value. the owning debugger’s uncaughtexceptionhandler is still fired for errors thrown in debugger.memory hooks. on a new debugger.memory instance, each of these properties is initially unde...
... analysis may yield surprising results, because browser implementation details that are transparent to content javascript often have visible effects on memory consumption. web developers need to know their pages’ actual memory consumption on real browsers, so it is correct for the tool to expose these behaviors, as long as it is done in a way that helps developers make decisions about their own code. this section covers some areas where firefox’s actual behavior deviates from what one might expect from the specified behavior of the web platform. objects spidermonkey objects usually use less memory than the naïve “table of properties with attributes” model would suggest. for example, it is typical for many objects to have identical sets of properties, with only the properties’ val...
...And 4 more matches
DataTransfer.types - Web APIs
some values that are not mime types are special-cased for legacy reasons (for example "text"). syntax datatransfer.types; return value an array of the data formats used in the drag operation. each format is string. ...
....items != null) { for (var i=0; i < ev.datatransfer.items.length; i++) { console.log("... ...
... for (var i=0; i < ev.datatransfer.items.length; i++) { console.log("... ...
...And 4 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
<table> element using tbl.appendchild(tblbody); next, we attach the <table> element to its parent <body> element using body.appendchild(tbl); remember this technique. you will use it frequently in programming for the w3c dom. first, you create elements from the top down; then you attach the children to the parents from the bottom up. here's the html markup generated by the javascript code: ... <table border="2"> <tbody> <tr><td>cell is row 0 column 0</td><td>cell is row 0 column 1</td></tr> <tr><td>cell is row 1 column 0</td><td>cell is row 1 column 1</td></tr> </tbody> </table> ... here's the dom object tree generated by the code for the <table> element and its child elements: you can build this table and its internal child elements by using just a few dom methods. remember...
...in the <table> tree of figure 1 the element <table> has one child: the element <tbody>. <tbody> has two children. each <tbody>'s child (<tr>) has two children (<td>). finally, each <td> has one child: a text node. ...
..., if you want to create a new <p> element as a child of the <body> element, you can use the mybody in the previous example and append a new element node. to create a node simply call document.createelement("tagname"). for example: mynewptagnode = document.createelement("p"); mybody.appendchild(mynewptagnode); removing nodes with the removechild(..) method nodes can be removed. the following code removes text node mytextnode (containing the word "world") from the second <p> element, myp. myp.removechild(mytextnode); text node mytextnode (containing the word "world") still exists. the following code attaches mytextnode to the recently created <p> element, mynewptagnode. mynewptagnode.appendchild(mytextnode); the final state for the modified object tree looks like this: creating a ...
...And 4 more matches
HTMLBodyElement - Web APIs
ext. htmlbodyelement.vlink is a domstring that represents the color of visited links. methods no specific methods; inherits methods from its parent, htmlelement, and from windoweventhandlers. event handlers no specific event handlers; inherits event handlers from its parent, htmlelement and from windoweventhandlers. ...
...its methods from its parent, htmlelement, and from windoweventhandlers. event handlers no specific event handlers; inherits event handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. ...
...nt handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. windoweventhandlers.onbeforeunload is an eventhandler representing the code to be called when the beforeunload event is raised. windoweventhandlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. windoweventhandlers.onlanguagechange is an eventhandler representing the code to be called when the languagechange event is raised. windoweventhandlers.onmessage is an eventhandler called whenever an object receives...
...And 4 more matches
HTMLFrameSetElement - Web APIs
structured as a comma-seperated list specifing the height of each column inside a frameset. methods no specific method; inherits methods from its parent, htmlelement and from windoweventhandlers. event handlers no specific event handler; inherits event handlers from its parent, htmlelement and from windoweventhandlers. ...
...erits methods from its parent, htmlelement and from windoweventhandlers. event handlers no specific event handler; inherits event handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. ...
...nt handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. windoweventhandlers.onbeforeunload is an eventhandler representing the code to be called when the beforeunload event is raised. windoweventhandlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. ...
...And 4 more matches
IDBObjectStoreSync - Web APIs
ta, which cannot change once it is created. methods add() stores the given value into this object store, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this method can raise a idbdatabaseexception with the following codes: value the value to store into the index. key a key to use for identifying the record. any the key for the stored record. constraint_err if a record exists in this index with a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. data_err if this object sto...
...y created index. get() retrieves and returns the value from this object store for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the value retrieved from the object store. exceptions this method can raise a idbdatabaseexception with the following codes: serial_err if the data being stored could not be deserialized by the internal structured cloning algorithm. not_found_err if no record exists in this index for the given key. opencursor() creates a cursor over the records of this object store. the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the recor...
... includes all the records. cursorsync opencursor ( in optional keyrange range, in optional unsigned short direction ) raises (databaseexception); parameters range the key range to use as the cursor's range. direction the cursor's required direction. returns idbindexsync an object for accessing the index. exceptions this method can raise a databaseexception with the following code: not_found_err if no records exist in this index for the requested key range. openindex() opens the index with the given name, using the mode of the current transaction. idbindexsync openindex ( in domstring name ) raises (idbdatabaseexception); parameters name the name of the index to open. returns idbindexsync an object to access the index. exceptions this method ca...
...And 4 more matches
KeyboardEvent - Web APIs
on the right side of the keyboard. examples include the right shift key and the right alt key (option on a mac keyboard). dom_key_location_numpad 0x03 the key is located on the numeric keypad, or is a virtual key associated with the numeric keypad if there's more than one place the key could originate from. the numlock key does not fall into this group and is always encoded with the location dom_key_location_standard. examples include the digits on the numeric keypad, the keypad's enter key, and the decimal point on the keypad. properties this interface also inherits properties of its parents, uievent and event. keyboardevent.altkey read only returns a boolean that is true if the alt ( option or ⌥ on os x) key was active when the key even...
...tion_standard. examples include the digits on the numeric keypad, the keypad's enter key, and the decimal point on the keypad. properties this interface also inherits properties of its parents, uievent and event. keyboardevent.altkey read only returns a boolean that is true if the alt ( option or ⌥ on os x) key was active when the key event was generated. keyboardevent.code read only returns a domstring with the code value of the physical key represented by the event. warning: this ignores the user's keyboard layout, so that if the user presses the key at the "y" position in a qwerty keyboard layout (near the middle of the row above the home row), this will always return "keyy", even if the user has a qwertz keyboard (which would mean the user expects a "z" and a...
... should use the keyboardevent() constructor. keyboardevent.initkeyboardevent() initializes a keyboardevent object. this is now deprecated. you should instead use the keyboardevent() constructor. obsolete properties keyboardevent.char read only returns a domstring representing the character value of the key. ...
...And 4 more matches
MediaSource.endOfStream() - Web APIs
ample, you might have a function that handles media chunk requests, separate from other network requests. when you make an xmlhttprequest call for a media chunk, and onabort or onerror triggers, you might want to call endofstream('network'), display a descriptive message in the ui, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: terminates playback and signals that a decoding error has occured. this can be used to indicate that a parsing error has occured while fetching media data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode. return value undefined exceptions exception explanation invalidstateerror mediasource.readystate is not e...
...al to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. ...
...ffer objects in mediasource.sourcebuffers are being updated (i.e. ...
...And 4 more matches
MediaSource.isTypeSupported() - Web APIs
user agent. that is, if it can successfully create sourcebuffer objects for that mime type. if the returned value is false, then the user agent is certain that it cannot access media of the specified format. syntax var isitsupported = mediasource.istypesupported(mimetype); parameters mimetype the mime media type that you want to test support for in the current browser. this may include the codecs parameter to provide added details about the codecs used within the file. return value a boolean which is true if the browser feels that it can probably play media of the specified type. this is not a guarantee, however, and your code must be prepared for the possibility that the media will not play correctly if at all. a value of false is a guarantee that media of the given type will not pl...
...dia files are complex, intricate constructs with far too many subtle variations to be absolutely certain of anything until you actually use the contents of the media. ...
...s with far too many subtle variations to be absolutely certain of anything until you actually use the contents of the media. ...
...And 4 more matches
RTCPeerConnection - Web APIs
alingstate enum; these values describe the state of the signaling process on the local end of the connection while connecting or reconnecting to another peer. see signaling in lifetime of a webrtc session for more details about the signaling process.event handlersalso inherits event handlers from: eventtargetonaddstream the rtcpeerconnection.onaddstream event handler is a property containing the code to execute when the addstream event, of type mediastreamevent, is received by this rtcpeerconnection. such an event is sent when a mediastream is added to this connection by the remote peer. the event is sent immediately after the call setremotedescription() and doesn't wait for the result of the sdp negotiation.onconnectionstatechangethe rtcpeerconnection.onconnectionstatechange property specifi...
...onicegatheringstatechange property is an eventhandler which specifies a function to be called when the icegatheringstatechange event is sent to an rtcpeerconnection instance. ...
... event handler is a property containing the code to execute when the identityresult event, of type rtcidentityevent, is received by this rtcpeerconnection. such an event is sent when an identity assertion is generated, via getidentityassertion() or during the creation of an offer or an answer.onidpassertionerror the rtcpeerconnection.onidpassertionerror event handler is a property containing the code to execute whent the idpassertionerror event, of type rtcidentityerrorevent, is received by this rtcpeerconnection. ...
...And 4 more matches
ReadableStreamDefaultReader.read() - Web APIs
ream has no owner. examples example 1 - simple example this example shows the basic api usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example. in this example stream is a previously-created custom readablestream. it is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui as an array of utf-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been rece...
.../ read some more, and call this function again return reader.read().then(processtext); }); } example 2 - handling text line by line this example shows how you might fetch a text file and handle it as a stream of text lines. it deals with stream chunks not ending on line boundaries and converting from uint8array to strings. ...
...and call this function again return reader.read().then(processtext); }); } example 2 - handling text line by line this example shows how you might fetch a text file and handle it as a stream of text lines. it deals with stream chunks not ending on line boundaries and converting from uint8array to strings. ...
...And 4 more matches
SVGLengthList - Web APIs
description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svglength newitem) svglength clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previo...
... clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svglength returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. except...
...sed when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svglength returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svglength newitem, in unsigned long index) svglength inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is...
...And 4 more matches
SVGNumberList - Web APIs
scription numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgnumber newitem) svgnumber clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous l...
... clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgnumber returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exc...
...hen the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgnumber returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgnumber newitem, in unsigned long index) svgnumber inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list befor...
...And 4 more matches
SVGPathSegList - Web APIs
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) svgpathseg clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is remove...
...isting current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. getitem(in unsigned long index) svgpathseg returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item i...
... getitem(in unsigned long index) svgpathseg returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. insertitembefore(in svgpathseg newitem, in unsigned long index) svgpathseg inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed ...
...And 4 more matches
SVGPointList - Web APIs
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) svgpoint clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is al...
...ting current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgpoint returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in t...
...e object itself is read only. getitem(in unsigned long index) svgpoint returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgpoint newitem, in unsigned long index) svgpoint inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it ...
...And 4 more matches
SVGStringList - Web APIs
ned long the number of items in the list. length unsigned long a mirror of the value in numberofitems, for consistency with other interfaces. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in domstring newitem) domstring clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its prev...
...clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) domstring returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exc...
...hen the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) domstring returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in domstring newitem, in unsigned long index) domstring inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it ...
...And 4 more matches
Using server-sent events - Web APIs
this is one-way connection, so you can't send events from a client to a server. receiving events from the server the server-sent event api is contained in the eventsource interface; to open a connection to the server to begin receiving events from it, create a new eventsource object with the url of a script that generates the events. ...
... you can also listen for events with addeventlistener(): evtsource.addeventlistener("ping", function(event) { const newelement = document.createelement("li"); const time = json.parse(event.data).time; newelement.innerhtml = ...
...at do not have an event field on them) and appends the message text to a list in the document's html. you can also listen for events with addeventlistener(): evtsource.addeventlistener("ping", function(event) { const newelement = document.createelement("li"); const time = json.parse(event.data).time; newelement.innerhtml = "ping at " + time; eventlist.appendchild(newelement); }); this code is similar, except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the json in the data field and outputs that information. when not used over http/2, sse suffers from a limitation to the maximum number of open connections, which can be especially painful when opening multiple tabs, as the limit is per browser and is se...
...And 4 more matches
SourceBuffer - Web APIs
iddle">sourcebuffer</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties sourcebuffer.appendwindowend controls the timestamp for the end of the append window. sourcebuffer.appendwindowstart controls the timestamp for the start of the append window. this is a timestamp range that can be used to filter what media data is appended to the sourcebuffer. coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out. sourcebuffer.audiotracks read only a list of the audio tracks currently contained inside the sourcebuffer. sourcebuffer.buffered read only returns the time ranges that are currently buffered in the sourcebuffer. sourcebuffer.mode controls how the order of media segments ...
...s have been removed. examples the following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. ...
...wing simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. ...
...And 4 more matches
Lighting in WebGL - Web APIs
t 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>. simulating lighting and shading in 3d although going into detail about the theory behind simulated lighting in 3d graphics is far beyond the scope of this article, it's helpful to know a bit about how it works. instead of discussing it in depth here, take a look at the article on phong shading at wikipedia, which provides a good overvie...
...pendicular to the face at that vertex. we need to know the direction in which the light is traveling; this is defined by the direction vector. then we update the vertex shader to adjust the color of each vertex, taking into account the ambient lighting as well as the effect of the directional lighting given the angle at which it's striking the face. we'll see how to do that when we look at the code for the shader. building the normals for the vertices the first thing we need to do is generate the array of normals for all the vertices that comprise our cube. since a cube is a very simple object, this is easy to do; obviously for more complex objects, calculating the normals will be more involved. const normalbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, normalbuffer); ...
...normals), gl.static_draw); ... return { position: positionbuffer, normal: normalbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; this should look pretty familiar by now; we create a new buffer, bind it to be the buffer we're working with, then send along our array of vertex normals into the buffer by calling bufferdata(). then we add the code to drawscene() to bind the normals array to a shader attribute so the shader code can get access to it: // tell webgl how to pull out the normals from // the normal buffer into the vertexnormal attribute. { const numcomponents = 3; const type = gl.float; const normalize = false; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.normal); ...
...And 4 more matches
Taking still photos with WebRTC - Web APIs
the html markup our html interface has two main operational sections: the stream and capture panel and the presentation panel. each of these is presented side-by-side in its own <div> to facilitate styling and control. ...
...irst panel on the left contains two components: a <video> element, which will receive the stream from webrtc, and a <button> the user clicks to capture a video frame. <div class="camera"> <video id="video">video stream not available.</video> <button id="startbutton">take photo</button> </div> this is straightforward, and we'll see how it ties together when we get into the javascript code. next, we have a <canvas> element into which the captured frames are stored, potentially manipulated in some way, and then converted into an output image file. this canvas is kept hidden by styling the canvas with display:none, to avoid cluttering up the screen — the user does not need to see this intermediate stage. we also have an <img> element into which we will draw the image — this is ...
...ge. we also have an <img> element into which we will draw the image — this is the final display shown to the user. <canvas id="canvas"> </canvas> <div class="output"> <img id="photo" alt="the screen capture will appear in this box."> </div> that's all of the relevant html. the rest is just some page layout fluff and a bit of text offering a link back to this page. the javascript code now let's take a look at the javascript code. we'll break it up into a few bite-sized pieces to make it easier to explain. initialization we start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using. (function() { var width = 320; // we will scale the photo width to this var height = 0; // this will be co...
...And 4 more matches
Web Audio API - Web APIs
audio context inside the context, create sources — such as <audio>, oscillator, stream create effects nodes, such as reverb, biquad filter, panner, compressor choose final destination of audio, for example your system speakers connect the sources up to the effects, and the effects to the destination. timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. so applications such as drum machines and sequencers are well within reach. the web audio api also allows us to control how audio is spatialized. using a system based on a source-listener model, it allows control of the panning model and deals with distance-induced attenuation induced by a movi...
...io source node interfaces. it is an audionode. oscillatornode the oscillatornode interface represents a periodic waveform, such as a sine or triangle wave. it is an audionode audio-processing module that causes a given frequency of wave to be created. audiobuffer the audiobuffer interface represents a short audio asset residing in memory, created from an audio file using the audiocontext.decodeaudiodata() method, or created with raw data using audiocontext.createbuffer(). once decoded into this form, the audio can then be put into an audiobuffersourcenode. audiobuffersourcenode the audiobuffersourcenode interface represents an audio source consisting of in-memory audio data, stored in an audiobuffer. it is an audionode that acts as an audio source. mediaelementaudiosourcenode the me...
... through the audiocontext object's audioworklet, and lets you add modules to the audio worklet to be executed off the main thread. audioworkletnode the audioworkletnode interface represents an audionode that is embedded into an audio graph and can pass messages to the corresponding audioworkletprocessor. audioworkletprocessor the audioworkletprocessor interface represents audio processing code running in a audioworkletglobalscope that generates, processes, or analyses audio directly, and can pass messages to the corresponding audioworkletnode. audioworkletglobalscope the audioworkletglobalscope interface is a workletglobalscope-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis o...
...And 4 more matches
Window.open() - Web APIs
Web › API › Window › open
with the focus() method. there would be no need to re-create the window or to reload the referenced resource. */ }; } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="promotefirefoxwindowname" onclick="openffpromotionpopup(); return false;" title="this link will create a new window or will re-use an already opened one" >promote firefox adoption</a></p> the above code solves a few usability problems related to links opening secondary window. the purpose of the return false in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. but if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the brows...
...n via script will very often annoy the users, will disorient the user, and will be wrong at best. the web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true. how do i open a referenced resource of a link in a new tab? or in a specific tab? to open a resource in a new tab see tabbed browser. some code snippets are available. if you are using the sdk, tabs are handled a bit differently k-meleon 1.1, a mozilla-based browser, gives complete control and power to the user regarding how links are opened. only the user can set his advanced preferences to do that. some advanced extensions also give mozilla and firefox a lot of power over how referenced resources are loaded. in a few years, the targe...
...ies or toolbars (or at least, the toolbars that are present by default). therefore, tab-browsing is preferred by a lot of users because the normal user-interface of the browser window they prefer is kept intact, remains stable. opening new windows, even with reduced features, uses considerably a lot of the user's system resources (cpu, ram) and involves considerably a lot of coding in the source code (security management, memory management, various code branchings sometimes quite complex, window frame/chrome/toolbars building, window positioning and sizing, etc.). opening new tabs is less demanding on the user's system resources (and faster to achieve) than opening new windows. offer to open a link in a new window, using these guidelines if you want to offer to open a link in a new window,...
...And 4 more matches
Window - Web APIs
Web › API › Window
the window interface represents a window containing a dom document; the document property points to the dom document loaded in that window. a window for a given document can be obtained using the document.defaultview property. a global variable, window, representing the window in which the script is running, is exposed to javascript code. the window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. however, the window interface is a suitable place to include these items that need to be globally available. many of these are documented in the javascript reference and the dom reference. in a tabbed browser, each tab is represented by its own window object; the global win...
...nstructors which are not necessarily directly associated with the concept of a user interface window. however, the window interface is a suitable place to include these items that need to be globally available. many of these are documented in the javascript reference and the dom reference. in a tabbed browser, each tab is represented by its own window object; the global window seen by javascript code running within a given tab always represents the tab in which the code is running. that said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeto() and innerheight. generally, anything that can't reasonably pertain to a tab pertains to the window instead. <div id="interfacediagram" style="display: inline-block; posit...
...drilaterial object, that is one having four corners and four sides. window.domrect read only returns a reference to a domrect object, which represents a rectangle. window.domrectreadonly read only returns a reference to a domrectreadonly object, which represents a rectangle. window.event read only returns the current event, which is the event currently being handled by the javascript code's context, or undefined if no event is currently being handled. the event object passed directly to event handlers should be used instead whenever possible. window.frameelement read only returns the element in which the window is embedded, or null if the window is not embedded. window.frames read only returns an array of the subframes in the current window. window.fullscreen this property...
...And 4 more matches
WindowEventHandlers - Web APIs
nt additional specific event handlers. note: windoweventhandlers is a mixin and not an interface; you can't actually create an object of type windoweventhandlers. properties the events properties, of the form onxyz, are defined on the windoweventhandlers, and implemented by window, and workerglobalscope for web workers. ...
...n object of type windoweventhandlers. properties the events properties, of the form onxyz, are defined on the windoweventhandlers, and implemented by window, and workerglobalscope for web workers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. ...
...ers, and implemented by window, and workerglobalscope for web workers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. windoweventhandlers.onbeforeunload is an eventhandler representing the code to be called when the beforeunload event is raised. windoweventhandlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. ...
...And 4 more matches
Synchronous and asynchronous requests - Web APIs
asynchronous request if you use an asynchronous xmlhttprequest, you receive a callback when the data has been received. this lets the browser continue to work as normal while your request is being handled. ...
...riable xhr, passed to the success callback function xhrsuccess., and ultimately supplied to the callback function (in this case, showmessage) which is invoked by function xhrsuccess. line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously. line 16 actually initiates the request. ...
... by function xhrsuccess. line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously. line 16 actually initiates the request. example: using a timeout you can use a timeout to prevent your code from hanging while waiting for a read to finish. ...
...And 4 more matches
:nth-child() - CSS: Cascading Style Sheets
as a simple p selector (although with a higher specificity). p:nth-child(1) or p:nth-child(0n+1) represents every <p> that is the first element in a group of siblings. this is the same as the :first-child selector (and has the same specificity). p:nth-child(n+8):nth-child(-n+15) represents the eighth through the fifteenth <p> elements of a group of siblings. ...
...though with a higher specificity). p:nth-child(1) or p:nth-child(0n+1) represents every <p> that is the first element in a group of siblings. this is the same as the :first-child selector (and has the same specificity). p:nth-child(n+8):nth-child(-n+15) represents the eighth through the fifteenth <p> elements of a group of siblings. ...
...pecificity). p:nth-child(1) or p:nth-child(0n+1) represents every <p> that is the first element in a group of siblings. this is the same as the :first-child selector (and has the same specificity). p:nth-child(n+8):nth-child(-n+15) represents the eighth through the fifteenth <p> elements of a group of siblings. ...
...And 4 more matches
hyphens - CSS: Cascading Style Sheets
Web › CSS › hyphens
e break opportunities below) will override automatic break point selection when present. note: the auto setting's behavior depends on the language being properly tagged to select the appropriate hyphenation rules. you must specify a language using the lang html attribute to guarantee that automatic hyphenation is applied in that language. suggesting line break opportunities there are two unicode characters used to manually specify potential line break points within text: u+2010 (hyphen) the "hard" hyphen character indicates a visible line break opportunity. even if the line is not actually broken at that point, the hyphen is still rendered. u+00ad (shy) an invisible, "soft" hyphen. this character is not rendered visibly; instead, it marks a place where the browser should break the ...
...soft hyphen. when the html <wbr> element leads to a line break, no hyphen is added. formal definition initial valuemanualapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | manual | auto examples specifying text hyphenation this example uses three classes, one for each possible configuration of the hyphens property. ...
.... when the html <wbr> element leads to a line break, no hyphen is added. formal definition initial valuemanualapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | manual | auto examples specifying text hyphenation this example uses three classes, one for each possible configuration of the hyphens property. ...
...And 4 more matches
Demos of open web technologies
mozilla supports a wide variety of exciting open web technologies, and we encourage their use. this page offers links to interesting demonstrations of these technologies. if you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
...ge their use. this page offers links to interesting demonstrations of these technologies. if you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
...nks to interesting demonstrations of these technologies. if you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
...And 4 more matches
Cross-browser audio basics - Developer guides
you can use type="audio/mp4". (currently, browsers that support mp3 also support...
... html5: <audio controls> <source src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for non supporting browsers goes here --> <p>your browser does not support html5 audio, but you can still <a href="audiofile.mp3">download the music</a>.</p> </audio> note: you can also use an mp4 file instead of mp3. mp4 files typically contain aac encoded audio. you can use type="audio/mp4". (currently, browsers that support mp3 also support mp4 audio). here we define an <audio> element with multiple sources — we do this as not all browsers support the same audio formats. to ensure reasonable coverage, we should specify at least two different formats. the two formats that will give maximum coverage are mp3 and ogg vorbis. we do this using ...
...these are also deprecated, and soon won't work in any modern browsers. manipulating the audio element with javascript in addition to being able to specify various attributes in html, the <audio> element comes complete with several pro...
...And 4 more matches
Creating a cross-browser video player - Developer guides
rowser defaults. the player controls themselves won't be styled beyond the basics required to get them working; full styling of the player will be taken care of in a future article. working example our example video player displays a clip from an open source movie called tears of steel, and includes typical video controls. note: you can see the example running live, or check out the source code on github. html markup to start off with, let's take a look at the html that makes up the player. the video first of all the <video> element is defined, contained within a <figure> element that acts as the video container. to anyone familiar with html5 markup and the <video> element, there should be nothing here that surprises you. <figure id="videocontainer"> <video id="video" controls ...
...s. for browsers that do not support html5 video, a flash player is provided that will allow playback of the mp4 video source, provided the end user has flash installed. in addition a download link is displayed to allow users to download the mp4 video file, should they wish to (providing those without flash installed with a method of viewing the video, a fallback for a fallback if you like). the code above would allow playback of the video in most browsers, using the browser's default control set. the next step is to define a custom control set, also in html, which will be used to control the video. the control set most browser's default video controls have the following functionality: play/pause mute volume control progress bar skip ahead go fullscreen the custom control set will...
...r default video control sets is the ability to click on the video's progress bar to "skip ahead" to a different point in the video. this can also be achieved by adding a simple click event listener to the progress element: progress.addeventlistener('click', function(e) { var pos = (e.pagex - this.offsetleft) / this.offsetwidth; video.currenttime = pos * video.duration; }); this piece of code simply uses the clicked position to (roughly) work out where in the progress element the user has clicked, and to move the video to that position by setting its currenttime attribute. fullscreen the fullscreen api should be straight forward to use: the user clicks a button, if the video is in fullscreen mode: cancel it, otherwise enter fullscreen mode. alas it has been implemented in browsers ...
...And 4 more matches
DOM onevent handlers - Developer guides
with properties on non-element objects that generate events, like window, document, xmlhttprequest, and others. for example, for the progress event on instances of xmlhttprequest: const xhr = new xmlhttprequest(); xhr.onprogress = function() { … }; html onevent attributes html elements have attributes named onevent which can be used to register a handler for an event directly within the html code. when the element is built from the html, the value of its onevent attributes are copied to the dom object that represents the element, so that accessing the attributes' values using javascript will get the value set in the html. further changes to the html attribute value can be done via the setattribute method; making changes to the javascript property will have no effect. html given this ht...
... the value of its onevent attributes are copied to the dom object that represents the element, so that accessing the attributes' values using javascript will get the value set in the html. further changes to the html attribute value can be done via the setattribute method; making changes to the javascript property will have no effect. html given this html document: <p>demonstrating quirks of <code>on<em>event</em></code> html attributes on <a onclick="log('click!')">these three words</a>. </p> <div></div> javascript then this javascript demonstrates that the value of the html attribute is unaffected by changes to the javascript object's property. let logelement = document.queryselector('div'); let el = document.queryselector("a"); function log(msg) { logelement.innerhtml += `${msg}...
...pt demonstrates that the value of the html attribute is unaffected by changes to the javascript object's property. ...
...And 4 more matches
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
n the same document. the <datalist> provides a list of predefined values to suggest to the user for this input. any values in the list that are not compatible with the type are not included in the suggested options. the values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ...
...this must be an non-negative integer value smaller than or equal to the value specified by maxlength. ...
...ue is specified, the email input has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. minlength the minimum number of characters (as utf-16 code units) the user can enter into the email input. this must be an non-negative integer value smaller than or equal to the value specified by maxlength. if no minlength is specified, or an invalid value is specified, the email input has no minimum length. the input will fail constraint validation if the length of the text entered into the field is fewer than minlength utf-16 code units long. constr...
...And 4 more matches
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
n the same document. the <datalist> provides a list of predefined values to suggest to the user for this input. any values in the list that are not compatible with the type are not included in the suggested options. the values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ...
...this must be an non-negative integer value smaller than or equal to the value specified by maxlength. ...
...lue is specified, the text input has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. minlength the minimum number of characters (as utf-16 code units) the user can enter into the text input. this must be an non-negative integer value smaller than or equal to the value specified by maxlength. if no minlength is specified, or an invalid value is specified, the text input has no minimum length. the input will fail constraint validation if the length of the text entered into the field is fewer than minlength utf-16 code units long. constrai...
...And 4 more matches
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
n the same document. the <datalist> provides a list of predefined values to suggest to the user for this input. any values in the list that are not compatible with the type are not included in the suggested options. the values provided are suggestions, not requirements: users can select from this predefined list or provide a different value. ...
...this must be an non-negative integer value smaller than or equal to the value specified by maxlength. ...
...alue is specified, the url input has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. minlength the minimum number of characters (as utf-16 code units) the user can enter into the url input. this must be an non-negative integer value smaller than or equal to the value specified by maxlength. if no minlength is specified, or an invalid value is specified, the url input has no minimum length. the input will fail constraint validation if the length of the text entered into the field is fewer than minlength utf-16 code units long. constraint...
...And 4 more matches
HTTP authentication - HTTP
uest including the correct authorization header. in the case of a "basic" authentication like shown in the figure, the exchange must happen over an https (tls) connection to be secure. proxy authentication the same challenge and response mechanism can be used for proxy authentication. as both resource authentication and proxy authentication can coexist, a different set of headers and status codes is needed. in the case of proxies, the challenging status code is 407 (proxy authentication required), the proxy-authenticate response header contains at least one challenge applicable to the proxy, and the proxy-authorization request header is used for providing the credentials to the proxy server. access forbidden if a (proxy) server receives valid credentials that are inadequate to access a...
...proxy authentication required), the proxy-authenticate response header contains at least one challenge applicable to the proxy, and the proxy-authorization request header is used for providing the credentials to the proxy server. access forbidden if a (proxy) server receives valid credentials that are inadequate to access a given resource, the server should respond with the 403 forbidden status code. unlike 401 unauthorized or 407 proxy authentication required, authentication is impossible for this user. authentication of cross-origin images a potential security hole recently been fixed by browsers is authentication of cross-site images. from firefox 59 onwards, image resources loaded from different origins to the current document are no longer able to trigger http authentication dialogs (...
...his could be a message like "access to the staging site" or similar, so that the user knows to which space they are trying to get access to. authorization and proxy-authorization headers the authorization and proxy-authorization request headers contain the credentials to authenticate a user agent with a (proxy) server. here, the <type> is needed again followed by the credentials, which can be encoded or encrypted depending on which authentication scheme is used. authorization: <type> <credentials> proxy-authorization: <type> <credentials> authentication schemes the general http authentication framework is used by several authentication schemes. schemes can differ in security strength and in their availability in client or server software. the most common authentication scheme is the "ba...
...And 4 more matches
Index - HTTP
Web › HTTP › Headers › Index
accept-ranges response http header is a marker used by the server to advertise its support of partial requests. the value of this field indicates the unit that can be used to define a range. 7 access-control-allow-credentials cors, http, reference, header the access-control-allow-credentials response header tells browsers whether to expose the response to frontend javascript code when the request's credentials mode (request.credentials) is "include". 8 access-control-allow-headers cors, http, reference, header the access-control-allow-headers response header is used in response to a preflight request which includes the access-control-request-headers to indicate which http headers can be used during the actual request. 9 access-control-allow...
...hods allowed when accessing the resource in response to a preflight request. 10 access-control-allow-origin access control, access-control-allow-origin, cors, dealing with cors, http, http header, how to fix cors, reference, security, cross-origin issue, header, origin the access-control-allow-origin response header indicates whether the response can be shared with requesting code from the given origin. 11 access-control-expose-headers cors, http, reference, header the access-control-expose-headers response header indicates which headers can be exposed as part of the response by listing their names. 12 access-control-max-age cors, http, reference, header the access-control-max-age response header indicates how long the results of a...
...plies to. the subpart is delimited by the boundary defined in the content-type header. used on the body itself, content-disposition has no effect. 23 content-encoding http, headers, reference the content-encoding entity header is used to compress the media-type. when present, its value indicates which encodings were applied to the entity-body. it lets the client know how to decode in order to obtain the media-type referenced by the content-type header. 24 content-language http, headers, reference the content-language entity header is used to describe the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. 25 content-length http, headers, reference the cont...
...And 4 more matches
Indexed collections - JavaScript
ms of array creation, and so is generally preferred. see array literals for details. to create an array with non-zero length, but without any items, either of the following can be used: // this... let arr = new array(arraylength) // ...results in the same array as this let arr = array(arraylength) // this has exactly the same effect let arr = [] arr.length = arraylength note: in the above code, arraylength must be a number. otherwise, an array with a single element (the provided value) will be created. calling arr.length will return arraylength, but the array doesn't contain any elements. a for...in loop will not find any property on the array. in addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object: let obj = ...
...rray with no elements // and arr.length set to 42. // // this is equivalent to: let arr = [] arr.length = 42 calling array(n) results in a rangeerror, if n is a non-whole number whose fractional portion is non-zero. the following example illustrates this behavior. let arr = array(9.3) // rangeerror: invalid array length if your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. alternatively, create an empty array first before adding the single element to it. in es2015, you can use the array.of static method to create arrays with single element. let wisenarray = array.of(9.3) // wisenarray contains only one element 9.3 referring to array elements because eleme...
...ors to access other properties of the array, like with an object. let arr = ['one', 'two', 'three'] arr[2] // three arr['length'] // 3 populating an array you can populate an array by assigning values to its elements. for example: let emp = [] emp[0] = 'casey jones' emp[1] = 'phil lesh' emp[2] = 'august west' note: if you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element. let arr = [] arr[3.4] = 'oranges' console.log(arr.length) // 0 console.log(arr.hasownproperty(3.4)) // true you can also populate an array when you create it: let myarray = new array('hello', myvar, 3.14159) // or let myarray = ['mango', 'apple', 'orange'] understanding l...
...And 4 more matches
Function.prototype.toString() - JavaScript
description the function object overrides the tostring method inherited from object; it does not inherit object.prototype.tostring. for user-defined function objects, the tostring method returns a string containing the source text segment which was used to define the function. ...
... description the function object overrides the tostring method inherited from object; it does not inherit object.prototype.tostring. for user-defined function objects, the tostring method returns a string containing the source text segment which was used to define the function. ...
...ow a typeerror exception ("function.prototype.tostring called on incompatible object"), if its this value object is not a function object. ...
...And 4 more matches
JSON.stringify() - JavaScript
ingify({ obj }); // shorthand property names (es2015). // '{"obj":"now i am a nested object under key 'obj'"}' json.stringify([ obj ]); // '["now i am a nested object under key '0'"]' issue with json.stringify() when serializing circular references note that since the json format doesn't support object references (although an ietf draft exists), a typeerror will be thrown if one attempts to encode an object with circular references. const circularreference = {}; circularreference.myself = circularreference; // serializing circular references throws "typeerror: cyclic object value" json.stringify(circularreference); to serialize circular references you can use a library that supports them (e.g. cycle.js by douglas crockford) or implement a solution by yourself, which will require findin...
...reference); to serialize circular references you can use a library that supports them (e.g. cycle.js by douglas crockford) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values. issue with plain json.stringify for use as javascript historically, json was not a completely strict subset of javascript. the literal code points u+2028 line separator and u+2029 paragraph separator could appear literally in string literals and property names in json text. but they could not appear literally in similar context in javascript text, only using unicode escapes as \u2028 and \u2029. this recently changed: now both code points may appear literally in strings in json and javascript both. therefore, if compatibility with ...
...is required, it is perilous to directly substitute the string returned by json.stringify into a javascript string to be passed to eval or new function or as part of a jsonp url, and the following utility can be used: function jsfriendlyjsonstringify (s) { return json.stringify(s). replace(/\u2028/g, '\\u2028'). ...
...And 4 more matches
async function - JavaScript
ait expressions. await expressions suspend progress through an async function, yielding control and subsequently resuming progress only when an awaited promise-based asynchronous operation is either fulfilled or rejected. the resolved value of the promise is treated as the return value of the await expression. use of async / await enables the use of ordinary try / catch blocks around asynchronous code. the await keyword is only valid inside async functions. if you use it outside of an async function's body, you will get a syntaxerror. the purpose of async/await is to simplify the syntax necessary to consume promise-based apis. the behavior of async/await is similar to combining generators and promises. async functions always return a promise. if the return value of an async function is ...
...c functions always return a promise. if the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. for example, the following: async function foo() { return 1 } ...is equivalent to: function foo() { return promise.resolve(1) } the body of an async function can be thought of as being split by zero or more await expressions. top-level code, up to and including the first await expression (if there is one), is run synchronously. in this way, an async function without an await expression will run synchronously. if there is an await expression inside the function body, however, the async function will always complete asynchronously. for example: async function foo() { await 1 } ...is equivalent to: function foo() { return pr...
...ssion (if there is one), is run synchronously. in this way, an async function without an await expression will run synchronously. if there is an await expression inside the function body, however, the async function will always complete asynchronously. for example: async function foo() { await 1 } ...is equivalent to: function foo() { return promise.resolve(1).then(() => undefined) } code after each await expression can be thought of as existing in a .then callback. in this way a promise chain is progressively constructed with each reentrant step through the function. the return value forms the final link in the chain. in the following example, we successively await two promises. progress moves through function foo in three stages. the first line of the body of function foo is...
...And 4 more matches
Template literals (Template strings) - JavaScript
tring.raw() method exists to create raw strings—just like the default template function and string concatenation would create. ...
...t like the default template function and string concatenation would create. ...
...e the default template function and string concatenation would create. ...
...And 4 more matches
Authoring MathML - MathML
itors and other content management systems to help writing web pages. mathematical notations are even more complex with structures like fractions, square roots or matrices that are likely to require their own tags. as a consequence, good mathml authoring tools are more important and we describe some tools below. in particular, the mozilla mathml team has been developing texzilla, a javascript unicode latex-to-mathml converter that is intended to be used in many scenarios described here. of course, the list is by no means exhaustive and you are invited to check out the w3c mathml software list where you can find various other tools. note that by design, mathml is well-integrated in html5 and in particular you can use usual web features like css, dom, javascript or svg. this is out of the scop...
...h/mathml"> <msqrt> <mn>2</mn> </msqrt> </math> </p> </body> </html> mathml in email and instant messaging clients modern mail clients may send and receive emails in the html5 format and thus can use mathml expressions. be sure to have the "send as html" and "view as html" options enabled. in thunderbird, you can use the "insert html" command to paste your html+mathml code. mathbird is a convenient add-on for thunderbird to insert such mathml expressions using the asciimath input syntax. moreover, a latex-to-mathml input box has also been integrated into seamonkey since version 2.28 and into thunderbird since version 31. again, the way mathml is handled and the quality of the mathml rendering depends on the mail client. even if your browser supports mathml, your we...
...ome of these tools to convert from a simple syntax to mathml. pros: writing mathematical expressions may only require a standard text editor. many tools are available, some of them are compatible with the classical latex-to-pdf workflow. this gives access to advanced features of latex like macros. cons: this may be harder to use: people must learn a syntax, typos in the code may easily lead to parsing or rendering errors etc the interface is not user-friendly: only code editor without immediate display of the mathematical expression. none of the syntax has been standardized, making cross-compatibility between converters difficult. even the popular latex language keeps having new packages added. client-side conversion in a web environment, the most obvio...
...And 4 more matches
Tutorials
best practices for web development and that provide or allow translations, through an open content license such as creative commons. for complete beginners to the web getting started with the web getting started with the web is a concise series introducing you to the practicalities of web development. you'll set up the tools you need to construct a simple webpage and publish your own simple code. html tutorials introductory level introduction to html this module sets the stage, getting you used to important concepts and syntax, looking at applying html to text, how to create hyperlinks, and how to use html to structure a webpage. mdn html element reference a comprehensive reference for html elements, and how the different browsers support them. creating a simple web page...
...xt, how to create hyperlinks, and how to use html to structure a webpage. mdn html element reference a comprehensive reference for html elements, and how the different browsers support them. creating a simple web page with html an html guide for beginners that includes explanations of common tags, including html5 tags. also includes a step-by-step guide to creating a basic web page with code examples. html challenges use these challenges to hone your html skills (for example, "should i use an <h2> element or a <strong> element?"), focusing on meaningful markup. intermediate level multimedia and embedding this module explores how to use html to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, an...
...ging in, sending feedback, buying products, and more. this module gets you started with creating the client-side parts of forms. tips for authoring fast-loading html pages optimize web pages to provide a more responsive site for visitors and reduce the load on your web server and internet connection. css tutorials introductory level css basics css (cascading style sheets) is the code you use to style your webpage. css basics takes you through what you need to get started. we'll answer questions like: how do i make my text black or red? how do i make my content show up in such-and-such a place on the screen? how do i decorate my webpage with background images and colors? css first steps css (cascading style sheets) is used to style and lay out web pages — for example, to...
...And 4 more matches
Using custom elements - Web Components
d, it displays the text in a pop up information box to provide further in-context information. to begin with, the javascript file defines a class called popupinfo, which extends the generic htmlelement class. class popupinfo extends htmlelement { constructor() { // always call super first in constructor super(); // write element functionality in here ... } } the preceding code snippet contains the constructor() definition for the class, which always starts by calling super() so that the correct prototype chain is established. inside the constructor, we define all the functionality the element will have when an instance of it is instantiated. in this case we attach a shadow root to the custom element, use some dom manipulation to create the element's internal shadow do...
...egister our custom element on the customelementregistry using the define() method we mentioned earlier — in the parameters we specify the element name, and then the class name that defines its functionality: customelements.define('popup-info', popupinfo); it is now available to use on our page. over in our html, we use it like so: <popup-info img="img/alt.png" data-text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."></popup-info> note: you can see the full javascript source code here. internal vs. external styles in the above example we apply style to the shadow dom using a <style> element, but it is perfectly possible to do it by referencing an external stylesheet from a <link> element instead. for exam...
...rity feature — it is the last 3 or 4 numbers on the back of your card."></popup-info> note: you can see the full javascript source code here. internal vs. external styles in the above example we apply style to the shadow dom using a <style> element, but it is perfectly possible to do it by referencing an external stylesheet from a <link> element instead. ...
...And 4 more matches
Introduction to using XPath in JavaScript - XPath
ifferent prefixes used in the document. the function can be either: created by using the creatensresolver method of a xpathevaluator object. you should use this virtually all of the time. null, which can be used for html documents or when no namespace prefixes are used. note that, if the xpathexpression contains a namespace prefix, this will result in a domexception being thrown with the code namespace_err. a custom user-defined function. see the using a user defined namespace resolver section in the appendix for details. resulttype: a constant that specifies the desired result type to be returned as a result of the evaluation. the most commonly passed constant is xpathresult.any_type which will return the results of the xpath expression as the most natural type. there is a s...
...ified in the resulttype parameter. the xpathresult interface is defined here. implementing a default namespace resolver we create a namespace resolver using the creatensresolver method of the document object. var nsresolver = document.creatensresolver( contextnode.ownerdocument == null ? contextnode.documentelement : contextnode.ownerdocument.documentelement ); or alternatively by using the <code>creatensresolver</code> method of a <code>xpathevaluator</code> object. <pre> var xpevaluator = new xpathevaluator(); var nsresolver = xpevaluator.creatensresolver( contextnode.ownerdocument == null ? contextnode.documentelement : contextnode.ownerdocument.documentelement ); </pre> and then pass document.evaluate, the nsresolver variable as the namespaceresolver parameter. note: xpath defines qn...
... node-set types the xpathresult object allows node-sets to be returned in 3 principal different types: iterators snap...
...And 4 more matches
WebAssembly
webassembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as c/c++, c# and rust with a compilation target so that they can run on the web. it is also designed to run alongside javascript, allowing both to work together. in a nutshell webassembly has huge implications for the web platform — it provides a way to run code written in multiple languages on the web at near native speed, with client apps running on the web that previously couldn’t have done so. webassembly is designed to complement and run alongside javascript — using the webassembly javascript apis, you can load webassembly modules into a javascript app and share functi...
...e so. webassembly is designed to complement and run alongside javascript — using the webassembly javascript apis, you can load webassembly modules into a javascript app and share functionality between the two. this allows you to take advantage of webassembly's performance and power and javascript's expressiveness and flexibility in the same apps, even if you don't know how to write webassembly code. and what's even better is that it is being developed as a web standard via the w3c webassembly working group and community group with active participation from all major browser vendors. guides webassembly concepts get started by reading the high-level concepts behind webassembly — what it is, why it is so useful, how it fits into the web platform (and beyond), and how to use it. comp...
...b standard via the w3c webassembly working group and community group with active participation from all major browser vendors. guides webassembly concepts get started by reading the high-level concepts behind webassembly — what it is, why it is so useful, how it fits into the web platform (and beyond), and how to use it. ...
...And 4 more matches
port - Archive of obsolete content
for an overview of content scripts, see the main article. port methods emit() the port.emit() function sends a message from one side to the other. ...
... for an overview of content scripts, see the main article. port methods emit() the port.emit() function sends a message from one side to the other. ...
... for an overview of content scripts, see the main article. port methods emit() the port.emit() function sends a message from one side to the other. ...
...And 3 more matches
Module structure of the SDK - Archive of obsolete content
commonjs is the underlying infrastructure for both the sdk and the add-ons you build using the sdk. a commonjs module is a piece of reusable javascript: it exports certain objects which are thus made available to dependent code. commonjs defines: an object called exports which contains all the objects which a commonjs module wants to make available to other modules a function called require which a module can use to import the exports object of another module. except for scripts that interact directly with web content, all the javascript code you'll write or use when developing add-ons using the sdk is part of a commonjs module, including: sdk modules: the javascript modules which the sdk provides, such as panel and page-mod. local modules: each of the javascript files under your ...
... using jpm run or jpm xpi, it is the versions of the modules in firefox that are used. if you need to use a different version of the modules, you can do this by checking out the version of the sdk that you need and passing the -o or --overload option to jpm run or jpm xpi. local modules at a minimum, an sdk-based add-on consists of a single module named main.js, but you can factor your add-on's code into a collection of separate commonjs modules. each module is a separate file stored under your add-on's "lib" directory, and exports the objects you want to make available to other modules in your add-on. see the tutorial on creating reusable modules for more details. to import a local module, specify a path relative to the importing module. for example, the following add-on contains an addit...
... relative to the importing module. ...
...And 3 more matches
page-worker - Archive of obsolete content
e the file in your add-on's data directory and create the url using the data.url() method of the self module: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: require("sdk/self").data.url("myfile.html") }); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: "./myfile.html" }); you can load a new page by setting the page worker's contenturl property. in this example we fetch the first paragraph of a page from wikipedia, then the first paragraph of a different page: var getfirstparagraph = "var paras = document.geteleme...
...t as a string, as in the examples above. with contentscriptfile you pass a url which points to a script saved under your add-on's data directory. you construct the url using the data.url() method of the self module. while content scripts can access dom content, they can't access any of the sdk apis, so in many cases you'll need to exchange messages between the content script and your main add-on code for a complete solution. for example, the content script might read some content and send it back to the main add-on, which could store it using the simple-storage api. you can communicate with the script using either the postmessage() api or (preferably, usually) the port api. for example, this add-on loads a page from wikipedia, and runs a content script in it to send all the headers back to ...
...solution. for example, the content script might read some content and send it back to the main add-on, which could store it using the simple-storage api. you can communicate with the script using either the postmessage() api or (preferably, usually) the port api. ...
...And 3 more matches
ui/frame - Archive of obsolete content
src="frame.js"></script> as usual, the path to the script is relative to the html file's location. messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run. however, they will appear in the browser console. this issue is being tracked as bug 982385. ...
...ear in the browser console. this issue is being tracked as bug 982385. communicating with frames you can exchange messages between the main add-on code and scripts loaded into the frame using an api modeled on window.postmessage(). a frame creates a separate iframe instance for each browser window. so there are three cases to consider: sending messages from a frame script to the main add-on code sending messages from the main add-on code to all instances of a frame, across all browser windows sending messages from the main add-on code to a single instance of a frame, attached to a specific browser window in all cases, postmessage() takes two arguments: the message itself and a targetorigin. the targetorigin argument can be either the uri of the document hosted by the target, or the w...
...s on the "city-selector" <select> element, and sends a message to the add-on containing the value for the newly selected element. // city-info.js var cityselector = window.document.getelementbyid("city-selector"); cityselector.addeventlistener("change", citychanged); function citychanged() { window.parent.postmessage(cityselector.value, "*"); } to listen for these messages in the main add-on code, you can assign a listener to the frame's message event. the data property of the event is the message payload. var { frame } = require("sdk/ui/frame"); var { toolbar } = require("sdk/ui/toolbar"); var frame = new frame({ url: "./city-info.html", onmessage: (e) => { console.log("new city: " + e.data); } }); var toolbar = toolbar({ name: "city-info", title: "city info", items: [...
...And 3 more matches
Rosetta - Archive of obsolete content
d arrays in ecmascript allow us, in theory, to build full virtual machines in pure ecmascript. therefore, it is also possible, in theory, to use ecmascript for a smaller task: parsing exotic programming languages (i.e., creating compilers). beyond ecmascript this is not the place for showing a full compiler written in ecmascript. we can show, however, a possible way to start from. the following code is nothing but the base for an extensible collection of compilers. but by default, no compilers are loaded. it relies on the fact that unrecognized mime types will be simply ignored: this allows us to manually parse them. for a fast overview on the code proposed here you can git clone https://github.com/madmurphy/rosetta.js, or, at your choice, directly download this .zip file. rosetta.js: lib...
...nually parse them. for a fast overview on the code proposed here you can git clone https://github.com/madmurphy/rosetta.js, or, at your choice, directly download this .zip file. rosetta.js: library "use strict"; /*\ |*| |*| :: rosetta.js :: |*| |*| a possible, extensible collection of compilers to native ecmascript. |*| |*| november 12, 2014 |*| |*| https://developer.mozilla.org/add-ons/code_snippets/rosetta |*| https://developer.mozilla.org/user:fusionchess |*| |*| this framework is released under the gnu public license, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0.html |*| |*| syntax: |*| |*| rosetta.appendcompiler([ "text/x-csrc", "text/x-c" ], yourcompiler); |*| \*/ var rosetta = new (function () { function createscript (oscript, oxhr200) { var ...
... the gnu public license, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0.html |*| |*| syntax: |*| |*| rosetta.appendcompiler([ "text/x-csrc", "text/x-c" ], yourcompiler); |*| \*/ var rosetta = new (function () { function createscript (oscript, oxhr200) { var smimetype = oscript.getattribute("type").tolowercase(), obaton = document.createcomment(" the previous code has been automatically translated from \"" + smimetype + "\" to \"text/ecmascript\". "); if (!odicts.hasownproperty(smimetype)) { alert("rosetta.translatescript() \u2013 unknown mime-type \"" + smimetype + "\": script ignored."); return; } var ocompiled = document.createelement("script"); oscript.parentnode.insertbefore(obaton, oscript); oscript.parentnode.remove...
...And 3 more matches
Appendix A: Add-on Performance - Archive of obsolete content
vent is that it runs before the main window becomes visible, so all handlers need to complete before the user can see the window. an add-on can normally add a few hundred milliseconds to startup time because of the load handler, and it's not hard to figure out what having several add-ons will do. luckily, minimizing your startup time is easy, if you follow these guidelines: do not load or run code before it’s needed. add-ons can have extra features that are only available depending on user preferences. other add-ons have most of their features depend on a user being logged in to a service. don’t load at startup something you won’t need at the time. javascript code modules. use them. jsm provide the cleanest way to separate js into modules that can be loaded on request, unlike chrome...
...ng on user preferences. other add-ons have most of their features depend on a user being logged in to a service. don’t load at startup something you won’t need at the time. javascript code modules. use them. jsm provide the cleanest way to separate js into modules that can be loaded on request, unlike chrome scripts which are generally loaded with the overlay at startup. keep as much of your code in jsm, make it as modular as you can, and only load modules as you require them. if your add-on is too simple for jsm, don’t worry about it. there’s still one more thing you can do. ...
...r code in jsm, make it as modular as you can, and only load modules as you require them. if your add-on is too simple for jsm, don’t worry about it. there’s still one more thing you can do. do as little as possible in your load handler. ask yourself: is there anything i can’t run 100 ms or even 500 ms later? if there is, just use an nsitimer or the settimeout function to delay running this code . the firefox window will be able to load sooner and your startup code will run almost instantaneously afterward, in parallel with the loading of the homepage or the saved tab session. the browser will now load faster, and your code will still load at startup for all practical purposes. the code is simple enough: // this is the function that is called in the load event handler. init : function(...
...And 3 more matches
Local Storage - Archive of obsolete content
extension that is more complex than a hello world needs some way to log errors and trace execution without having to fire up a debugger. it used to be the case that custom logging solutions were necessary, but mozilla labs have come up with a javascript implementation of a logger similar to the log4j logger used in java projects. ...
...p with a javascript implementation of a logger similar to the log4j logger used in java projects. the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above. to use this logger, you need to copy the log4moz.js file to your modules directory. in the initialization method of your one of your "common" or startup objects, add the following code: let formatter = new log4moz.basicformatter(); let root = log4moz.repository.rootlogger; let logfile = this.getlocaldirectory(); // remember this? let appender; logfile.append("log.txt"); // loggers are hierarchical, lowering this log level will affect all // output. root.level = log4moz.level["all"]; // this appender will log to the file system. appender = new log4moz.rotatingfileappender(lo...
...x used by sqlite, you can read more at the sqlite site. you should carefully design your database structure, taking into account features you're planning on adding in the future. adding or removing columns, or making other changes to your db structure from one version of your extension to the next will probably cause breakage of user data in older versions. you'll need to carefully add migration code that moves the data from the old db format to the new, and this becomes increasingly complex as you add new versions and new structure changes. so, be careful and plan for the future. there are two paths you can take when creating the local database you'll be using for your extension: generate the database file (through mozistorageservice.opendatabase(), all tables (through mozistorageconnect...
...And 3 more matches
Observer Notifications - Archive of obsolete content
for example, you might want to notify that a task is completed, and then several different actions must be performed. you could do that by calling all those functions directly, but xpcom offers you a better and cleaner way to achieve that using observers and the observer service. an observer is an object that is responsible to observe (wait for) notifications and then to carry out subsequent actions. to create an observer, you need to implement the nsiobserver interface. the interface has only one method observe() which takes three parameters. ...
... for) notifications and then to carry out subsequent actions. to create an observer, you need to implement the nsiobserver interface. the interface has only one method observe() which takes three parameters. the first parameter (subject) can be any xpcom object, the second parameter is a notification topic, and the final parameter is a string that further describes the notification. ...
...pass to those observers (can be null), the second parameter is the notification topic and the last parameter is an additional string to pass to those observers (can be null). observerservice.notifyobservers(null, "xulschoolhello-test-topic", "hello"); non-chrome to chrome communication non-chrome to chrome communication is one of the main uses of observers. by non-chrome we mean javascript code modules or xpcom. as we saw in previous sections, you can use javascript code module and xpcom objects very easily from the chrome. but given that chrome is window-dependent and non-chrome objects are not, it's tricky to send a message to the chrome. you would have to invoke a method for the chrome objects in all windows. it's much easier to use observers in this case. let's see the following ex...
...And 3 more matches
Setting Up a Development Environment - Archive of obsolete content
on the other hand, extensions use the same (or similar) languages that are used for web development, so most text editors and ides are up to the task. most xul tools and plugins you'll find online are merely templates that generate the folder structure for the project, and that's not much help. we recommend komodo edit. ...
... komodo project file. we recommend git and github for source control, but any decent software configuration management system will do. to package xpi files, we use make. we chose make because this is the same system used by mozilla to build firefox, and it is available for all operating systems. make is a default tool in most unix-based systems. it can be installed on mac os x as part of the xcode tools package, and on windows with cygwin. in cygwin installations you'll have to explicitly check the make and zip utilities from the long list of packages to download and install. also make sure that make is in the executable system path. after setting up make, you should be able to open a command line window, run "make -ver", and get the installed version of make as output. we recommend you ...
... don't see this textbox, click on the "more" button. you also have the option to save the command, by clicking on the "add to toolbox" checkbox. to see the toolbox, click on view > tabs > toolbox, from the main menu. with that, you should now have a very easy way to build your xpi, by just double clicking on the created commands. we can make it even better. once you're testing and debugging your code, you'll find that constantly building and installing an xpi can be very tedious. this is the reason why we introduced "make install". this only works if your extension is already installed in a firefox profile. just like in the provided project, you need the add-on id and profile location set in the file makefile. we use this information to locate the installation path of the extension and overwr...
...And 3 more matches
Extensions support in SeaMonkey 2 - Archive of obsolete content
starting with seamonkey 2 alpha 1 seamonkey supports toolkit/-style extensions. these type of extensions have many advantages for both users and developers compared to the old xpinstall/-style extensions. the basics to support seamonkey 2 as a target application, you need to add it to the list of target applications in the extension's install.rdf file. the code for that will look something like this: <em:targetapplication> <!-- seamonkey --> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.0</em:minversion> <em:maxversion>2.*</em:maxversion> </description> </em:targetapplication> the install.js is not supported any more and should be removed. differences as compared to other toolkit/-based applications you need to overlay/open d...
... chrome://browser/content/places/places.xul chrome://communicator/content/bookma...rksmanager.xul thunderbird uses mostly the same chrome urls for overlaying as seamonkey. there are exceptions, but these are few and far between. seamonkey also uses different ids for the menu items. ...
...pup bookmarks menu popup menu_toolspopup taskpopup taskpopup tools menu popup - windowpopup windowpopup window menu popup menu_helppopup helppopup helppopup help menu popup urlbar icons to display a button with a menupopup in the urlbar-icons for both firefox and seamonkey 2.0, use this code: <hbox id="urlbar-icons"> <image popup="myext-menu"/> </hbox> <window id="main-window"> <menupopup id="myext-menu"> <menuitem label="menuitem"/> <menuitem label="menuitem"/> </menupopup> </window> instead of <hbox id="urlbar-icons"> <button type="menu"> <menupopup> <menuitem labe...
...And 3 more matches
Developing New Mozilla Features - Archive of obsolete content
our portability requirements may be new to even seasoned developers. our cross-platform component model (“xpcom”) is similar to com, but you’ll want to make sure you use it well before going too far with your project. and of course, we have a set of coding practices to help everyone live together. ...
...o mail, spend some time helping the existing mail developers. talk to the developers about fixing some of their bugs. fix some bugs. have some of your qa team get involved. once you’re familiar with an area, do the completely unexpected and write a piece of documentation. developers will be grateful, and you’ll be known as someone seriously interested in contributing. become familiar with our code review processes. have someone on your team become mozilla-savvy enough to obtain cvs access. help the existing developers to understand that you are “for real” that you have a clue about mozilla development; that your team is going to ship a product. our developers get a lot of mail, and not all of it is helpful. we appreciate the attention and interest in mozilla, but the developers have ...
...eviewing the tree only at the milestone releases is risky if you're doing significant development. something may have changed that will cause you extra work. and you'll miss the early discussion phase when you can add your perspective to the design work. if you absolutely don't have the resources to do this, then plan for extra integration time. ...
...And 3 more matches
Drag and Drop Example - Archive of obsolete content
. the user can click on one of several xul elements on the palette and drag it onto a stack element to create an element of a particular type. first, we'll add the wrapper scripts: <script src="chrome://global/content/nsdraganddrop.js"/> <script src="chrome://global/content/nstransferable.js"/> <script src="dragboard.js"/> an additional script file dragboard.js is included which will contain the code we will write ourselves. the board will be created using a stack element. we'll use some style properties to set the width and height of the stack. a maximum size is also specified so that it doesn't resize when new elements are dragged onto it. the board will need to respond to the dragdrop event so that an element is created when the user drags onto it. <stack id="board" style="width:300...
...t we know what type of element to create when dragging. next, we'll define the two listener objects. first, the listobserver which needs a function to handle the start of the drag. var listobserver = { ondragstart: function (event, transferdata, action) { var txt = event.target.getattribute("elem"); transferdata.data = new transferdata(); transferdata.data.adddataforflavour("text/unicode", txt); } } one function has been defined, ondragstart, which will be called by the nsdraganddrop object when necessary. the function adds the data to be dragged to the transfer object. the elem attribute is retrieved from the target of the drag event. the target will be the element that had the drag start on. we'll use the value of this attribute as the data of the drag. the boardobserver wil...
.... we'll use the value of this attribute as the data of the drag. the boardobserver will need three functions, getsupportedflavours, ondragover and ondrop. the ondrop function will grab the data from the drag session and create a new element of the appropriate type. ...
...And 3 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
his can be used to display additional items that are not autocomplete results. nomatch type: boolean this attribute will be set to true if the last search resulted in no matches. overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the window object event object exampl...
...this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script cod...
...ipt type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> onerrorcommand type: script code this event handler is called when an error occurs when selecting a result from the popup. oninput type: script code this event is sent when a user enters text in a textbox. this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the autocomplete search is finished and results are available. ontextcommand obso...
...And 3 more matches
The Joy of XUL - Archive of obsolete content
of platforms that currently support mozilla, this may be one of the most compelling features of xul as a technology for building applications. since xul provides an abstraction of user interface components, it delivers on the promise of write-once, run-anywhere. the user interface for all of mozilla's core applications (browser, messenger, address book, etc.) is written in xul with one single code base supporting 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 prov...
...h html-based web applications, with less impact on the overall stability and quality of the system. easy customization, localization, or branding another highly practical benefit of the separation that xul provides among application logic, presentation, and language text is the ease of customizing for different customers or groups of users. a developer can maintain one primary code base for their application and customize the logo and branding for each of their customers by supplying different skins. an application that is written and deployed with an english language user interface can be translated to french for the same customer. while such changes are extensive and affect most (if not all) of the application, they are also isolated from one another, enabling the core xu...
...ut highly different ways. in one respect, overlays are synonymous with "include" files in other languages because an application may specify that an overlay be included in its definition. but overlays can also be specified externally, enabling the designer to superimpose them upon an application without changing the original source. in practical terms, this enables developers to maintain one code stream for a given application, then apply custom branding or include special features for customers with a completely independent code base. this leads to an overall solution that is easier and less costly to maintain in the long run. there is an additional benefit to overlays for software developers who intend to add features to mozilla that they wish to keep proprietary. the netscape publ...
...And 3 more matches
Complete - Archive of obsolete content
way. this page is not a step-by-step tutorial. instead it explains the missing features, and outlines how to add them. if you want to see these techniques in action, then you can download and install the complete allcustom extension: allcustom.xpi (the link is external only because this wiki does not support xpi files.) the extension does not contain any useful functions. it is just an extended code sample. to see the code, use a jar tool or zip tool to unpack the xpi file that you downloaded. for more information about developing extensions, see the main extensions page here. features of this extension this extension is a more complex version of the original custom toolbar button extension. it provides a user interface in two languages (english and french). it supports firefox, thunderbird,...
.... it provides all five custom toolbar buttons on all the toolbars, and it provides corresponding menu choices in seamonkey's chatzilla window. the following sections describe this extension's overall structure, and how it implements languages and themes. overall structure this extension's internal name is allcustom. it uses this name as the default file name throughout. where you see a url in the code with no file name, the application uses this default file name and an extension appropriate for the type of file expected. the extension is supplied as a xpi, which is compressed to reduce download times. the xpi contains: install.rdf information about the extension chrome.manifest registration data for firefox etc. install.js insta...
...for the type of file expected. the extension is supplied as a xpi, which is compressed to reduce download times. the xpi contains: install.rdf information about the extension chrome.manifest registration data for firefox etc. ...
...And 3 more matches
Adding Event Handlers - Archive of obsolete content
to make the find files dialog functional, we need to add some scripts which will execute when the user interacts with the dialog. we would want to add a script to handle the find button, the cancel button and to handle each menu command. we write this using javascript functions much in the same way as html. you can use the script element to include scripts in xul files. you can embed the script code directly in the xul file in between the opening and closing script tags but it is much better to include code in a separate file as the xul window will load slightly faster. the src attribute is used to link in an external script file. our find files example let's add a script to the find file dialog. although it does not matter what the script file is called, usually it would be the same as t...
...s from web content. to show errors in chrome javascript, it is necessary to change the preference javascript.options.showinconsole to true. you can also change the preference javascript.options.strict for debugging. by setting this value to true, non-standard, poorly written, or syntax prone to cause logic errors are logged to the javascript console. responding to events the script will contain code which responds to various events triggered by the user or other situations. there are about thirty or so different events that may be handled in several different ways. a typical event is the user pressing a mouse button or pressing a key. each xul element has the ability to trigger certain events in different situations. some events are triggered only by certain elements. each event has a name,...
...ll the ancestors, you may attach a listener to a specific element or to an element higher in the hierarchy. naturally, an event attached to an element higher up will receive notification of all elements inside it, whereas an event attached to a button will only receive events pertaining to that button. this is useful if there are several elements you would like to handle using the same or similar code. the most common event used is the 'command' event. the command event is fired when a user activates an element, for example by pressing a button, changing a checkbox or selecting an item from a menu. the command event is a useful event since it automatically handles different ways of activating the element. for example, the command event will occur regardless of whether the user uses the mouse ...
...And 3 more matches
More Wizards - Archive of obsolete content
ert. in some cases, it would be more convenient to disable the next button until valid input has been entered. the wizard has a property canadvance, which can be set to true to indicate that the next button should be enabled. if set to false, the next button is disabled. you can change the property when invalid or valid data has been entered. in the following example, the user must enter a secret code into a textbox on the first page of the wizard. the function checkcode() is called whenever the first page is shown as indicated by the onpageshow attribute. it is also called whenever a key is pressed in the textbox, to determine whether the next button should be enabled again. wizard example source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard ...
...page of the wizard. the function checkcode() is called whenever the first page is shown as indicated by the onpageshow attribute. it is also called whenever a key is pressed in the textbox, to determine whether the next button should be enabled again. ...
...pageshow attribute. it is also called whenever a key is pressed in the textbox, to determine whether the next button should be enabled again. ...
...And 3 more matches
Using nsIXULAppInfo - Archive of obsolete content
this is useful, for example, for extensions that support several mozilla-based applications or several versions of a single application. this is not useful for scripts on webpages, which should continue using the navigator object when it's not possible to rely on feature-detection. nsixulappinfo interface to distinguish between different mozilla-based applications, use the frozen nsixulappinfo interface. the following sections provide a few examples of using nsixulappinfo from javascript. ...
...o distinguish between different mozilla-based applications, use the frozen nsixulappinfo interface. the following sections provide a few examples of using nsixulappinfo from javascript. note that while firefox 1.5, thunderbird 1.5, and xulrunner 1.8-based applications support nsixulappinfo, older applications, such as firefox and thunderbird 1.0, do not support it. ...
...ing sections provide a few examples of using nsixulappinfo from javascript. note that while firefox 1.5, thunderbird 1.5, and xulrunner 1.8-based applications support nsixulappinfo, older applications, such as firefox and thunderbird 1.0, do not support it. you'll need to have additional code for those older versions. getting nsixulappinfo to get a component implementing nsixulappinfo use this code: var appinfo = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo); (for explanation see this creating xpcom article.) getting application information after you obtained the app info component, you can read its properties to get the application's id, human-readable name, version, platform version, etc. for complete list o...
...And 3 more matches
Adobe Flash - Archive of obsolete content
plugin, scriptability can not be used on mac os x browsers based on gecko. the example below shows a detection heuristic in action. example 1: verifying the flash plugin version below, javascript identifies the version of flash, and whether it is scriptable in netscape gecko: can we have javascript in a wiki page? <script type="text/javascript">identifyflash();</script> typically, javascript code that determines what version of the plugin is installed looks at the mimetypes array that is part of the navigator object. every plugin exposes a description string that typically includes the plugin's name and version number. the flash plugin's description string uses a standard versioning nomenclature that can then be parsed for meaningful information. for example, the current flash plugin vers...
...sh to be scriptable in mach-o browsers (on os x) by version 12. this is currently not the case, but 12 is a sufficiently high version number (current versions are version 6r.79) to allow for some leeway for fixing this down the road. when information about when this problem on mac os x will be addressed becomes available, the constant can be updated to reflect something less arbitrary. a complete code listing which expands on the above approach can be found in the flashversion.js file used in the samples. performance and flash as is the case with any plug-in content, flash content has the potential to slow down or even completely stall not just the tab it's running in, but the entire browser and even the entire computer it's being used on. avoiding poorly-written or unnecessary flash content...
...n general, to invoke a macromedia-defined method on a flash animation in netscape gecko browsers: use dom methods to get a handle to the html element that spawns the plugin. this may be the embed element or the object element's name or id attribute respectively. treat the handle to the html element as a handle to the actual flash plugin and invoke the published methods on it. the illustrative code snippet below shows this idea: <object id="myflash" ..... > <param name="movie" value="somefile.swf" /> .... var myflash = document.getelementbyid("myflash").setvariable("myvar", sendtext); a more expanded code example that shows how example 2 was created is shown in this source listing. fscommands: accessing javascript from flash note: fscommand may not work with flash player versions ...
...And 3 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
complete single-sign on solution must address the need to interoperate with enterprise systems, such as the underlying operating system, that rely on passwords or other forms of authentication. object signing communicator supports a set of tools and technologies called object signing. object signing uses standard techniques of public-key cryptography to let users get reliable information about code they download in much the same way they can get reliable information about shrink-wrapped software. most importantly, object signing helps users and network administrators implement decisions about software distributed over intranets or the internet-for example, whether to allow java applets signed by a given entity to use specific computer capabilities on specific users' machines. the "objects...
... about shrink-wrapped software. most importantly, object signing helps users and network administrators implement decisions about software distributed over intranets or the internet-for example, whether to allow java applets signed by a given entity to use specific computer capabilities on specific users' machines. the "objects" signed with object signing technology can be applets or other java code, javascript scripts, plug-ins, or any kind of file. the "signature" is a digital signature. signed objects and their signatures are typically stored in a special file called a jar file. software developers and others who wish to sign files using object-signing technology must first obtain an object-signing certificate. types of certificates common types of certificates include the following: ...
...ed s/mime and ssl certificates solely for the purpose of authenticating employee identities, thus permitting signed email and client ssl authentication but not encrypted email. another company issues s/mime certificates solely for the purpose of both signing and encrypting email that deals with sensitive financial or legal matters. object-signing certificates. used to identify signers of java code, javascript scripts, or other signed files. for more information, see "object signing". example: a software company signs software distributed over the internet to provide users with some assurance that the software is a legitimate product of that company. using certificates and digital signatures in this manner can also make it possible for users to identify and control the kind of access do...
...And 3 more matches
Building up a basic demo with A-Frame - Game development
, and save the follow html inside it: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: a-frame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- html goes here --> </body> </html> this contains some basic information like the document charset and <title>. the <script> element includes the a-frame framework in the page; we will write our example code inside the <body> element. initializing the scene a scene is the place where everything happens. when creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. in a-frame, the scene is reperesented by a scene entity. note: an entity is any element — it can be an object like a box, cylinder or cone, but it can also be a camera, light or sou...
...background: sky box a sky box is a background for the 3d world, represented by an <a-sky> element. in our case we will use a simple color, but it could also be an image, etc. looking around would give an impression of being inside an open sky, a wooden barn — wherever you like! add the following html before the <a-cube> element: <a-sky color="#dddddd"></a-sky> at this point, if you save the code and refresh your browser you can already see the cube on the screen with our custom background: here's the code we have created so far: you can also check it out on github. a-frame takes care of setting up everything you need: a default light source and camera are included, so the cube is visible. the controls are already working: you can use the mouse for looking around and the keyboa...
...set its scale so it will more easily visible, its color, and some opacity so it won't completely covering the objects behind it. adding lights the basic light types in a-frame are directional and ambient. the first type is a directional light placed somewhere on the scene while the second one reflects the light from the first type, so it looks more natural; this can be set globally. add the new code below your previous additions — this uses the standard <a-light> element: <a-light type="directional" color="#fff" intensity="0.5" position="-1 1 2"> </a-light> <a-light type="ambient" color="#fff"> </a-light> the directional light has a white color, its intensity is set to 0.5, and it is placed at position -1 1 2. the ambient light only needs a color, which is also white. addin...
...And 3 more matches
Async scripts for asm.js - Game development
to see the difference, toggle javascript.options.parallel_parsing in about:config. ...
...to see the difference, toggle javascript.options.parallel_parsing in about:config. ...
.../script> or, to do the same thing via script: var script = document.createelement('script'); script.src = "file.js"; document.body.appendchild(script); (scripts created from script default to async.) the default html shell emscripten generates produces the latter. ...
...And 3 more matches
Implementing controls using the Gamepad API - Game development
owed us to use console gamepads with desktop games — either native games or those running in the browser. now in the era of html5, we finally have the gamepad api, which gives us the ability to play browser-based games using gamepad controllers without any plugins. the gamepad api achieves this by providing an interface exposing button presses and axis changes that can be used inside javascript code to handle the input. these are good times for browser gaming. api status and browser support the gamepad api is still at the working draft stage in the w3c process, which means its implementation might still change, but saying that the browser support is already quite good. firefox 29+ and chrome 35+ support it out of the box. opera supports the api in version 22+ (not surprising given that th...
...orting the gamepad api. which gamepads are best? the most popular gamepads right now are those from the xbox 360, xbox one, ps3 and ps4 — they have been heavily tested and work well with the gamepad api implementation in browsers across windows and mac os x. there's also a number of other devices with various different button layouts that more or less work across browser implementations. the code discussed in this article was tested with a few gamepads, but the author's favorite configuration is a wireless xbox 360 controller and the firefox browser on mac os x. case study: hungry fridge the github game off ii competition ran in november 2013 and enclave games decided to take part in it. the theme for the competition was "change", so they submitted a game where you have to feed the hung...
...oot down the food, but once again you also have to find the type of food the fridge wants to eat at each point, or else you'll lose energy. the game encapsulates two totally different types of "change" — good food vs. bad food, and mobile vs. desktop. ...
...And 3 more matches
Build the brick field - Game development
« previousnext » this is the 6th step out of 10 of the gamedev canvas tutorial. you can find the source code as it would look after completing this lesson at gamedev-canvas-workshop/lesson6.html. after modifying the gameplay mechanics, we are now able to lose — this is great as it means the game is finally feeling more like a game. however, it will quickly get boring if all you do is bounce the ball off the walls and the paddle. what a breakout game really needs is some bricks to destroy with the ball, and this is what we'll create now! setting up the brick variables the overall aim of this lesson is to render a few lines of code for the bricks, using a nested loop that works through a two-dimensional array. first however we need to set up some variables to define informat...
...ith the ball, and this is what we'll create now! setting up the brick variables the overall aim of this lesson is to render a few lines of code for the bricks, using a nested loop that works through a two-dimensional array. first however we need to set up some variables to define information about the bricks such as their width and height, rows and columns, etc. add the following lines to your code below the variables which you have previously declared in your program. var brickrowcount = 3; var brickcolumncount = 5; var brickwidth = 75; var brickheight = 20; var brickpadding = 10; var brickoffsettop = 30; var brickoffsetleft = 30; here we've defined the number of rows and columns of bricks , their width and height, the padding between the bricks so they won't touch each other and a top a...
...tain the brick columns (c), which in turn will contain the brick rows (r), which in turn will each contain an object containing the x and y position to paint each brick on the screen. ...
...And 3 more matches
Extra lives - Game development
« previousnext » this is the 13th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson13.html. we can make the game enjoyable for longer by adding lives. in this article we'll implement a lives system, so that the player can continue playing until they have lost three lives, not just one. new variables add the following new variables below the existing ones in your code: var lives = 3; var livestext; var lifelosttext; these respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives. defining the new text labels defining ...
...if we ever want to change the font size or color we will have to do it in multiple places. ...
...; livestext = game.add.text(game.world.width-5, 5, 'lives: '+lives, textstyle); livestext.anchor.set(1,0); lifelosttext = game.add.text(game.world.width*0.5, game.world.height*0.5, 'life lost, click to continue', textstyle); lifelosttext.anchor.set(0.5); lifelosttext.visible = false; this way changing the font in one variable will apply the changes to every place it is used. the lives handling code to implement lives in our game, let's first change the ball's function bound to the onoutofbounds event. instead of executing an anonymous function and showing the alert right away : ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); we will assign a new function called ballleavescreen; delete the previous event handler (shown above) and replac...
...And 3 more matches
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
n that function, etc. when a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. any functions that are called by that function are added to the call stack further up, and run where their calls are reached. ...
...e called by that function are added to the call stack further up, and run where their calls are reached. when the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. if the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. ...
... the call stack further up, and run where their calls are reached. when the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. if the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. example function greeting() { // [1] some codes here sayhi(); // [2] some codes here } function sayhi() { return "hi!"; } // invoke the `greeting` function greeting(); // [3] some codes here the code above would be executed like this: ignore all functions, until it reaches the greeting() function invocation. add the greeting() function to the call stack list. call stack list: - greeting execute all lines of code inside the greeting() function. get ...
...And 3 more matches
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
ecmascript® 2015 language specification. hoisting was thought up as a general way of thinking about how execution contexts (specifically the creation and execution phases) work in javascript. however, the concept can be a little confusing at first. ...
...vascript. however, the concept can be a little confusing at first. conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. ...
...t variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. learn more technical example one of the advantages of javascript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. for example: function catname(name) { console.log("my cat's name is " + name); } catname("tiger"); /* the result of the code above is: "my cat's name is tiger" */ the above code snippet is how you would expect to write the code for it to work. now, let's see what happens when we call the function before we ...
...And 3 more matches
Test your skills: CSS and JavaScript accessibility - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. css accessibility 1 in the first task you are presented with a list of links. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. css accessibility 1 in the first task you are presented with a list of links. ...
......
...And 3 more matches
Test your skills: The Box Model - Learn web development
the aim of this task is to help you check your understanding of the css box model. note: you can try out solutions in the interactive editors below, however, it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. the box model one with the two boxes below, one is using the standard box model, the other the alternate box model. ...
... — see the assessment or further help section at the bottom of this page. the box model one with the two boxes below, one is using the standard box model, the other the alternate box model. change the width of the second box by adding rules to the .alternate class, so that it matches the visual width of the first box. your final result will look like the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. the box model two in this task, add to the box: a 5px, black, dotted border. a top margin of 20px. a right margin of 1em. a bottom margin of 40px. a left margin of 2em. padding on all sides of 1em. try upda...
...eate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. the box model two in this task, add to the box: a 5px, black, dotted border. a top margin of 20px. a right margin of 1em. a bottom margin of 40px. a left margin of 2em. padding on all sides of 1em. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. the box model three in this example the inline element has a margin, padding and border however the lines above and below are overlapping it. what can you add to your css to cause the size of the margi...
...And 3 more matches
Test your skills: backgrounds and borders - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...u to add a background, border, and some simple styling to a page header: give the box a 5px black solid border, with rounded corners of 10px. add a background image (use the url balloons.jpg) and size it so that it covers the box. give the <h2> a semi-transparent black background color, and make the text white. the finished example should look like the image below. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. backgrounds and borders 2 in this task we want you to add background images, a border, and some other styling to a decorative box: give the box a 5px lightblue border, and round the top left corner 20px and the bottom right corner 40px the heading uses th...
...And 3 more matches
Test your skills: values and units - Learn web development
the aim of this task is to help you check your understanding of some of the values and units that we looked at in the lesson on css values and units. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one in this task, the first list item has been given a background color using hex color codes. your task is to complete the css using the same color in different formats, plus a final list item where you should make the background semi-opaque. the second list item should use rgb color. the third should use hsl color. the f...
...ng the same color in different formats, plus a final list item where you should make the background semi-opaque. the second list item should use rgb color. the third should use hsl color. the fourth should use rgb color but with the alpha channel set to .2. you can find conversions for the hex color at this link. you need to figure out how to use the values in css. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in this task you need to set the size of various items of text. the <h1> should be 50 pixels. the <h2> should be 2em. all <p> elements should be 16 pixels. a <p> element that is directly after an <h1> sh...
... for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in this task you need to set the size of various items of text. the <h1> should be 50 pixels. the <h2> should be 2em. all <p> elements should be 16 pixels. a <p> element that is directly after an <h1> should be 120%. ...
...And 3 more matches
Test your skills: Writing Modes and Logical Properties - Learn web development
the aim of this task is to help you check your understanding of writing modes and logical properties. the things you need to know to complete these tasks are covered in the lesson on handling different text directions. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. ...
...or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one the box in the example is displayed with a horizontal writing mode. can you add a line of css to change it so it uses a vertical writing mode with right to left text? your example should look like the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in the example below use logical properties to replace width and height in order to maintain the aspect ratio of the box as it is turned vertically. your end result should look like the image below. try upd...
...ate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in the example below use logical properties to replace width and height in order to maintain the aspect ratio of the box as it is turned vertically. your end result should look like the image below. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task three use logical versions of the margin, border, and padding properties so that the edges of the box relate to the text rather than following top, left, bottom and right. you can see how this sho...
...And 3 more matches
Test your skills: floats - Learn web development
the aim of this task is to get you working with the css float and clear properties covered in our lesson on floats. you will be working through three small tasks which use different elements of the material you have just covered. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. ...
... float two in this example the element with a class of float should be floated left. ...
...d the starting point for this task to work in your own editor or in an online editor. float two in this example the element with a class of float should be floated left. then we want the first line of text to display next to that element, but the following line of text (which has a class of .below) to display underneath it. you can see the desired result in this image. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. float three finally, we have a floated element in this example. the box wrapping the float and text is displaying behind the float. use the most up to date method available to cause the box background to extend to belo...
...And 3 more matches
Responsive design - Learn web development
o fill the browser window or a fixed width site, which would be a fixed size in pixels. these two approaches tended to result in a website that looked its best on the screen of the person designing the site! the liquid site resulted in a squashed design on smaller screens (as seen below) and unreadably long line lengths on larger ones. note: see this simple liquid layout: example, source code. when viewing the example, drag your browser window in and out to see how this looks at different sizes. the fixed-width site risked a horizontal scrollbar on screens smaller than the site width (as seen below), and lots of white space at the edges of the design on larger screens. note: see this simple fixed-width layout: example, source code. again, observe the result as you change the b...
..., so it is worth understanding it, even though you would not build a modern site using a float-based flexible grid. the following example demonstrates a simple responsive design using media queries and a flexible grid. on narrow screens the layout displays the boxes stacked on top of one another: on wider screens they move to two columns: note: you can find the live example and source code for this example on github. modern layout technologies modern layout methods such as multiple-column layout, flexbox, and grid are responsive by default. they all assume that you are trying to create a flexible grid and give you easier ways to do so. multicol the oldest of these layout methods is multicol — when you specify a column-count, this indicates how many columns you want your cont...
...e flex container, using the shorthand of flex: 1 as described in the layout topic flexbox: flexible sizing of flex items. .container { display: flex; } .item { flex: 1; } note: as an example, we have rebuilt the simple responsive layout above, this time using flexbox. you can see how we no longer need to use strange percentage values to calculate the size of the columns: example, source code. css grid in css grid layout the fr unit allows the distribution of available space across grid tracks. the next example creates a grid container with three tracks sized at 1fr. this will create three column tracks, each taking one part of the available space in the container. you can find out more about this approach to create a grid in the learn layout grids topic, under flexible grids with ...
...And 3 more matches
How do I use GitHub Pages? - Learn web development
github is a "social coding" site. it allows you to upload code repositories for storage in the git version control system. you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it. you can do that with other people's code too! this article provides a basic guide to publishing content using github's gh-pages feature. publishing content github is a very important and useful community to get involved in, and git/github is a very popular version control system — most tech companies now use it in their workflow. github has a very useful feature called github pages, which allows you to publish website code live on the web. basic github setup first of all, i...
...y useful feature called github pages, which allows you to publish website code live on the web. basic github setup first of all, install git on your machine. this is the underlying version control system software that github works on top of. next, sign up for a github account. it's simple and easy. once you've signed up, log in to github.com with your username and password. preparing your code for upload you can store any code you like in a github repository, but to use the github pages feature to full effect, your code should be structured as a typical website, e.g. with the primary entry point being an html file called index.html. the other thing you need to do before moving on is to initialise your code directory as a git repository. to do this: point the command line to your t...
...and (i.e. "change directory"). here's what you'd type if you've put your website in a directory called test-site on your desktop: cd desktop/test-site when the command line is pointing inside your website directory, type the following command, which tells the git tool to turn the directory into a git repository: git init an aside on command line interfaces the best way to upload your code to github is via the command line — this is a window where you type in commands to do things like create files and run programs, rather than clicking inside a user interface. it will look something like this: note: you could also consider using a git graphical user interface to do the same work, if you feel uncomfortable with the command line. every operating system comes with a command l...
...And 3 more matches
Test your skills: Advanced styling - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...earch box is a magnifying glass icon. we've made one available in the same directory as our html files — see search-24px.png — plus a <div> element after the search input to help you attach it, should you need it. can you figure out a sensible way to attach it, and can you use some css to get it to sit to the right of the search box, and be lined up vertically as well? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. advanced form styling 2 in our next task we provide you with a set of three radio buttons. we want you to give them custom styling. we've already provided you with a basic reset to build upon. first of all, get rid of their default styling. next, give th...
...And 3 more matches
Test your skills: Basic controls - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. basic controls 1 this task starts you off nice and gently by asking you to create two <input> elements, for a user's id and password, along with a submit button. ...
... basic controls 1 this task starts you off nice and gently by asking you to create two <input> elements, for a user's id and password, along with a submit button. create appropriate inputs for user id and password. you should also associate them with their text labels semantically. create a submit button inside the remaining list item, with button text of "log in". try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. basic controls 2 the next task requires you to create working sets of checkboxes and radio buttons, from the provided text labels. turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at ...
...f checkboxes and radio buttons, from the provided text labels. turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at once. make it so that the first radio button is selected upon page load. turn the second <fieldset>'s content into a set of checkboxes. add a couple more hotdog choices of your own. ...
...And 3 more matches
Test your skills: Other controls - Learn web development
this aim of this skill test is to assess whether you've understood our other form controls article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. other controls 1 in our first "other controls" assessment, we'll get you to create a multi-line text input. create a basic multi-line text input. ...
...ion at the bottom of this page. other controls 1 in our first "other controls" assessment, we'll get you to create a multi-line text input. create a basic multi-line text input. associate it semantically with the provided "comment" label. give the input 35 columns, and 10 rows of space in which to add comments. give the comments a maximum length of 100 characters. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. other controls 2 now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favourite food from the choices provided. create your basic select box structure. associate it semantically with the provided "comment" labe...
...itor or in an online editor. other controls 2 now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favourite food from the choices provided. create your basic select box structure. associate it semantically with the provided "comment" label. inside the list, split the choices up into 2 subgroups — "mains" and "snacks". try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. other controls 3 in our final task of this set, we start with much the same list of food choices. however, this time we want to do things differently: create a basic text input that is semantically associated with the provided label. put the food choices ...
...And 3 more matches
Your first form - Learn web development
pdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the <input> element, although there are some other elements to learn about too. form controls can also be programmed to enforce specific formats or values to be entered (form validation), and paired with text labels that describe their purpose to both sighted and blind users. designing your form before starting to code, it's always better to step back and take the time to think about your form. designing a quick mockup will help you to define the right set of data you want to ask your user to enter. from a user experience (ux) point of view, it's important to remember that the bigger your form, the more you risk frustrating people and losing users. keep it simple and stay focused: ask only for the data you abso...
...ments our contact form is not complex: the data entry portion contains three text fields, each with a corresponding <label>: the input field for the name is a single-line text field. the input field for the e-mail is an input of type email: a single-line text field that accepts only e-mail addresses. the input field for the message is a <textarea>; a multiline text field. ...
...for usability and accessibility, we include an explicit label for each form control. note the use of the for attribute on all <label> elements, which takes as its value the id of the form control with which it is associated — this is how you associate a for...
...And 3 more matches
Publishing your website - Learn web development
what are the options? publishing a website is a complex topic because there are many ways to go about it. this article doesn't attempt to document all the possible methods. instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. then it steps through one method that can work right away for many readers. ...
...re are also free services available like neocities, blogger, and wordpress. sometimes you get what you pay for, but sometimes these resources are good enough for your initial experiments. many companies provide hosting and domains. using an online tool like github or google app engine some tools let you publish your website online: github is a "social coding" site. it allows you to upload code repositories for storage in the git version control system. you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it. github has a very useful feature called github pages, which allows you to expose website code live on the web. google app engine is a powerful platform...
... google app engine is a powerful platform that lets you build and run applications on google’s infrastructure — whether you need to build a multi-tiered web application from scratch or host a static website. see how do you host your website on google app engine? for more information. these options are usually free, but you may outgrow the limited feature-set. ...
...And 3 more matches
Getting started with the Web - Learn web development
the story of your first website it's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small. you won't build another facebook right away, but it's not hard to get your own simple website online, so we'll start there. ...
... away, but it's not hard to get your own simple website online, so we'll start there. by working through the articles listed below in order, you will go from nothing to getting your first webpage online. let's begin our journey! installing basic software when it comes to tools for building a website, there's a lot to pick from. if you're just starting out, you might be confused by the array of code editors, frameworks, and testing tools out there. in installing basic software, we show you step-by-step how to install just the software you need to begin some basic web development. what will your website look like? before you start writing the code for your website, you should plan it first. what information are you showcasing? what fonts and colors are you using? what will your website look...
...basic web development. what will your website look like? before you start writing the code for your website, you should plan it first. what information are you showcasing? what fonts and colors are you using? what will your website look like? ...
...And 3 more matches
Responsive images - Learn web development
amine a typical scenario. a typical website may contain a header image and some content images below the header. the header image will likely span the whole of the width of the header, and the content image will fit somewhere inside the content column. here's a simple example: this works well on a wide screen device, such as a laptop or desktop (you can see the example live and find the source code on github.) we won't discuss the css much in this lesson, except to say that: the body content has been set to a maximum width of 1200 pixels — in viewports above that width, the body remains at 1200px and centers itself in the available space. in viewports below that width, the body will stay at 100% of the width of the viewport. the header image has been set so that its center always stay...
...element traditionally only lets you point the browser to a single source file: <img src="elva-fairy-800w.jpg" alt="elva dressed as a fairy"> we can however use two new attributes — srcset and sizes — to provide several additional source images along with hints to help the browser pick the right one. you can see an example of this in our responsive.html example on github (see also the source code): <img srcset="elva-fairy-480w.jpg 480w, elva-fairy-800w.jpg 800w" sizes="(max-width: 600px) 480px, 800px" src="elva-fairy-800w.jpg" alt="elva dressed as a fairy"> the srcset and sizes attributes look complicated, but they're not too hard to understand if you format them as shown above, with a different part of the attribute value on each line. each value...
... size, different resolutions if you're supporting multiple display resolutions, but everyone sees your image at the same real-world size on the screen, you can allow the browser to choose an appropriate resolution image by using srcset with x-descriptors and without sizes — a somewhat easier syntax! ...
...And 3 more matches
JavaScript building blocks - Learn web development
you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. ...
...n you need to work towards your goal. get started prerequisites before starting this module, you should have some familiarity with the basics of html and css, and you should have also worked through our previous module, javascript first steps. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides making decisions in your code — conditionals in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. for example, in a game, if the player's number of lives is 0, then it's game over. in a weather app, if it is being looked at in the morning, show a sunri...
...g language, code needs to make decisions and carry out actions accordingly depending on different inputs. for example, in a game, if the player's number of lives is 0, then it's game over. in a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. in this article we'll explore how conditional structures work in javascript. looping code sometimes you need a task done more than once in a row. for example, looking through a list of names. in programming, loops perform this job very well. here we will look at loop structures in javascript. functions — reusable blocks of code another essential concept in coding is functions. ...
...And 3 more matches
Manipulating documents - Learn web development
for good reasons, mostly centering around security. imagine if a web site could get access to your stored passwords or other sensitive information, and log into websites as if it were you? despite the limitations, web apis still give us access to a lot of functionality that enable us to do a great many things with web pages. there are a few really obvious bits you'll reference regularly in your code — consider the following diagram, which represents the main parts of a browser directly involved in viewing web pages: the window is the browser tab that a web page is loaded into; this is represented in javascript by the window object. using methods available on this object you can do things like return the window's size (see window.innerwidth and window.innerheight), manipulate the docum...
... correct elements as it renders a page, and developers like you can manipulate the dom with javascript after the page has been rendered. we have created a simple example page at dom-example.html (see it live also). try opening this up in your browser — it is a very simple page containing a <section> element inside which you can find an image, and a paragraph with a link inside. ...
...rent node: a node which has another node inside it. for example, body is the parent node of section in the above example. sibling nodes: nodes that sit on the same level in the dom tree. for example, img and p are siblings in the above example. text node: a node containing a text string. it is useful to familiarize yourself with this terminology before working with the dom, as a number of the code terms you'll come across make use of them. you may have also come across them if you have studied css (e.g. descendant selector, child selector). active learning: basic dom manipulation to start learning about dom manipulation, let's begin with a practical example. take a local copy of the dom-example.html page and the image that goes along with it. add a <script></script> element just abov...
...And 3 more matches
Video and Audio APIs - Learn web development
we can see all the information — one box is not obscuring another. implementing the javascript we've got a fairly complete html and css interface already; now we just need to wire up all the buttons to get the controls working. create a new javascript file in the same directory level as your index.html file. call it custom-player.js. ...
...e are creating constants to hold references to all the objects we want to manipulate. we have three groups: the <video> element, and the controls bar. the play/pause, stop, rewind, and fast forward buttons. the outer timer wrapper <div>, the digital timer readout <span>, and the inner <div> that gets wider as the time elapses. ...
...e following at the bottom of your code: media.removeattribute('controls'); controls.style.visibility = 'visible'; these two lines remove the default browser controls from the video, and make the custom controls visible. playing and pausing the video let's implement probably the most important control — the play/pause button. ...
...And 3 more matches
Basic math in JavaScript — numbers and operators - Learn web development
e course. for example, say you wanted to loop through a list of prices, and add sales tax to each one. you'd use a loop to go through each value in turn and do the necessary calculation for adding the sales tax in each case. the incrementor is used to move to the next value when needed. we've actually provided a simple example showing how this is done — check it out live, and look at the source code to see if you can spot the incrementors! we'll look at loops in detail later on in the course. let's try playing with these in your console. for a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. the following will return an error: 3++; so, you can only increment an ex...
... are operators that assign a value to a variable. we have already used the most basic one, =, loads of times — it simply assigns the variable on the left the value stated on the right: let x = 3; // x contains the value 3 let y = 4; // y contains the value 4 x = y; // x now contains the same value y contains, 4 but there are some more complex types, which provide useful shortcuts to keep your code neater and more efficient. the most common are listed below: operator name purpose example shortcut for += addition assignment adds the value on the right to the variable value on the left, then returns the new variable value x += 4; x = x + 4; -= subtraction assignment subtracts the value on the right from the variable value on the le...
...ercise, you will manipulate some numbers and operators to change the size of a box. the box is drawn using a browser api called the canvas api. there is no need to worry about how this works — just concentrate on the math for now. the width and height of the box (in pixels) are defined by the variables x and y, which are initially both given a value of 50. open in new window in the editable code box above, there are two lines marked with a comment that we'd like you to update to make the box grow/shrink to certain sizes, using certain operators and/or values in each case. let's try the following: change the line that calculates x so the box is still 50px wide, but the 50 is calculated using the numbers 43 and 7 and an arithmetic operator. change the line that calculates y so the box ...
...And 3 more matches
Test your skills: Arrays - Learn web development
this aim of this skill test is to assess whether you've understood our arrays article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). arrays 1 let's start off with some basic array practice. in this task we'd like you to create an array of three items, stored inside a variable called...
... let's start off with some basic array practice. in this task we'd like you to create an array of three items, stored inside a variable called myarray. the items can be anything you want — how about your favourite foods or bands? next, modify the first two items in the array using simple bracket notation and assignment. then add a new item to the beginning of the array. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. arrays 2 now let's move on to another task. here you are provided with a string to work with. we'd like you to: convert the string into an array, removing the + characters in the process. save the result in a variable called myarray. store the length of t...
...itor. arrays 2 now let's move on to another task. here you are provided with a string to work with. we'd like you to: convert the string into an array, removing the + characters in the process. save the result in a variable called myarray. store the length of the array in a variable called arraylength. store the last item in the array in a variable called lastitem. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. arrays 3 for this final array task, we provide you with a starting array, and you will work in somewhat the opposite direction. you need to: remove the last item in the array. add two new names to the end of the array. go over each item in the array and ...
...And 3 more matches
Test your skills: Math - Learn web development
this aim of this skill test is to assess whether you've understood our basic math in javascript — numbers and operators article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). math 1 let's start out by testing your knowledge of basic math operators. you will have to create four num...
...e downloadable version). math 1 let's start out by testing your knowledge of basic math operators. you will have to create four numeric values, then add the first two together, then subtract the fourth from the third, then multiply the two secondary results together to get a result of 48. finally, we need to write a test that proves that this value is an even number. so, try updating the live code below to recreate the finished example, following these steps: create four variables that contain numbers. call the variables something sensible. add the first two variables together and store the result in another variable. subtract the fourth variable from the third and store the result in another variable. multiply the results from the last two steps together, storing the result in a var...
...ond task you are already provided with two calculations, with the results stored in the variables result and result2. but these results aren't what we want; you'll need to take the calculations and change them to give us what we want. what do we want? after multiplying the two results together and formatting the result to 2 decimal places, the final result should be 10.42. try updating the live code below to recreate the finished example, following these steps: write a calculation that multiplies result and result2 together and assigns the result back to result. this will require assignment shorthand. write a line of code that takes result and formats it to 2 decimal places, storing the result of this in a variable called finalresult. check the data type of finalresult using typeof; you...
...And 3 more matches
Test your skills: variables - Learn web development
this aim of this skill test is to assess whether you've understood our storing the information you need — variables article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). variables 1 in this task we want you to: declare a variable called myname. initialize myname with a suitable...
...out the answer (or into the browser's javascript console, in the case of the downloadable version). variables 1 in this task we want you to: declare a variable called myname. initialize myname with a suitable value, on a separate line (you can use your actual name, or something else). declare a variable called myage and initialize it with a value, on the same line. ...
...are a variable called myage and initialize it with a value, on the same line. 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. variables 2 in this task you need to add a new line to correct the value stored in the existing myname variable to your own name. 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. variables 3 the final task for now — in this case you are provided with some existing code, which has two errors present in it. the results panel should be outputting the name chris, and a statement about how old chris will be in 20 years' time. how can you...
...And 3 more matches
Test your skills: Object-oriented JavaScript - Learn web development
the aim of this skill test is to assess whether you've understood our object-oriented javascript for beginners, object prototypes, and inheritance in javascript articles. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. note: in the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version). oojs 1 in this task we provide you with a constructor. we want you...
...the shape class called square. give it a name of square and a sidelength of 5. call your calcperimeter() method on the instance, to see whether it logs the calculation result to the browser devtools' console as expected. create a new instance of shape called triangle, with a name of triangle and a sidelength of 3. call triangle.calcperimeter() to check that it works ok. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() f...
... task to work in your own editor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling their calcperimeter() methods. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 3 finally, we'd like you to start with the es shape class you created in the last task. we'd like you to create a square class that inherits from shape, and adds a calcarea() method that calculates the square's area. also set up the constructor so that ...
...And 3 more matches
Componentizing our React app - Learn web development
todo list app into components. defining our first component defining a component can seem tricky until you have some practice, but the gist is: if it represents an obvious "chunk" of your app, it's probably a component if it gets reused often, it's probably a component. that second bullet is especially valuable: making a component out of common ui elements allows you to change your code in one place and see those changes everywhere that component is used. you don't have to break everything out into components right away, either. let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the ui: a todo list item. make a <todo /> before we can make a component, we should create a new file for it. in fact, we should make...
...s. the following commands make a components directory and then, within that, a file called todo.js. ...
...ory and then, within that, a file called todo.js. make sure you're in the root of your app before you run these! mkdir src/components touch src/components/todo.js our new todo.js file is currently empty! open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that to todo.js too, as follows. ...
...And 3 more matches
Understanding client-side JavaScript frameworks - Learn web development
rward and learn about frameworks in a pragmatic way that doesn't forget about web platform fundamental best practices such as accessibility. get started now, with "introduction to client-side frameworks" prerequisites you should really learn the basics of the core web languages first before attempting to move on to learning client-side frameworks — html, css, and especially javascript. your code will be richer and more professional as a result, and you'll be able to troubleshoot problems with more confidence if you understand the fundamental web platform features that the frameworks are building on top of. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started introductor...
... the dom, handling browser events, and providing an enjoyable developer experience. this article will explore the main features of “the big 4” frameworks, looking at how frameworks tend to work from a high level and the differences between them. react tutorials note: react tutorials last tested in may 2020, with react/reactdom 16.13.1 and create-react-app 3.4.1. if you need to check your code against our version, you can find a finished version of the sample react app code in our todo-react repository. for a running live version, see https://mdn.github.io/todo-react-build/. 1. getting started with react in this article we will say hello to react. we'll discover a little bit of detail about its background and use cases, set up a basic react toolchain on our local computer, and cre...
...y, including focus management in react, which can improve usability and reduce confusion for both keyboard-only and screen reader users. 7. react resources our final article provides you with a list of react resources that you can use to go further in your learning. ember tutorials note: ember tutorials last tested in may 2020, with ember/ember cli version 3.18.0. if you need to check your code against our version, you can find a finished version of the sample ember app code in the ember-todomvc-tutorial repository. for a running live version, see https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (this also includes a few additional features not covered in the tutorial). 1. getting started with ember in our first ember article we will look at how ember works and what it's use...
...And 3 more matches
Implementing feature detection - Learn web development
this article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports. prerequisites: familiarity with the core html, css, and javascript languages; an idea of the high-level principles of cross-browser testing. ...
...a of the high-level principles of cross-browser testing. objective: to understand what the concept of feature detection is, and be able to implement suitable solutions in css and javascript. the concept of feature detection the idea behind feature detection is that you can run a test to determine whether a feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that do support the feature, and browsers that don't. if you don't do this, browsers that don't support the features you are using in your code won't display your sites properly and will just fail, creating a bad user experience. let's recap and look at the example we touched on in our handling common javascript problems — the geolocation ap...
...riting your own all the time. modernizr is the industry standard for feature detection tests, and we'll look at that later on. before we move on, we'd like to say one thing upfront — don't confuse feature detection with browser sniffing (detecting what specific browser is accessing the site) — this is a terrible practice that should be discouraged at all costs. see using bad browser sniffing code for more details. writing your own feature detection tests in this section, we'll look at implementing your own feature detection tests, in both css and javascript. css you can write tests for css features by testing for the existence of element.style.property (e.g. paragraph.style.transform) in javascript. a classic example might be to test for flexbox support in a browser; for browsers tha...
...And 3 more matches
Multiprocess on Windows
should have a solid understanding of what apartments are. unfortunately this topic is often poorly explained. one of the better pieces of documentation is a two-part series written by jeff prosise: understanding com apartments, part i understanding com apartments, part ii for the purposes of this document, "com" will refer to microsoft com (as opposed to xpcom). gecko and apartments most code that runs on gecko's main thread is not thread safe. since gecko's main thread uses com, and com requires threads to declare their threading model, the main thread must initialize itself to live inside its own single threaded apartment (sta). this is true for both chrome and content processes. as you should already know from the prerequisite reading, single threaded apartments receive remote pro...
...this uses a com technology called the interceptor. interceptors are, essentially, wrapper objects which implement the same interfaces as the object that they are wrapping. when an incoming rpc invokes a method on an interceptor, the interceptor dispatches a callback that allows us...
...ming rpc invokes a method on an interceptor, the interceptor dispatches a callback that allows us to do whatever we want with that request. our callback implementation forwards the method call to the main thread in order to invoke the method on the wrapped object. the interceptor is also aware that any outparams, which contain interfaces, must also be wrapped with interceptors of their own. this code lives in the mscom library, located in the tree at /ipc/mscom. its headers are exported to mozilla/mscom. ensuring that the interceptor supports your interfaces this information is current, but is likely to change when bug 1346957 is landed. interceptors cannot replicate interfaces without access to the metadata that describes those interfaces. since we are using com, we already generate met...
...And 3 more matches
Creating Sandboxed HTTP Connections
text, astream, asourceoffset, alength) { var scriptableinputstream = components.classes["@mozilla.org/scriptableinputstream;1"] .createinstance(components.interfaces.nsiscriptableinputstream); scriptableinputstream.init(astream); this.mdata += scriptableinputstream.read(alength); }, onstoprequest: function (arequest, acontext, astatus) { if (components.issuccesscode(astatus)) { // request was successfull this.mcallbackfunc(this.mdata); } else { // request failed this.mcallbackfunc(null); } gchannel = null; }, // nsichanneleventsink onchannelredirect: function (aoldchannel, anewchannel, aflags) { // if redirecting, store the new channel gchannel = anewchannel; }, // nsiinterfacerequestor getinterface:...
...it would be better to have the entire implementation inside a class and storing the channel as a member: function myclass() { this.mchannel = null; // ... var listener = new this.streamlistener(callbackfunc); // ... } myclass.prototype.streamlistener = function (acallbackfunc) { return ({ mdata: "", // ... }) } handling cookies when sending a request, cooki...
...he observe method gets passed in three arguments, which for the two cookie topics are: asubject: the channel (nsichannel) that caused this notification to happen. atopic: the notification topic. adata: null for the two topics. since the observers get notified for the registered topic for any connection, the listener needs to make sure that the notification is for the http connection our code created. since the channel that causes the notification is passed in as the first argument, comparing it to the globally stored channel (gchannel) in the previous section (which also gets updated each time a redirect happens). // create an nsiobserver implementor var listener = { observe : function(asubject, atopic, adata) { // make sure it is our connection first. if (asubject == gcha...
...And 3 more matches
Debugging on Windows
: set xpcom_debug_break=warn the environment variable takes also other values besides warn, see xpcom_debug_break for more details. note that unlike unix, the default for windows is not warn, it's to pop up a dialog. to set the environment variable for visual studio, use project > properties > debugging > environment and click the little box. ...
...check the memory address for that line. now open memory view. ...
...check the memory address for that line. now open memory view. ...
...And 3 more matches
Configuring Build Options
zconfig file. mozconfig contains two types of options: options prefixed with mk_add_options are passed to client.mk. the most important of these is moz_objdir, which controls where your application gets built (also known as the object directory). options prefixed with ac_add_options are passed to configure, and affect the build process. building with an objdir this means that the source code and object files are not intermingled in your directory system and you can build multiple applications (e.g., firefox and thunderbird) from the same source tree. if you do not specify a moz_objdir, it will be automatically set to @topsrcdir@/obj-@config_guess@. if you need to re-run configure, the easiest way to do it is using ./mach configure; running configure manually is strongly discouraged.
...thunderbird) ac_add_options --enable-application=comm/mail ac_add_options --enable-calendar selecting build options the build options you choose depends on what application you are building and what you will be using the build for. if you want to use the build regularly, you will want a release build without extra debugging information; if you are a developer who wants to hack the source code, you probably want a non-optimized build with extra debugging macros. there are many options recognized by the configure script which are special-purpose options intended for embedders or other special situations, and should not be used to build the full suite/xul applications. the full list of options can be obtained by running ./configure --help. warning: do not use a configure option un...
...uild will compile and run correctly. the following build options are very common: optimization ac_add_options --enable-optimize enables the default compiler optimization options note: this is enabled by default ac_add_options --enable-optimize=-o2 chooses particular compiler optimization options. in most cases, this will not give the desired results, unless you know the mozilla codebase very well; note, however, that if you are building with the microsoft compilers, you probably do want this as -o1 will optimize for size, unlike gcc. ac_add_options --enable-debug enables assertions in c++ and javascript, plus other debug-only code. this can significantly slow a build, but it is invaluable when writing patches. people developing patches (especially in c++) should generally...
...And 3 more matches
How Mozilla's build system works
rchitecture is config.status. the existence of a config.status file may be familiar to those who have worked with autoconf before. however, mozilla's config.status is different from many other config.status files, as it's written in python! instead of our configure script producing a shell script, it generates a python script. python 2 is prevalent in a mozilla build system. if we need to write code for the build system, we do it in python 2 instead of editing a makefile. config.status contains 2 parts: data structures representing the output of configure and a command-line interface for preparing, configuring, or generating an appropriate build backend. a build backend is merely a tool used to build the tree — like gnu make or tup. these data structures describe the current state o...
...es. most of the files already existed and didn't need to be changed. however, one was updated as a result of the new configuration. the whole process took 5.03s. of this, only 3.79s were in cpu time. this means we spent roughly 25% of the time waiting on i/o. phase 3: invocation of the build backend when most people think of the build system, they think of phase 3. this is where we take all the code in the tree and produce the firefox binary program file or the application you are creating. phase 3 effectively takes whatever was generated by phase 2 and runs it. since the dawn of mozilla, this has been done with the make tool, consuming makefiles. however, with the transition to moz.build files, you may eventually see non-make build backends, such as tup or visual studio. when building the ...
...t of the tree, run the following: mach mozbuild-reference or, you can view the raw file at /python/mozbuild/mozbuild/frontend/context.py. how moz.build processing works for most developers, knowing that moz.build files are python scripts that are executed and emit python dictionaries describing the build configuration is enough. if you insist on knowing more, this section is for you. ...
...And 3 more matches
Reviewer Checklist
submitting patches to mozilla source code needn't be complex. this article provides a list of best practices for your patch content that reviewers will check for or require. following these best practices will lead to a smoother, more rapid process of review and acceptance. good web citizenship make sure new web-exposed apis actually make sense and are either standards track or preffed off by default. in c++, wrapper-cache as needed. if your object can be gotten from somewhere without creating it in the process, it needs to be wrapper-cached. correctness the bug being fixed is a valid bug and should be fixed. the patch fixes the issue. the patch is not unnecessarily complicated. ...
...nse and are either standards track or preffed off by default. in c++, wrapper-cache as needed. if your object can be gotten from somewhere without creating it in the process, it needs to be wrapper-cached. correctness the bug being fixed is a valid bug and should be fixed. the patch fixes the issue. the patch is not unnecessarily complicated. the patch does not add duplicates of existing code ('almost duplicates' could mean a refactor is needed). commonly this results in "part 0" of a bug, which is "tidy things up to make the fix easier to write and review". if qa needs to verify the fix, you should provide steps to reproduce (str). quality if you can unit-test it, you should unit-test it. if it's js, try to design and build so that xpcshell can exercise most functionality. it'...
...mmonly this results in "part 0" of a bug, which is "tidy things up to make the fix easier to write and review". if qa needs to verify the fix, you should provide steps to reproduce (str). quality if you can unit-test it, you should unit-test it. if it's js, try to design and build so that xpcshell can exercise most functionality. it's quicker. make sure the patch doesn't create any unused code (e.g., remove strings when removing a feature) all caught exceptions should be logged at the appropriate level, bearing in mind personally identifiable information, but also considering the expense of computing and recording log output. [fennec: checking for log levels is expensive unless you're using logger.] style follow the style guide for the language and module in question. follow loc...
...And 3 more matches
mach
requirements mach requires a current version of /mozilla-central/ (or a tree derived from there). mach was committed on 2012-sep-26. mach also requires python 2.7. mach itself is python 3 compliant, but modules used by mach likely are not python 3 compliant - so stick to python 2.7. running from the root of the source tree checkout, you should just be able to type: $ ./mach if all is well, you should see a help message. ...
... bugs and numerous areas for improvement. some larger known issues include: mintty (alternative terminal emulator on windows) doesn't work. text encoding issues (especially on windows where latin-1 is not the default system encoding). failed commands spew lots of extra error output, e.g. you will see a big mach error message when all that happened was an invoked command returned a non-0 exit code - possibly expectedly so in mozilla! generally, mach is known to work pretty well without issues for most people and works terribly for others with even the "basics" being quite unsatisfactory. how do i report bugs? bugs against the mach core can be filed in bugzilla in the firefox build system::mach core. most mach bugs are bugs in individual commands, not bugs in the core mach code. bugs ...
...that aren't part of building (read: compiling) the tree. this includes things related to testing and packaging. these weigh down make files and add to the burden of maintaining the build system. instead, you are encouraged to implement ancillary functionality in not make (preferably python). if you do implement something in python, hooking it up to mach is often trivial (just a few lines of proxy code). how does mach fit into the modules system? mozilla operates with a modules governance system where there are different components with different owners. there is not currently a mach module. there may or may never be one. mach is just a generic tool. the mach core is the only thing that could fall under perview of a module and an owner. even if a mach module were established, mach command m...
...And 3 more matches
Embedding the editor
this is equivalent to embedding the browser via nsiwebbrowser, but instead having an editable document. the composer chrome (toolbars etc) may be implemented by the embedder using native widgets, or using some amount of xul. that chrome needs to be configurable - dockable floating toolbars, toolbar shared between composer widgets, or 1 per widget. this type of embedding requires that the composer code is agnostic to where its ui is coming from; communication between the core editor and the ui needs to go through one or more interfaces that insulate the editor from its host application. (the current nseditorshell makes assumptions about the hosting xul document, which need to be broken.) composer embedded in a web page (<htmlarea>) ie 5 supports the <htmlarea> element; if mozilla is to support ...
...ndow. at window construction time, we get the editorshell from the <editor> element, and put that into window.editorshell. thence, lots of javascript in editor.js, composercommands.js and the various dialog js files assume that they can get at the one true editor via window.editorshell. this assumption was short-sighted, and must be fixed. editor assumes xul document structure there is c++ and js code in the editor that assumes that the editor is living in a xul document, and that there are xul document nodes out there whose attributes can be tweaked to change the state of the ui (e.g. the inline style buttons). this needs to be changed to allow embedders to provide their own, possibly native ui. editor needs to call through one or more interfaces when communicating with the ui. embedding obje...
...gation interface used for a browser.) when we have one editor per docshell, loading a frameset document, or a page with an <iframe> in composer, will instantiate more than one low-level editor. we need a concept of an "editing session" - a single top-level document which is editable, and which may embody more than one editor. this interface will be called nsi????. high-level ui and emebedding code should deal with this editing session interface, without knowledge of the underlying editors. the editing session will forward commands to the individual editors depending on focus, and mediate undo/redo between them. alternative solution: rather than having multiple editors in this scenario, we could have a single editor, which is capable of saving and restoring state such that it can be trans...
...And 3 more matches
PBackground
rkers and multiple child processes and other parent-process worker threads. this article outlines what pbackground is, and how it works. ipdl recap ipdl is a language used to define "protocols" — essentially formalized versions of how two things can communicate. it is similar in some respects to idl and webidl. at build time the ipdl compiler automatically generates a large amount of c++ glue code from the ipdl files. ipdl protocols are used to specify how the chrome and content processes talk to each other and verify that a content process is "following the rules". note: if you want more detailed information on ipdl, start out by reading the ipdl tutorial. when used at run time, every protocol has two actors — a parent and a child. these actors can live in different processes due to...
...rectly to the compositor thread in the parent process by creating a new top-level protocol that connects the compositor thread in the parent process to the main thread of a child process. this protocol is called pcompositor, and allows us to bypass the main thread of the parent process, which trims the latency of texture uploads since they will not get bogged down if that thread is busy. writing code that works in both chrome and content processes a lot of code "just works" in the content process. but some things, such as apis that need to manipulate files or device settings (e.g. geolocation) cannot run in the content process because it has restricted privileges. instead, these apis must ask the chrome process to do something on their behalf via an ipdl protocol. this has lead to a rather a...
... pbackground pbackground exists to solve such problems. ...
...And 3 more matches
XPCOMUtils.jsm
the xpcomutils.jsm javascript code module offers utility routines for javascript components loaded by the javascript component loader. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/xpcomutils.jsm"); using xpcomutils exposing a javascript class as a component using these utility methods requires four key steps: import xpcomutils.jsm, as explained previously. declare the class (or multiple classes) implementing the component(s). create an array of component constructors. define the nsgetfactory() or nsgetmodule() entry point. pseudocode this section provides some pseudocode that demonstrates how to put together a javascript class based on the steps listed above. constructor the constructor...
... "nsibar"], flags: ci.nsiclassinfo.singleton}), // ...component implementation... }; note: the ability to register the component in a category only on specific applications by adding the apps field to a category entry was added in gecko 2. notice that the queryinterface() method implemented by the component simply calls the generateqi() method provided by the xpcomutils code module. create an array of component constructors you need to create an array that lists the constructors for each component. this array can of course have just one entry: var components = [mycomponent]; here, we're calling the array components. create the nsgetfactory() or nsgetmodule() entry point finally, you need to implement the nsgetmodule() entry point so gecko can start up your com...
...value without recalculating it. this means that you shouldn't use a lazy getter for a property whose value you expect to change, because the getter will not recalculate the value. definelazygetter takes three arguments: the object to define the property on the name of the property defined the getter function itself, which returns the value and which will be called just once, the first time code tries to access the property. example for this is seen at bottom of this page here. function definelazygetter( aobject, aname, alambda ); parameters aobject the object into which to add the new lazy getter function. aname the name of the getter function to create. alambda a function that returns the value the getter should return. this function is called exactly once. this wil...
...And 3 more matches
source-editor.jsm
this component has been removed from the platform in firefox 28. the source-editor.jsm javascript code module implements an editor specifically tailored for editing source code; its primary purpose is to provide support for web developer tools to display and edit web site code. the editor provided is eclipse orion. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/source-editor.jsm"); warning: much of the functionality of the source editor is implemented by a secondary code module (by default, source-editor-orion.jsm). you must not directly import that code module; it is essentially an implementation detail. its functionality is all exposed through source-editor.jsm. method overview initialization and d...
...rom making changes. set it to false to allow editing. constants preference name constants these constants define the names of preferences used by the source editor. constant value description sourceeditor.prefs.component "devtools.editor.component" a string indicating the name of the source editor engine to use; this is "orion" by default. the source editor code module loads a module by the name "source-editor-<component>.jsm" and exposes its api as part of the sourceeditor object. sourceeditor.prefs.expand_tab "devtools.editor.expandtab" a boolean value that indicates whether or not to automatically expand tabs out to a series of spaces. sourceeditor.prefs.tab_size "devtools.editor.tabsize" an integer value that specifies t...
...tax highlighting mode for the editor by calling its setmode() method, or in the configuration object when first initializing the editor using its init() method. constant value description sourceeditor.modes.css "css" cascading style sheet. sourceeditor.modes.html "html" html document. sourceeditor.modes.javascript "js" javascript source code. sourceeditor.modes.text "text" utf-8 text document. sourceeditor.modes.xml "xml" xml document. theme constants these constants are used to identify the available themes that can be used by the syntax highlighter. only one is provided by default at this time. constant value description sourceeditor.themes.mozilla "mozilla" the d...
...And 3 more matches
Mozilla Web Developer FAQ
ers can shut out new browsers. the point of having a common api (the w3c dom) is interoperability, and checking for a particular browser defeats that purpose. when working with the dom, it is better to check for the existence of the methods and objects you are planning on using. for example, the existence of document.getelementbyid() can be checked as follows: if(document.getelementbyid) { /* code that uses document.getelementbyid() */ } why doesn’t mozilla display my alt tooltips? contrary to a popular belief stemming from the behavior of a couple browsers running on the windows platform, alt isn’t an abbreviation for ‘tooltip’ but for ‘alternative’. the value of the alt attribute is a textual replacement for the image and is displayed when the image isn’t. mozilla doesn...
... and opentype formats (.ttf and .otf) are supported since firefox 3.5. the fonts have to be served from the same origin (protocol, host, port) as the content that uses them unless the fonts are served with the appropriate cross-origin resource sharing http headers. downloadable fonts in the eot format are not supported. if you use downloadable fonts, please make sure the fonts have the right unicode mappings and the content uses the right unicode characters. the past practice of displaying non-latin text by assigning non-latin glyphs to latin code points breaks copying and pasting, breaks searching on the page, breaks indexing by search engines and breaks readability in browsers that do not support downloadable fonts (e.g. legacy browsers or mobile browsers that opt not to download fonts due...
... <font face="symbol">a</font> means the character latin small letter a (u+0061) preferably displayed using the symbol font. since the symbol font does not have glyph for that character, another font is used. ...
...And 3 more matches
An overview of NSS Internals
abase), and nss will then transparently manage the database files. most of the time certificates and keys are supposed to be stored in the nss database. therefore, after initial import or creation, the programmer usually doesn't deal with their raw bytes. instead, the programmer will use lookup functions, and nss will provide an access handle that will be subsequently used by the application's code. those handles are reference counted. nss will usually create an in-memory (ram) presentation of certificates, once a certificate has been received from the network, read from disk, or looked up from the database, and prepare in-memory data structures that contain the certificate's properties, as well as providing a handle for the programmer to use. once the application is done with a handle, it ...
...free the associated resources. when working with handles to private keys it's usually difficult (and undesired) that an application gets access to the raw key data; therefore it may be difficult to extract such data from nss. the usual minimum requirement is that private keys must be wrapped using a protective layer (such as password-based encryption). the intention is to make it easier to review code for security. the less code that has access to raw secret keys, the less code that must be reviewed. nss has only limited functionality to look up raw keys. the preferred approach is to use certificates, and to look up certificates by properties such as the contained subject name (information that describes the owner of the certificate). for example, while nss supports random calculation (crea...
...ion is passed to the parser, which will analyze the asn.1 data stream accordingly. the templates are usually closely aligned to definitions found in rfc documents. a data block described as der is usually in asn.1 format. you must know which data you are expecting, and use the correct template for parsing, based on the context of your software's interaction. data described as pem is a base64 encoded presentation of der, usually wrapped between human readable begin/end lines. nss prefers the binary presentation, but is often capable to use base64 or ascii presentations, especially when importing data from files. a recent development adds support for loading external pem files that contain private keys, in a software library called nss-pem, which is separately available, but should eventually...
...And 3 more matches
NSS Certificate Download Specification
this document describes the data formats used by nss 3.x for installing certificates. this document is currently being revised and has not yet been reviewed for accuracy. data formats nss can accept certificates in several formats. in all cases the certificates are x509 version 1, 2, or 3. binary formats nss's certificate loader will recognize several binary formats. they are: der encoded certificate: this is a single binary der encoded certificate. pkcs#7 certificate chain: this is a single pkcs#7 signeddata object. the only significant field in the signeddata object is the certificates field, which may contain multiple certificates to be imported together. the contents of the version, digestalgorithms, contentinfo, crls, and signerinfos fields are ignored. netscape certificat...
...ction below on certificate chains for more information about how multiple certificates are handled. text formats any of the above binary formats can also be imported in text form. the text form begins with the following line: -----begin certificate----- following this line should be the certificate data, which can be in any of the binary formats described above. this data must be base64 encoded as described by rfc 1113. following the data should be the following line: -----end certificate----- in a text format download, nss ignores any text before the first begin certificate line, and ignores any text after the first end certificate line. between those two lines, there must be exactly one item of any of the supported binary formats described above, and that one item must be base6...
... described by rfc 1113. following the data should be the following line: -----end certificate----- in a text format download, nss ignores any text before the first begin certificate line, and ignores any text after the first end certificate line. between those two lines, there must be exactly one item of any of the supported binary formats described above, and that one item must be base64 encoded. regardless of which of the supported binary formats is used, the begin and end lines must say certificate, and not any other word (such as key). the begin and end lines must begin and end with 5 dashes, with no extra leading or trailing white space (excluding the end of line characters). importing certificate chains several of the formats described above can contain several certificates. when...
...And 3 more matches
NSS environment variables
will trigger an assertion failure in debug builds when a program tries to shutdown nss before freeing all the resources it acquired from nss while nss was initialized. 3.5 nss_trace_ocsp boolean (any value to enable) enables ocsp tracing. the trace information is written to the file pointed by nspr_log_file (default stderr). see nss tracing 3.12 nss_use_decoded_cka_ec_point boolean (any value to enable) tells nss to send ec key points across the pkcs#11 interface in the non-standard unencoded format that was used by default before nss 3.12.3. 3.12.3 nss_use_shexp_in_cert_name boolean (any value to enable) tells nss to allow shell-style wildcard patterns in certificates to match ssl server host names. this behavior was th...
...fault before nss 3.12.3. 3.12.3 nss_use_shexp_in_cert_name boolean (any value to enable) tells nss to allow shell-style wildcard patterns in certificates to match ssl server host names. this behavior was the default before nss 3.12.3. 3.12.3 pkix_object_leak_test_abort_on_leak string (any non-empty value) debug variable for pkix leak checking. note: the code must be built with pkix_object_leak_test defined to use this functionality. 3.12 sockettrace boolean (1 to enable) controls tracing of socket activity by libpkix. messages sent and received will be timestamped and dumped (to stdout) in standard hex-dump format. 3.12 sqlite_force_proxy_locking boolean (1 to enable) 1 means force always use proxy, 0 means...
...12 sqlite_force_proxy_locking boolean (1 to enable) 1 means force always use proxy, 0 means never use proxy, null means use proxy for non-local files only. 3.12.6 sslbypass boolean (1 to enable) uses pkcs#11 bypass for performance improvement. do not set this variable if fips is enabled. 3.11 ssldebug integer debug level note: the code must be built with debug defined to use this functionality. before 3.0 ssldebugfile string (file name) file where debug or trace information is written. if not set, the debug or trace information is written to stderr. note: ssldebug or ssltrace have to be set to use this functionality. 3.12 sslforcelocks boolean (1 to enable) forces nss to use l...
...And 3 more matches
NSS Tools pk12util
he the crypto provider may be the softtoken module or an external hardware module. it may be the case that the cryptographic module does not support the requested algorithm and a best fit will be selected, likely to be the default. if no suitable replacement for the desired algorithm can be found a "no security module can perform the requested operation" will appear on the error message. ...
...ely to be the default. if no suitable replacement for the desired algorithm can be found a "no security module can perform the requested operation" will appear on the error message. ...
...urity module can perform the requested operation" will appear on the error message. ...
...And 3 more matches
NSS tools : pk12util
esired length of the symmetric key to be used to encrypt the certificates and other meta-data. -r dumps all of the data in raw (binary) form. this must be saved as a der file. the default is to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. ...
... to return information in a pretty-print ascii format, which displays the information about the certificates and public keys in the p12 file. ...
...ificates and public keys in the p12 file. ...
...And 3 more matches
Invariants
, js::autocompartment, both make sure the invariant is maintained. however, there is another internal api, js::switchtocompartment, that lets you break this invariant, and of course in xpconnect we use that from time to time when we know we aren't going to be creating any new objects (other than global objects, which have no parent or prototype) or doing anything that might call back into native code that could create objects. we do this in order to save some cpu cycles (in other words, for no good reason whatsoever). if !js_isrunning(cx) && cx->globalobject == null, then cx->compartment == cx->runtime->defaultcompartment. while executing a script, cx->compartment == script->compartment. but this is true only so long as we are actually in the interpreter or jit code. a jsnative or other cal...
...e places, pointers to jsobjects and jsstrings must refer to live heap objects, but this is not a hard fast rule, especially for strings. some jsstrings are allocated on the stack for quick operations. some commonly used strings are allocated statically; see jsstring::isstatic(). most jscontext pointers must point to live contexts, but jstitle::ownercx may point to one that has been destroyed! so code must check js_validcontextpointer(ownercx) before dereferencing it. shape invariants the shape guarantees hold whenever the property cache is enabled. also, we never change the shape of the global object on trace. (here "the global object" refers to the object at the end of the scope chain of the function object we're executing.) requests many functions require a request. that is, they take...
...he global object" refers to the object at the end of the scope chain of the function object we're executing.) requests many functions require a request. that is, they take a parameter cx of type jscontext *, and require that cx is in a request on the current thread. see js_threadsafe. "are we in a request on cx?", where cx is any variable of type jscontext *, is a static yes for most lines of code where such a variable exists. occasionally it's a static no; other times we don't care. almost all jsapi callbacks provide a request; that is, when we call a callback with a cx argument, we know statically that we must be in a request on cx there. locks "are we holding the runtime-wide gc lock?" is a static yes or no for almost every line of code. a general rule about the state of all thread...
...And 3 more matches
Split object
ons of firefox accomplished this by blowing away all window properties every time a user navigated to another page, then reusing the window. each page, even on back, had to load from scratch. this was slow. circa firefox 1.5, the decision was made to cache layout information and javascript state across navigation. a new approach for window was needed. security privileges are granted to js code on the basis of the scope chain of the executing code. spidermonkey walks up the scope chain to the nearest object that has jsprincipals attached. the end of the scope chain is the global object for the script. but what jsprincipals should be attached to a window object? the principals of the page the window is currently displaying? but then the page that called window.open could use a with state...
...g? but then the page that called window.open could use a with statement to inject that window into its scope chain, gaining access to that window's privileges. (note: with does add an object to the scope chain, but it's a special with wrapper object that is skipped, or something, during the search described here. this security feature is not peculiar to split objects. ...and yet, there is special code in jsobj.h with a comment about fixing some kind of interaction between with an split objects. write that down, it'll be on the test.) split objects were the solution. the inner window object is different for each page a browser window visits. it serves as the "globals" object and provides the jsprincipals for scripts on that page. access to inner window properties is fast. the outer window ob...
...object and provides the jsprincipals for scripts on that page. access to inner window properties is fast. the outer window object is the object returned by window.open. it represents the window or tab itself and survives as the user navigates in that window or tab. the window object's jsclass.resolve hook ensures that properties of the inner object are visible via the outer object, if the running code has the right principals to access them. this privilege check may be slow. see wikimo:gecko:splitwindow and bug 296639 for more discussion. see also http://groups.google.com/group/mozil...81825b338fb84f details this section describes split objects as a feature of the jsapi. it catalogues (and tries to explain) the subtle ways in which split objects affect spidermonkey's behavior. split objects ar...
...And 3 more matches
Places utilities for JavaScript
for instance, normally in order to get access to the bookmarks service, you have to run something like: components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); with places utils all you need to wr...
...for instance, normally in order to get access to the bookmarks service, you have to run something like: components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); with places utils all you need to write is: place...
...node according to the rules of the specified content type. string wrapnode(anode, string atype, nsiuri aoverrideuri) parameters anode the result node to wrap (serialize) atype the content type to serialize as aoverrideurioptional used instead of the node's uri if provided. this is useful for wrapping a container as type_x_moz_url, type_html or type_unicode. return type returns a string serialization of the node unwrapnodes() unwraps data from the clipboard or the current drag session. array object unwrapnodes(blob, type) parameters blob a blob (string) of data, in some format we potentially know how to parse. type the content type of the blob. return type returns an array of objects representing each item...
...And 3 more matches
How to build an XPCOM component in JavaScript
that's been detailed elsewhere. this tutorial will show you what you need to do to get a component working in as few and as simple steps as possible. ...
... if you want to use your component in other xpcom components, you must define the interfaces that you want exposed. if you want to use your component only from javascript, you can skip to the next section. there are many interfaces already defined in mozilla applications, so you may not need to define a new one. you can browse existing xpcom interfaces at various locations in the mozilla source code, or using xpcomviewer, a gui for browsing registered interfaces and components. you can download an old version of xpcomviewer that works with firefox 1.5 from mozdev mirrors. if an interface exists that meets your needs, then you do not need to write an idl, or compile a typelib, and may skip to the next section. if you don't find a suitable pre-existing interface, then you must define your ow...
...ch xpcom component that you create. see generating guids for more information. compiling the typelib your interface definition must be compiled into a binary format (xpt) in order to be registered and used within mozilla applications. the compilation can be done using the gecko sdk. you can learn how to get mac, linux, and windows versions of the gecko sdk by reading the article gecko sdk. for code outside the tree note: on windows if you download the gecko sdk without the whole build tree, you will be missing some required dlls for xpidl.exe and it will run with no errors but not do anything. to fix this download the mozilla build tools for windows and copy the dlls from windows\bin\x86 within the zip into the bin directory of the gecko sdk. note: the mac version of the sdk provided for ...
...And 3 more matches
XPCOM changes in Gecko 2.0
no more frozen interfaces there are no longer any frozen interfaces; from now on, all interfaces are subject to change. documentation will be updated as time allows to remove references to interfaces being "frozen" or "unfrozen." component registration the way xpcom components are registered changed in gecko 2. ...
...est. the component is loaded only when the xpcom component manager needs to create a component. ...
...e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} components/mycomponent.js contract @foobar/mycomponent;1 {e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8} category profile-after-change mycomponent @foobar/mycomponent;1 the javascript code no longer exports a nsgetmodule() function. it now must export a nsgetfactory() function, which accepts a class id (cid) as a parameter. for example, in your component's javascript code : components.utils.import("resource://gre/modules/xpcomutils.jsm"); function mycomponent() { } mycomponent.prototype = { // this must match whatever is in chrome.manifest! classid: components.id("{e6b866e3-41b2-4f05-a4d2-3d4bde0f7ef8}"), queryinterface: xpcomutils.generateqi([components.interfaces.nsimycomponent]), /* nsimycomponent implementation goes here */ ... }; // the followin...
...And 3 more matches
Preface
next » this is a book about gecko, and about creating xpcom components for gecko-based applications. though the emphasis is on the practical steps you take to make your c++ code into a component that can be used in gecko, we hope that these steps will also give us an occasion to discuss all of the tools, techniques, and technologies that make up xpcom. accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work. ...
...an occasion to discuss all of the tools, techniques, and technologies that make up xpcom. accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work. for example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with mozilla - prompts a discussion of the relationship between components and modules, of xpcom interfaces, and of the registration process in general. the top of each chapter provides a list of the major topics covered. sidebar sections are included to highlight technical details. by the end of the book, if we've done our job, you will have learned how to build a component and ...
...read this book no one. it is badly out of date, and much of what it says is either no longer remotely accurate, or is severely deprecated. if you are a historian, though... creating xpcom components is meant for c++ developers. though you can create xpcom components in javascript and other languages, and though you might be able to follow along as a c programmer, the component implementation code is written in c++, and much of the discussion of how to make your codeinto an xpcom component starts from c++. you don't need to be a c++ expert, however. although basic ideas such as inheritance and encapsulation should be familar to you, wherever possible they are explained in the book as they are used. also many of the examples are in javascript, which is used in mozilla to access xpcom compon...
...And 3 more matches
Creating XPCOM components
next » this guide is about gecko, and about creating xpcom components for gecko-based applications. though the emphasis is on the practical steps you take to make your c++ code into a component that can be used in gecko, we hope that these steps will also give us an occasion to discuss all of the tools, techniques, and technologies that make up xpcom. accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work. ...
...an occasion to discuss all of the tools, techniques, and technologies that make up xpcom. accordingly, the book is arranged so that you can follow along and create your own components or learn about different xpcom topics individually, as in a reference work. for example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with mozilla - prompts a discussion of the relationship between components and modules, of xpcom interfaces, and of the registration process in general. note: in general, you should try to avoid having to create xpcom components. add-ons should try to use the new add-on sdk as much as possible; however, there may be cases when it's unavoidable. note:this article describes a m...
...zation of the tutorial following along with the examples conventions acknowledgements an overview of xpcom the xpcom solution gecko components interfaces interfaces and encapsulation the nsisupports base interface xpcom identifiers cid contract id factories xpidl and type libraries xpcom services xpcom types method types reference counting status codes variable mappings common xpcom error codes using xpcom components component examples cookie manager the webbrowserfind component the weblock component component use in mozilla finding mozilla components using xpcom components in your cpp xpconnect: using xpcom components from script component internals creating components in cpp xpcom initialization ...
...And 3 more matches
Components.lastResult
in cases where components.lastresult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult. ...
... in cases where components.lastresult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult. ...
... in cases where components.lastresult is used, it is best to get it right away after the target call is made and save it in a local variable to test its value rather than doing multiple tests against components.lastresult. ...
...And 3 more matches
Components.utils.import
gecko 2.0 adds support for loading modules from chrome: urls, even those inside jar archives. ...
...gecko 2.0 adds support for loading modules from chrome: urls, even those inside jar archives. ...
...gecko 2.0 adds support for loading modules from chrome: urls, even those inside jar archives. ...
...And 3 more matches
Components.utils.unwaiveXrays
it can then use unwaivexrays to restore its xray vision for the object. the waivexrays operation is transitive: it waives xrays not just for the given object, but for all properties of the object (and their properties, and so on). ...
...it can then use unwaivexrays to restore its xray vision for the object. the waivexrays operation is transitive: it waives xrays not just for the given object, but for all properties of the object (and their properties, and so on). ...
...nd so on). the unwaivexrays operation undoes the operation, so xray vision is restored transitively as well. syntax xray = components.utils.unwaivexrays(obj); parameters obj the object for which we wish to restore xrays. returns the object with xrays restored. ...
...And 3 more matches
Components.utils.waiveXrays
any expando properties are not visible, and if any native properties have been redefined, this has no effect. ...
...any expando properties are not visible, and if any native properties have been redefined, this has no effect. ...
...exrays to remove xray vision for the object. waiving xrays is transitive, so waiving it for an object automatically waives it for any properties of that object (and their properties, and so on). if you waive xray vision, you can no longer trust that any of the object's properties are what you expect: any of them, including prototypes and accessors, could have been redefined by the less-privileged code. to undo waivexrays and get xray vision back, call components.utils.unwaivexrays on the object. the result of waivexrays is just like the wrappedjsobject property for xrayed objects, but it's more useful because you can call it on primitives or objects that aren't xrays, in which case it just returns the argument you passed in. this means you don't have to care whether the initial object is an xr...
...And 3 more matches
Using components
t to the above. var {cc: classes, ci: interfaces} = components; there are many more than just classes and interfaces. var { cu: utils, ci: interfaces, cc: classes, cr: results, cs: stack, cm: manager, ce: exception, } = components; here is a full breakdown of what is contained in components. ...
...cr: results, cs: stack, cm: manager, ce: exception, } = components; here is a full breakdown of what is contained in components. ...
...ack, cm: manager, ce: exception, } = components; here is a full breakdown of what is contained in components. ...
...And 3 more matches
imgIRequest
modules/libpr0n/public/imgirequest.idlscriptable please add a summary to this article. inherits from: nsirequest last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview void cancelandforgetobserver(in nsresult astatus); imgirequest clone(in imgidecoderobserver aobserver); void decrementanimationconsumers(); imgirequest getstaticrequest(); void incrementanimationconsumers(); void lockimage(); void requestdecode(); void unlockimage(); attributes attribute type description corsmode long the cors mode that this image was loaded with. read only. decoderobserver imgidecoderobserver read only. image imgicontainer the image container. read only. imageprincipal nsiprincipal the principal gotten from the channel the ...
...ag that a request is being cancelled as a result of a failure of a proxy holder and not an internal failure. at least i think that's what it does. regardless, there's no reason for this flag to be public, and it should either go away or become a private state flag within imgrequest. do not rely on it. status_load_complete 0x4 the data has been fully loaded to memory, but not necessarily fully decoded. status_error 0x8 an error occurred loading the image. status_frame_complete 0x10 the first frame has been completely decoded. status_decode_complete 0x20 the whole image has been decoded. cors_none 1 cors modes images can be loaded with. by default, all images are loaded with cors_none and cannot be used cross-origin in context like webgl. if an html img element has the crossorigin at...
...t be used cross-origin in context like webgl. if an html img element has the crossorigin attribute set, the imgirequest will be validated for cross-origin usage with cors, and, if successful, will have its cors mode set to the relevant type. cors_anonymous 2 cors_use_credentials 3 methods cancelandforgetobserver() cancels this request as in nsirequest.cancel(); further, also nulls out decoderobserver so it gets no further notifications from us. note: you should not use this in any new code; instead, use cancel(). note that cancel() is asynchronous, which means that some time after you call it, the listener/observer will get an onstoprequest(). this means that, if you're the observer, you can not call cancel() from your destructor. void cancelandforgetobserver( in nsresult astatus )...
...And 3 more matches
mozIRegistry
warning: the content of this article may be out of date. it appears to be a design document for something that never got implemented. introduction the title of this document is completely misleading. it's not really about any "registry interface" so much as it's about how mozilla supports a more dynamic binding between interface clients and the code that actually provides the implementation of those interfaces. it happens that this objective requires storing information about which implementation to use in a place distinct from your source code. and it happens that we've chosen, up till now, to store that information in the "netscape registry" file. which explains how this information came to be associated with the notion of a "registry." someday (i hope) this page will be pro...
...s that the build/install process will require updates to user "registry" to enable new class implementations to be accessible. our current build/install process doesn't quite step up to these problems as of yet. there are some bootstrapping issues related to using the service manager to access the moziregistry interface. currently, nsiservicemanager requires a clsid to access a service which hardcodes the implementation of that service. this issue needs to be resolved in order to enable alternative moziregistry implementations or to permit other service implementations to be bound at runtime. i think a simple clsid "alias" mechanism (equivalent to com's "component categories" in some respects), along with the ability to "set" services (versus the service manager insisting on creating the serv...
...ere's one component (labelled "mozrdfregistry/nsirdfdatabase") that potentially will emerge as an improved implementation of one of the moziregistry interfaces. i'll be discussing that implementation only briefly (mainly because i'm hoping i can pawn off the chore of implementing it to somebody else). there's another component that turns out to also be real important when you go to hook up your code with other mozilla components. that's the service manager. i'm just starting to understand the role it plays in this and it isn't really under my jurisdiction, so there's nothing about it here right now. in the future, i'll either add the information about it or at least put in a link to it's documentation. higher-level application components this box represents all the potential user's of th...
...And 3 more matches
nsINavBookmarksService
obsolete since gecko 2.0 nsiuri getbookmarkuri(in long long a...
...oid getbookmarkfolderstarray(in nsiuri auri, in print64array aresult); native code only! obsolete since gecko 1.9 void getbookmarkidsforuri(in nsiuri auri, [optional] out unsigned long count, [array, retval, size_is(count)] out long long bookmarks); note: renamed from getbookmarkfolders in gecko 1.9 void getbookmarkidsforuritarray(in nsiuri auri, in print64array aresult); native code only! obsolete since gecko 2.0 nsiuri getbookmarkuri(in long long aitemid); long long getchildfolder(in long long afolder, in astring asubfolder); obsolete since gecko 2.0 long long getfolderidforitem(in long long aitemid); boolean getfolderreadonly(in long long aitemid); astring getfoldertitle(in print64 folder); obsolete since gecko 1.9 n...
... observers to be notified of a beginupdatebatch when a lot of things are about to change. calls can be nested, observers will only be notified when all batches begin/end. it is extremely important that you call endupdatebatch() for each call to beginupdatebatch. if you do not do this, certain parts of the ui will not get updated and any changes to bookmarks will not get written to disk. from c++ code inside the places component, use nsbookmarksupdatebatcher defined in nsnavbookmarks.h to scope batches. for js or from other components, just please be very careful to close the batch, especially when encountering an error and returning early. void beginupdatebatch(); parameters none. changebookmarkuri() this method changes the bookmarked uri for a bookmark. it changes which "place" the boo...
...And 3 more matches
nsISocketTransport
fox 6.0 / thunderbird 6.0 / seamonkey 2.3) note: connection setup is triggered by opening an input or output stream, it does not start on its own. completion of the connection setup is indicated by a status_connected_to notification to the event sink (if set). ...
...tion setup is triggered by opening an input or output stream, it does not start on its own. completion of the connection setup is indicated by a status_connected_to notification to the event sink (if set). ...
...able once the socket is connected. read only. constants timeout type this constants are used by gettransport() and settransport() to specify socket timeouts constant value description timeout_connect 0 connecting timeout. timeout_read_write 1 read and write timeouts. ...
...And 3 more matches
Getting Started Guide
er in c or c++, i.e., you can apply * or -> to it to "get to" what it points at. nscomptr is smart in that, unlike a raw c++ pointer to an xpcom object, nscomptr manages addref, release, and queryinterface for you. 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...
...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;| /* |addref| the ...
...|mfooptr|, if any, and |addref|s the new one, in the appropriate sequence to avoid the ownership bug mentioned earlier. */ mfooptr = afooptr; additionally, the class using raw xpcom interface pointers will need a destructor to release mfooptr; and a constructor to ensure that mfooptr is initially set to null (or some other reasonable value). nscomptr helps you write code that is leak-proof, exception safe, and significantly less verbose than you would with raw xpcom interface pointers. with nscomptr, you may never have to call addref, release, or queryinterface by hand. you still have to understand xpcom. you still have to know which functions return interface pointers that have already been addrefed and which don't. you still have to ensure your program logic d...
...And 3 more matches
Reference Manual
// ... // the getter returns an already |addref|ed object (of the wrong type)... nscomptr<nsibar> bar( getter_addrefs(createbar()) ); // ...which i must query for the right type nscomptr<nsifoo> foo( do_queryinterface(bar) ); one unfortunate trap that people fall into in this case is forgetting that their getter function addrefed the result. which leads them to type in code that looks like this: nscomptr<nsifoo> foo( do_queryinterface(createbar()) ); // oops! the interface returned by |createbar| leaks. // you _must_ handle this case with the two step solution shown above. // seems unlikely, you say? you're more likely to see it in a form like this nscomptr<nsifoo> foo( do_queryinterface(alist->elementat(i)) ); // |elementat|, li...
... not deter you from using nscomptr. the patterns presented throughout this section will help you get the most out of nscomptr. space in general, nscomptr can be more efficient in space than using raw xpcom pointers. this is primarily because it factors its destructor, and the more complicated constructors and assignment operators. by following the optimization tips in this section, you will write code that generates fewer bytes of object than you might with raw pointers. even if you don't follow these suggestions, your nscomptr code may still end up smaller, or at worst only negligibly bulkier than the raw pointer version. see code bloat [long, summary at top] for details, though the recommendations from that document are re-iterated here. time [[more time-performance measurements are needed.]...
...ng a subroutine. this time is negligable, especially in the face of work done by queryinterface, and the work that may be done by release. in all other cases, nscomptr does only the work you would have done by hand. the bulk of the work for which an nscomptr is used is dereferencing with operator->, just as it is with a primitive pointer. ...
...And 3 more matches
Address Book examples
xt() .queryinterface(components.interfaces.nsiabdirectory); if (addressbook instanceof components.interfaces.nsiabdirectory) { // or nsiabitem or nsiabcollection // alert ("directory name:" + addressbook.dirname); ... } } how do i get one address book? address books are uniquely identified by a uri. this can be obtained via nsiabdirectory.uri. the code stores uris in various places (e.g. preferences, in address book trees etc). assuming you have the uri, then use the address book manager to get an nsiabdirectory representing the address book: let abmanager = components.classes["@mozilla.org/abmanager;1"] .getservice(components.interfaces.nsiabmanager); let oneaddressbook = abmanager.getdirectory(addressbookuri); ho...
...if the collection has not implemented that function. this is currently true in the case of ldap, but may be true in other cases as well. how do i search for multiple contacts? formulate a boolean search string (see nsiabcard for built-in property names): var searchquery = "(or(primaryemail,bw,@v)(nickname,bw,@v)(and(ismaillist,=,true)(notes,bw,@v)))"; searchquery = searchquery.replace(/@v/g, encodeuricomponent("mystr") the search queries use lisp syntax with operators enumerated in nsabquerystringtoexpression.cpp. assuming you wish to search across multiple directories: let abmanager = components.classes["@mozilla.org/abmanager;1"] .getservice(components.interfaces.nsiabmanager); let alladdressbooks = abmanager.directories; while (alladdressbooks.hasmoreelemen...
...ther case, you'll need: a factory object implementing nsiabdirfactory a directory object implementing nsiabdirectory if you are using c++, you can inherit from nsabdirproperty and override functions for your specific implementation to save implementing all the functions on nsiabdirectory yourself. the best example of a binary implementation of an address book is the os x address book source code. if you are implementing in javascript then you will have to implement the full interfaces mentioned above. at the moment, the best example of this is the eds contacts integration add-on. once you've added your own address book implementation, you might also want to extend the address book user interface. how do i extend the address book user interface? there are several hooks in the address ...
...And 3 more matches
MailNews Filters
mailnews filters consist of a set of search terms, and a set of filter actions. filter execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match. for new incoming messages, the protocol specific object that handles new messages calls nsimsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits. e.g., imap, pop3. applyfilterstohdr will in turn call the applyfilterhit method of the passed in nsimsgfilterhitnotify interface ptr. the protocol specific code will then apply all of the actions of the filter to the current msg header. if one of the actions is a move, or a stop filter execution action, we move on to the next header; otherwise, we mo...
...ded. these filters are initiated in the filter editor, and implemented in nsmsgfilterservice.cpp. this is implemented by doing a search using the filter criteria and applying the actions en masse on the resulting hits. the search is executed locally, not on the server, so that criteria like "in address book" still work. ...
... actions en masse on the resulting hits. the search is executed locally, not on the server, so that criteria like "in address book" still work. ...
...And 3 more matches
Scripting plugins - Plugins
netscape plugin api, an extension to the api has been developed that lets plugins be scriptable again, independent of java. this extension will also let plugins access the script objects in the browser, and is thus a much stronger and more flexible api.) the information in this section applies to firefox 1.0 and mozilla 1.7.5 and newer versions. how the dom handles scripting the mozilla dom code now checks if a plugin supports this new scriptability api and if it exposes a scriptable object through this new mechanism. mozilla does this by calling the old plugin api call npp_getvalue with the new enumeration value that has been added to the nppvariable enumeration. the new nppvariable enumeration is defined in npapi.h as: nppvpluginscriptablenpobject = 15 threading model this api is ...
... that loaded the plugin is not able to access methods and properties on the plugin. the same thing applies the other way too; the plugin can reach only javascript objects in the same origin as the page that loaded the plugin. ...
...me thing applies the other way too; the plugin can reach only javascript objects in the same origin as the page that loaded the plugin. in addition to this, a further extension to this api is being discussed that would give a plugin greater flexibility by letting the plugin control the origin of the calling code, so that the plugin can specify the origin of calls that come from internally loaded code from other origins. ...
...And 3 more matches
Set event listener breakpoints - Firefox Developer Tools
starting with firefox 69, debugging an application that includes event handlers is simplified because the debugger now includes the ability to automatically break when the code hits an event handler. this article explains how to use it. using a standard event breakpoint to use an event breakpoint, you open up the javascript debugger, and find and expand the event listener breakpoints section in the right hand column. to break when event listeners are hit, check the boxes next the events you are interested in. all of the standard events supported in your version of firefox are listed, arranged by which api or api area they're part of. now when a keydown, keyup, keypress, or input event occurs, execution will pause as soon as it enters the listener code. when execution pauses, the sour...
... hit, check the boxes next the events you are interested in. all of the standard events supported in your version of firefox are listed, arranged by which api or api area they're part of. now when a keydown, keyup, keypress, or input event occurs, execution will pause as soon as it enters the listener code. when execution pauses, the source pane displays the highlighted line of the javascript code that is next to be executed, along with the surrounding code for context. in addition, you get a box overlaid on the viewport saying "paused on event breakpoint", with buttons to step over that line of code or resume execution. you could add regular breakpoints at the entry point of the listener to achieve the same effect. if however you have multiple elements, all of which have event listeners ...
......
...And 3 more matches
Debugger-API - Firefox Developer Tools
the debugger interface mozilla’s javascript engine, spidermonkey, provides a debugging interface named debugger which lets javascript code observe and manipulate the execution of other javascript code. both firefox’s built-in developer tools and the firebug add-on use debugger to implement their javascript debuggers. however, debugger is quite general, and can be used to implement other kinds of tools like tracers, coverage analysis, patch-and-continue, and so on. debugger has three essential qualities: it is a source level interface: it operates in terms of the javascript language, not machine language. ...
...ment their javascript debuggers. however, debugger is quite general, and can be used to implement other kinds of tools like tracers, coverage analysis, patch-and-continue, and so on. debugger has three essential qualities: it is a source level interface: it operates in terms of the javascript language, not machine language. it operates on javascript objects, stack frames, environments, and code, and presents a consistent interface regardless of whether the debuggee is interpreted, compiled, or optimized. if you have a strong command of the javascript language, you should have all the background you need to use debugger successfully, even if you have never looked into the language’s implementation. it is for use by javascript code. javascript is both the debuggee language and the...
...nd the tool implementation language, so the qualities that make javascript effective on the web can be brought to bear in crafting tools for developers. as is expected of javascript apis, debugger is a sound interface: using (or even misusing) debugger should never cause gecko to crash. errors throw proper javascript exceptions. it is an intra-thread debugging api. both the debuggee and the code using debugger to observe it must run in the same thread. cross-thread, cross-process, and cross-device tools must use debugger to observe the debuggee from within the same thread, and then handle any needed communication themselves. (firefox’s builtin tools have a protocol defined for this purpose.) in gecko, the debugger api is available to chrome code only. by design, it ought not to int...
...And 3 more matches
CloseEvent - Web APIs
a closeevent is sent to clients using websockets when the connection is closed. this is delivered to the listener indicated by the websocket object's onclose attribute. constructor closeevent() creates a new closeevent. properties this interface also inherits properties from its parent, event. closeevent.code read only returns an unsigned short containing the close code sent by the server. the following values are permitted status codes. ...
...object's onclose attribute. constructor closeevent() creates a new closeevent. properties this interface also inherits properties from its parent, event. closeevent.code read only returns an unsigned short containing the close code sent by the server. the following values are permitted status codes. the following definitions are sourced from the iana website [ref]. note that the 1xxx codes are only websocket-internal and not for the same meaning by the transported data (like when the application-layer protocol is invalid). the only permitted codes to be specified in firefox are 1000 and 3000 to 4999 [source, bug]. status code name description 0–999 reserved and not used. 1000 normal closure normal closure; the connect...
...ting the connection due to a protocol error. 1003 unsupported data the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data). 1004 reserved. a meaning might be defined in the future. 1005 no status received reserved. indicates that no status code was provided even though one was expected. 1006 abnormal closure reserved. used to indicate that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected. 1007 invalid frame payload data the endpoint is terminating the connection because a message was received that contained inconsistent data (e.g., non-utf...
...And 3 more matches
DataTransfer.items - Web APIs
.items != null) { for (var i=0; i < ev.datatransfer.items.length; i++) { console.log("... ...
... for (var i=0; i < ev.datatransfer.items.length; i++) { console.log("... ...
...ar i=0; i < ev.datatransfer.items.length; i++) { console.log("... ...
...And 3 more matches
Using files from web applications - Web APIs
using the file api, which was added to the dom in html5, it's now possible for web content to ask the user to select local files and then read the contents of those files. this selection can be done by either using an html <input type="file"> element or by drag and drop. if you want to use the dom file api from extensions or other browser chrome code, you can; however, note there are some additional features to be aware of. see using the dom file api in chrome code for details. accessing selected file(s) consider this html: <input type="file" id="input" multiple> the file api makes it possible to access a filelist containing file objects representing the files selected by the user. the multiple attribute on the input element allows the user to select multiple files. accessing the first...
...n>; total size: <span id="filesize">0</span> </div> <div><input type="submit" value="send file"></div> </form> <script> function updatesize() { let nbytes = 0, ofiles = this.files, nfiles = ofiles.length; for (let nfileid = 0; nfileid < nfiles; nfileid++) { nbytes += ofiles[nfileid].size; } let soutput = nbytes + " bytes"; // optional code for multiples approximation const amultiples = ["kib", "mib", "gib", "tib", "pib", "eib", "zib", "yib"]; for (nmultiple = 0, napprox = nbytes / 1024; napprox > 1; napprox /= 1024, nmultiple++) { soutput = napprox.tofixed(3) + " " + amultiples[nmultiple] + " (" + nbytes + " bytes)"; } // end of optional code document.getelementbyid("filenum").innerhtml = nfiles; docum...
...ement and present your own interface for opening the file picker and displaying which file or files the user has selected. you can do this by styling the input element with display:none and calling the click() method on the <input> element. consider this html: <input type="file" id="fileelem" multiple accept="image/*" style="display:none"> <button id="fileselect">select some files</button> the code that handles the click event can look like this: const fileselect = document.getelementbyid("fileselect"), fileelem = document.getelementbyid("fileelem"); fileselect.addeventlistener("click", function (e) { if (fileelem) { fileelem.click(); } }, false); you can style the new button for opening the file picker as you wish. using a label element to trigger a hidden file input element...
...And 3 more matches
GlobalEventHandlers.onkeypress - Web APIs
er, in practice browsers do not fire keypress events for certain keys. the onkeypress event handler has been deprecated. you may want to use onkeydown instead. syntax target.onkeypress = functionref; value functionref is a function name or a function expression. the function receives a keyboardevent object as its sole argument. ...
...nction receives a keyboardevent object as its sole argument. examples basic example this example logs the keyboardevent.code value whenever you press a key inside the <input> element. html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeypress = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression. ...
...ector('input'); const log = document.getelementbyid('log'); input.onkeypress = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression. ...
...And 3 more matches
HTMLTextAreaElement - Web APIs
d, contains the index of the character that follows the input cursor. on being set, the control behaves as if setselectionrange() had been called with this as the first argument, and selectionend as the second argument. tabindex long: returns / sets the position of the element in the tabbing navigation order for the current document. textlength read only long: returns the codepoint length of the control's value. same as reading value.length type read only string: returns the string textarea. validationmessage read only string: returns a localized message that describes the validation constraints that the control does not satisfy (if any). this is the empty string if the control is not a candidate for constraint validation (willvalidate is fals...
...etc.&nbsp;]</p> <p><textarea name="mytxtarea" rows="10" cols="50">lorem ipsum dolor sit amet, consectetur adipiscing elit. ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. praesent tristique commodo lorem quis fringil...
...etc.&nbsp;]</p> <p><textarea name="mytxtarea" rows="10" cols="50">lorem ipsum dolor sit amet, consectetur adipiscing elit. ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. praesent tristique commodo lorem quis fringilla. sed ac tellus ero...
...And 3 more matches
Recommended Drag Types - Web APIs
the document describes best practices for common draggable data types. caution: all methods and properties in this document with a moz prefix, such as mozsetdataat(), will only work with gecko-based browsers. dragging text for dragging text, use the text/plain type. the second data parameter should be the dragged string. for example: event.datatransfer.setdata("text/plain", "this is text to drag"); dragging text in textboxes and selections on web pages is done automatically by the browser, so you do not need to handle it yourself. ...
...lections on web pages is done automatically by the browser, so you do not need to handle it yourself. it is recommended to always add data of the text/plain type as a fallback for applications or drop targets that do not support other types, unless there is no logical text alternative. always add this text/plain type last, as it is the least specific and shouldn’t be preferred. note: in older code, you may find text/unicode or the text types. these are equivalent to text/plain, and will store and retrieve plain text data. dragging links dragged hyperlinks should include data of two types: text/uri-list, and text/plain. both types should use the link’s url for their data. for example: var dt = event.datatransfer; dt.setdata("text/uri-list", "https://www.mozilla.org"); dt.setdata("text/...
...lso see data with the mozilla-specific type text/x-moz-url. if it appears, it should appear before the text/uri-list type. it holds the urls of links followed by their titles, separated by a linebreak. for example: http://www.mozilla.org mozilla http://www.example.com example dragging html and xml html content may use the text/html type. the data for this type should be serialized html source code. for example, it would be suitable to set its data to the value of the innerhtml property of an element. xml content may use the text/xml type, but ensure that the data is well-formed xml. you may also include a plain text representation of the html or xml data using the text/plain type. the data should be just the text without any of the source tags or attributes. for instance: var dt = event...
...And 3 more matches
IDBIndexSync - Web APIs
index; if false, a key can have duplicate values. methods add() stores the given value into this index, optionally with the specified key. if a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (idbdatabaseexception); parameters returns exceptions this method can raise a idbdatabaseexception with the following code: value the value to store into the index. key a key to use for identifying the record. any the key for the stored record. constraint_err if a record exists in this index with a key corresponding to the key parameter or the index is auto-populated, or if no record exists with a key corresponding to the value parameter in the index's referenced object store. get() retrieves the value f...
...r in the index's referenced object store. get() retrieves the value from this index for the record that corresponds to the given key. any get ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the index. exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. getobject() retrieves and returns the value from this index's referenced object store that corresponds to the given key. any getobject ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the referenced object st...
...t() retrieves and returns the value from this index's referenced object store that corresponds to the given key. any getobject ( in any key ) raises (idbdatabaseexception); parameters key the key that identifies the record to be retrieved. returns any the retrieved value from the referenced object store. exceptions this method can raise a idbdatabaseexception with the following code: not_found_err if no record exists in this index for the given key. opencursor() creates a cursor over the records of this index. the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records. void opencursor ( in optional idbkeyrange range, in optional unsigned short direction ) raises (idbdatabaseex...
...And 3 more matches
Intersection Observer API - Web APIs
f visibility of advertisements in order to calculate ad revenues. deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result. implementing intersection detection in the past involved event handlers and loops calling methods like element.getboundingclientrect() to build up the needed information for every element affected. since all this code runs on the main thread, even one of these can cause performance problems. when a site is loaded with these tests, things can get downright ugly. consider a web page that uses infinite scrolling. it uses a vendor-provided library to manage the advertisements placed periodically throughout the page, has animated graphics here and there, and uses a custom library that draws notification boxes and ...
...tification boxes and the like. each of these has its own intersection detection routines, all running on the main thread. the author of the web site may not even realize this is happening, since they may know very little about the inner workings of the two libraries they are using. as the user scrolls the page, these intersection detection routines are firing constantly during the scroll handling code, resulting in an experience that leaves the user frustrated with the browser, the web site, and their computer. the intersection observer api lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount. this way, sites no longer need ...
...nd a reference to the intersectionobserver object itself. each entry in the list of thresholds is an intersectionobserverentry object describing one threshold that was crossed; that is, each entry describes how much of a given element is intersecting with the root element, whether or not the element is considered to be intersecting or not, and the direction in which the transition occurred. the code snippet below shows a callback which keeps a counter of how many times elements transition from not intersecting the root to intersecting by at least 75%. for a threshold value of 0.0 (default) the callback is called approximately upon transition of the boolean value of isintersecting. the snippet thus first checks that the transition is a positive one, then determines whether intersectionratio i...
...And 3 more matches
MediaDevices.getUserMedia() - Web APIs
may simply ignore the request. generally, you will access the mediadevices singleton object using navigator.mediadevices, like this: async function getmedia(constraints) { let stream = null; try { stream = await navigator.mediadevices.getusermedia(constraints); /* use the stream */ } catch(err) { /* handle the error */ } } similarly, using the raw promises directly, the code looks like this: navigator.mediadevices.getusermedia(constraints) .then(function(stream) { /* use the stream */ }) .catch(function(err) { /* handle the error */ }); note: if the current document isn't loaded securely, navigator.mediadevices will be undefined, and you cannot use getusermedia(). see security for more information on this and other security issues related to using getusermedia...
...op-level document context for a valid origin can even request permission to use getusermedia(), unless the top-level context expressly grants permission for a given <iframe> to do so using feature policy. otherwise, the user will never even be asked for permission to use the input devices. for additional details on these requirements and rules, how they are reflected in the context in which your code is running, and about how browsers manage user privacy and security issues, read on. user privacy as an api that may involve significant privacy concerns, getusermedia() is held by the specification to very specific requirements for user notification and permission management. first, getusermedia() must always get user permission before opening any media gathering input such as a webcam or micr...
...ways security management and controls in a user agent can cause getusermedia() to return a security-related error. note: the security model for getusermedia() is still somewhat in flux. the originally-designed security mechanism is in the process of being replaced with feature policy, so various browsers have different levels of security support, using different mechanisms. you should test your code carefully on a variety of devices and browsers to be sure it is as broadly compatible as possible feature policy the feature policy security management feature of http is in the process of being introduced into browsers, with support available to some extent in many browsers (though not always enabled by default, as in firefox). getusermedia() is one method which will require the use of featur...
...And 3 more matches
MediaError.message - Web APIs
ering specific diagnostic details related to the error described by the mediaerror object, or an empty string ("") if no diagnostic information can be determined or provided. syntax var errormessage = mediaerror.message; value a domstring providing a detailed, specific explanation of what went wrong and possibly how it might be fixed. this is not simply a generic description of the mediaerror.code property's value, but instead goes deeper into the specifics of this particular error and its circumstances. if no specific details are available, this string is empty. example this example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute. the error han...
...d its circumstances. if no specific details are available, this string is empty. example this example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute. the error handler simply outputs a message to a box onscreen describing the error, including both the code and the message. only the relevant parts of the code are displayed; you can see the complete source code here. the example creates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist. this lets us see the behavior of the error event handler, which is received by an event handler we add to the <audio> element itself. the error han...
...reates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist. this lets us see the behavior of the error event handler, which is received by an event handler we add to the <audio> element itself. ...
...And 3 more matches
MediaSource.addSourceBuffer() - Web APIs
't handle any more sourcebuffer objects, or creating a new sourcebuffer using the given mimetype would result in an unsupported configuration of sourcebuffers. ...
...r creating a new sourcebuffer using the given mimetype would result in an unsupported configuration of sourcebuffers. ...
...ew sourcebuffer using the given mimetype would result in an unsupported configuration of sourcebuffers. ...
...And 3 more matches
MediaSource - Web APIs
ebuffer objects for that mime type. examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can. ...
...ples the following simple example loads a video with xmlhttprequest, playing it as soon as it can. ...
...owing simple example loads a video with xmlhttprequest, playing it as soon as it can. ...
...And 3 more matches
RTCInboundRtpStreamStats.qpSum - Web APIs
pressible. the quantization process and the amount of compression can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. ...
...ion can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. ...
...est you can do is make an estimate. you can, for example, use the value of rtcreceivedrtpstreamstats.framesdecoded if receiving the media or rtcsentrtpstreamstats.framesencoded if sending it to get the number of frames handled so far, and compute an average from there. see calculating average quantization below for a function that does this. also, the exact meaning of the qp value depends on the codec being used. for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2. ...
...And 3 more matches
RTCRtpStreamStats.qpSum - Web APIs
pressible. the quantization process and the amount of compression can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. ...
...ion can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. ...
...est you can do is make an estimate. you can, for example, use the value of rtcreceivedrtpstreamstats.framesdecoded if receiving the media or rtcsentrtpstreamstats.framesencoded if sending it to get the number of frames handled so far, and compute an average from there. see calculating average quantization below for a function that does this. also, the exact meaning of the qp value depends on the codec being used. for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2. ...
...And 3 more matches
SVGTransform - Web APIs
round the center point (0, 0), e and f will be zero. methods name & arguments return description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the new transformation. note that the values from the parameter matrix are copied. ...
...ns: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. settranslate(in float tx , in float ty) void sets the transform type to svg_transform_translate, with parameters tx and ty defining the translation amounts. exceptions: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. setscale(in float sx , in float sy) void sets the transform type to svg_transform_scale, with parameters sx and sy defining the scale amounts. ...
... exceptions: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. setscale(in float sx , in float sy) void sets the transform type to svg_transform_scale, with parameters sx and sy defining the scale amounts. exceptions: a domexception with code no_modification_allowed_err is raised when attempting to modify a read only attribute or when the object itself is read only. setrotate(in float angle, in float cx , in float cy) void sets the transform type to svg_transform_rotate, with parameter angle defining the rotation angle and parameters cx and cy defining the optional center of rotation. exceptions: ...
...And 3 more matches
SubtleCrypto.digest() - Web APIs
sha-256 this algorithm is specified in fips 180-4, section 6.2, and produces an output 256 bits long. sha-384 this algorithm is specified in fips 180-4, section 6.5, and produces an output 384 bits long. sha-512 this algorithm is specified in fips 180-4, section 6.4, and produces an output 512 bits long. ...
... sha-384 this algorithm is specified in fips 180-4, section 6.5, and produces an output 384 bits long. sha-512 this algorithm is specified in fips 180-4, section 6.4, and produces an output 512 bits long. hint: if you are looking here for how to create an keyed-hash message authentication code (hmac), you need to use the subtlecrypto.sign() instead. ...
...ow to create an keyed-hash message authentication code (hmac), you need to use the subtlecrypto.sign() instead. examples basic example this example encodes a message, then calculates its sha-256 digest and logs the digest length: const text = 'an obscure body in the s-k system, your majesty. the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const encoder = new textencoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('sha-256', data); return hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings. this example ca...
...And 3 more matches
SubtleCrypto.exportKey() - Web APIs
ons is encountered: invalidaccesserror raised when trying to export a non-extractable key. notsupported raised when trying to export in an unknown format. typeerror raised when trying to use an invalid format. examples note: you can try the working examples out on github. raw export this example exports an aes key as an arraybuffer containing the bytes for the key. see the complete code on github. /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "raw", key ); const exportedkeybuffer = new uint8array(exported); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = `[${exportedkeybuffer}]`; } /* generate an...
...utton. */ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ).then((key) => { const exportbutton = document.queryselector(".raw"); exportbutton.addeventlistener("click", () => { exportcryptokey(key); }); }); pkcs #8 export this example exports an rsa private signing key as a pkcs #8 object. the exported key is then pem-encoded. see the complete code on github. /* convert an arraybuffer into a string from https://developers.google.com/web/updates/2012/06/how-to-convert-arraybuffer-to-and-from-string */ function ab2str(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } /* export the given key and write it into the "exported-key" space. */ async function exportcryptokey(key) { const exported = a...
...*/ async function exportcryptokey...
...And 3 more matches
Matrix math for the web - Web APIs
ng the w component to the point, notice how neatly the matrix and the point line up: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] [4, 3, 2, 1] // point at [x, y, z, w] the w component has some additional uses that are out of scope for this article. check out the webgl model view projection article for a look into how it comes in handy. ...
..., 0, 0, 0, 1 ]; // returns a new array equivalent to somematrix let somematrixresult = multiplymatrices(identitymatrix, somematrix); important: these matrix functions are written for clarity of explanation, not for speed or memory management. these functions create a lot of new arrays, which can be particularly expensive for real-time operations due to garbage collection. in real production code it would be best to use optimized functions. glmatrix is an example of a library that has a focus on speed and performance. the focus in the glmatrix library is to have target arrays that are allocated before the update loop. translation matrix a translation matrix is based upon the identity matrix, and is used in 3d graphics to move a point or object in one or more of the three directions (x,...
... rotation matrix a rotation matrix is used to rotate a point or object. rotation matrices look a little bit more complicated than scaling and transform matrices. they use trigonometric functions to perform the rotation. while this section won't break the steps down into exhaustive detail (check out this article on wolfram mathworld for that), take this example for illustration. first, here's code that rotates a point around the origin without using matrices. // manually rotating a point about the origin without matrices let point = [10, 2]; // calculate the distance from the origin let distance = math.sqrt(point[0] * point[0] + point[1] * point[1]); // the equivalent of 60 degrees, in radians let rotationinradians = math.pi / 3; let transformedpoint = [ math.cos(rotationinradians) *...
...And 3 more matches
Animating objects with WebGL - Web APIs
our sample loads a copy from a cdn in our html's <head>. making the square rotate let's start by making the square rotate. ...
... square, we apply the rotation like this: mat4.rotate(modelviewmatrix, // destination matrix modelviewmatrix, // matrix to rotate squarerotation, // amount to rotate in radians [0, 0, 1]); // axis to rotate around this rotates the modelviewmatrix by the current value of squarerotation, around the z axis. ...
...to rotate in radians [0, 0, 1]); // axis to rotate around this rotates the modelviewmatrix by the current value of squarerotation, around the z axis. to actually animate, we need to add code that changes the value of squarerotation over time. ...
...And 3 more matches
Using DTMF with WebRTC - Web APIs
pport audio/video conferencing, webrtc supports sending dtmf to the remote peer on an rtcpeerconnection. this article offers a brief high-level overview of how dtmf works over webrtc, then provides a guide for everyday developers about how to send dtmf over an rtcpeerconnection. the dtmf system is often referred to as "touch tone," after an old trade name for the system. webrtc doesn't send dtmf codes as audio data. instead, they're sent out-of-band, as rtp payloads. note, however, that although it's possible to send dtmf using webrtc, there is currently no way to detect or receive incoming dtmf. webrtc currently ignores these payloads; this is because webrtc's dtmf support is primarily intended for use with legacy telephone services that rely on dtmf tones to perform tasks such as: teleco...
...ble to send dtmf using webrtc, there is currently no way to detect or receive incoming dtmf. webrtc currently ignores these payloads; this is because webrtc's dtmf support is primarily intended for use with legacy telephone services that rely on dtmf tones to perform tasks such as: teleconferencing systems menu systems voicemail systems entry of credit card or other payment information passcode entry note: while the dtmf is not sent to the remote peer as audio, browsers may choose to play the corresponding tone to the local user as part of their user experience, since users are typically used to hearing their phone play the tones audibly. sending dtmf on an rtcpeerconnection a given rtcpeerconnection can have multiple media tracks sent or received on it. when you wish to transmit ...
...> element to play the audio received by the rtcpeerconnection being "called." a <button> element to trigger creating and connecting the two rtcpeerconnection objects, then sending the dtmf tones. a <div> to receive and display log text to show status information. <p>this example demonstrates the use of dtmf in webrtc. note that this example is "cheating" by generating both peers in one code stream, rather than having each be a truly separate entity.</p> <audio id="audio" autoplay controls></audio><br/> <button name="dial" id="dial">dial</button> <div class="log"></div> javascript let's take a look at the javascript code next. keep in mind that the process of establishing the connection is somewhat contrived here; you normally don't build both ends of the connection in...
...And 3 more matches
Using bounded reference spaces - Web APIs
orted or not. safely creating a bounded-preferred space before actually attempting to create a bounded reference space, you need to create a session that supports them. ...
...erence space, you need to create a session that supports them. since not all hardware supports bounded reference spaces, you should made sure to support bounded reference spaces as an option rather than as a required feature unless you have special knowledge of the environment in which your code will run. ...
.... this way, our session will start up regardless of whether or not the user's platform is able to provide bounded reference spaces. creating the reference space simply requesting support for bounded-floor when calling the xrsystem method requestsession() isn't enough to get a bounded space. you need to ask for one when you call requestreferencespace() as well. ...
...And 3 more matches
Controlling multiple parameters with ConstantSourceNode - Web APIs
same value even while being changed in some way. for example, perhaps you have a set of oscillators, and two of them need to share the same, configurable volume, or you have a filter that's been applied to certain inputs but not to all of them. you could use a loop and change the value of each affected audioparam one at a time, but there are two drawbacks to doing it that way: first, that's extra code that, as you're about to see, you don't have to write; and second, that loop uses valuable cpu time on your thread (likely the main thread), and there's a way to offload all that work to the audio rendering thread, which is optimized for this kind of work and may run at a more appropriate priority level than your code. the solution is simple, and it involves using an audio node type which, at fi...
... setting up let's start by looking at the global variable initialization. let context = null; let playbutton = null; let volumecontrol = null; let oscnode1 = null; let oscnode2 = null; let oscnode3 = null; let constantnode = null; let gainnode1 = null; let gainnode2 = null; let gainnode3 = null; let playing = false; these variables are: context the audiocontext in wh...
...ter setting the window's load event handler to be the setup() function, the stage is set. let's see how the action plays out. toggling the oscillators on and off because oscillatornode doesn't support the notion of being in a paused state, we have to simulate it by terminating the oscillators and starting them again when the play button is clicked again to toggle them back on. let's look at the code. ...
...And 3 more matches
Using the Web Audio API - Web APIs
t to carry out more complex audio processing, as well as playback, the web audio api provides much more power and control. a powerful feature of the web audio api is that it does not have a strict "sound call limitation". for example, there is no ceiling of 32 or 64 sound calls at one time. some processors may be capable of playing more than 1,000 simultaneous sounds without stuttering. example code our boombox looks like this: note the retro cassette deck with a play button, and vol and pan sliders to allow you to alter the volume and stereo panning. we could make this a lot more complex, but this is ideal for simple learning at this stage. check out the final demo here on codepen, or see the source code on github. browser support modern browsers have good support for most features o...
...ntact; we are merely allowing the sound to be available to the web audio api. controlling sound when playing sound on the web, it's important to allow the user to control it. depending on the use case, there's a myriad of options, but we'll provide functionality to play/pause the sound, alter the track's volume, and pan it from left to right. controlling sound programmatically from javascript code is covered by browsers' autoplay support policies, as such is likely to be blocked without permission being granted by the user (or a whitelist). autoplay policies typically require either explicit permission or a user engagement with the page before scripts can trigger audio to play. these special requirements are in place essentially because unexpected sounds can be annoying and intrusive, and...
...false') { audioelement.play(); this.dataset.playing = 'true'; } else if (this.dataset.playing === 'true') { audioelement.pause(); this.dataset.playing = 'false'; } }, false); we also need to take into account what to do when the track finishes playing. our htmlmediaelement fires an ended event once it's finished playing, so we can listen for that and run code accordingly: audioelement.addeventlistener('ended', () => { playbutton.dataset.playing = 'false'; }, false); modifying sound let's delve into some basic modification nodes, to change the sound that we have. this is where the web audio api really starts to come in handy. first of all, let's change the volume. this can be done using a gainnode, which represents how big our sound wave is. t...
...And 3 more matches
WorkerGlobalScope.self - Web APIs
h, as indicated above). ...
...l get a worker global scope of the same type as that worker object written to the console — something like the following: dedicatedworkerglobalscope { undefined: undefined, infinity: infinity, math: mathconstructor, nan: nan, intl: object…} infinity: infinity array: function array() { [native code] } arguments: null caller: null isarray: function isarray() { [native code] } length: 1 name: "array" observe: function observe() { [native code] } prototype: array[0] unobserve: function unobserve() { [native code] } __proto__: function empty() {} <function scope> arraybuffer: function arraybuffer() { [native code] } blob: function blob() { [native code] } boolean: function boolean() { [native code] } dataview: ...
...etc. ...
...And 3 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
changing to a new api in longhorn. msaa will still be supported through an emulation layer, but that will probably be a very slow solution. we'll have to wait and see how good the msaa support in longhorn is, before we can call this one. msaa decision-making guide use msaa whenever you have created custom controls where you're handling the drawing, mouse and keyboard accessibility in your own code. msaa is the only way to let all at's know what your code is doing. don't use msaa if you're not running on a windows platform ... hope that one was obvious. don't use msaa if you're only windows target for accessibility is longhorn. don't use msaa if you're not going to take it all the way via testing with assistive technologies and working with at vendors. don't use msaa for exposing doc...
...space at the beginning or end of any of the accessible names, and make sure there is a \r\n where the line breaks occur in the accessible name for the role_link. for an example of how to do this properly, see internet explorer or gecko. again, if it's not done exactly this way, some links will not be read. for links inside dialogs, just expose a single role_link object and work on a scripting or code change solution with the assistive technology vendor. issues with tree views problem: tree views are difficult to support msaa in, because the nodes may be constantly changing or lazily instantiated. the screen reader vendors actually use the systreeview32 class directly rather than the msaa support for them, and can thus provide better support for native tree views. solution: look carefully a...
.... common examples are button, listbox, combobox, msctls_statusbar32, msctls_trackbar32, #32770 (dialog class), systreeview32, static, edit and richedit. other assistive technologies use a whitelist, and must list your window classes somewhere in their implementation, and then turn on msaa support when a window of that class receives focus. the window class is also used to determine a host of hard-coded behaviors, such as whether or not a screen reader will load the entire msaa tree into a special buffer for the user to navigate with screen reader commands. this is only supposed to occur for document navigation, not for ui/dialogs. where your application's keyboard commands will be solely used to navigate. solution: contact each vendor who's product isn't using your msaa, and let them know wha...
...And 3 more matches
<string> - CSS: Cascading Style Sheets
Web › CSS › string
for example, \22 represents a double quote, \27 a single quote ('), and \a9 the copyright symbol (©). ...
...for example, \22 represents a double quote, \27 a single quote ('), and \a9 the copyright symbol (©). ...
...for example, \22 represents a double quote, \27 a single quote ('), and \a9 the copyright symbol (©). ...
...And 3 more matches
word-break - CSS: Cascading Style Sheets
ord-break: break-all will create a break at the exact place where text would otherwise overflow its container (even if putting an entire word on its own line would negate the need for a break). formal definition initial valuenormalapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | break-all | keep-all | break-word examples html <p>1. ...
... create a break at the exact place where text would otherwise overflow its container (even if putting an entire word on its own line would negate the need for a break). formal definition initial valuenormalapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | break-all | keep-all | break-word examples html <p>1. ...
...reak-all | keep-all | break-word examples html <p>1. <code>word-break: normal</code></p> <p class="normal narrow">this is a long and honorificabilitudinitatibus califragilisticexpialidocious taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉</p> <p>2. <code>word-break: break-all</code></p> <p class="breakall narrow">this is a long and honorificabilitudinitatibus califragilisticexpialidocious taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉</p> <p>3. ...
...And 3 more matches
Block formatting context - Developer guides
lling the browser how you want to deal with overflowing content. there are some occasions in which you will find you get unwanted scrollbars or clipped shadows when you use this property purely to create a bfc. in addition, it is potentially not readable for a future developer, as it might not be obvious why you used overflow for this purpose. if you use overflow, it is a good idea to comment the code to explain. using display: flow-root a newer value of display lets us create a new bfc without any other potentially problematic side-effects. using display: flow-root on the containing block creates a new bfc . with display: flow-root; on the <div>, everything inside that container participates in the block formatting context of that container, and floats will not poke out of the bottom of th...
... element in browser) in terms of how it creates a new context for the flow layout inside it. ...
... in terms of how it creates a new context for the flow layout inside it. ...
...And 3 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
optionally, as a number between 0 and 15 (0x0 and 0xf). all components must be specified using the same number of digits. if you use the single-digit notation, the final color is computed by using each component's digit twice; that is, "#d" becomes "#dd" when drawing. a color in hexadecimal string notation always begins with the character "#". after that come the hexadecimal digits of the color code. the string is case-insensitive. "#rrggbb" specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. "#rrggbbaa" specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. the alpha channel is specified by 0xaa; the lower this value is, the more trans...
...order: 1px solid black; font: 16px "open sans", helvetica, arial, sans-serif; border-spacing: 0; border-collapse: collapse; } th, td { border: 1px solid black; padding:4px 6px; text-align: left; } th { background-color: hsl(0, 0%, 75%); } <table> <thead> <tr> <th scope="col">color in hsl notation</th> <th scope="col">example</th> </tr> </thead> <tbody> <tr> <td><code>hsl(90deg, 100%, 50%)</code></td> <td style="background-color: hsl(90deg, 100%, 50%);">&nbsp;</td> </tr> <tr> <td><code>hsl(90, 100%, 50%)</code></td> <td style="background-color: hsl(90, 100%, 50%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15turn, 50%, 75%)</code></td> <td style="background-color: hsl(0.15turn, 50%, 75%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15tur...
...0%, 50%)</code></td> <td style="background-color: hsl(90deg, 100%, 50%);">&nbsp;</td> </tr> <tr> <td><code>hsl(90, 100%, 50%)</code></td> <td style="background-color: hsl(90, 100%, 50%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15turn, 50%, 75%)</code></td> <td style="background-color: hsl(0.15turn, 50%, 75%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15turn, 90%, 75%)</code></td> <td style="background-color: hsl(0.15turn, 90%, 75%);">&nbsp;</td> </tr> <tr> <td><code>hsl(0.15turn, 90%, 50%)</code></td> <td style="background-color: hsl(0.15turn, 90%, 50%);">&nbsp;</td> </tr> <tr> <td><code>hsl(270deg, 90%, 50%)</code></td> <td style="background-color: hsl(270deg, 90%, 50%);">&nbsp;</td> </tr> </tbody> </table> note that when you omit th...
...And 3 more matches
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
s tainted will cause a securityerror to be thrown. this protects users from having private data exposed by using images to pull information from remote web sites without permission. storing an image from a foreign origin in this example, we wish to permit images from a foreign origin to be retrieved and saved to local storage. implementing this requires configuring the server as well as writing code for the web site itself. web server configuration the first thing we need is a server that's configured to host images with the access-control-allow-origin header configured to permit cross-origin access to image files. let's assume we're serving our site using apache. consider the html5 boilerplate apache server configuration file for cors images, shown below: <ifmodule mod_setenvif.c> <if...
...ch> </ifmodule> </ifmodule> in short, this configures the server to allow graphic files (those with the extensions ".bmp", ".cur", ".gif", ".ico", ".jpg", ".jpeg", ".png", ".svg", ".svgz", and ".webp") to be accessed cross-origin from anywhere on the internet. ...
...p", ".cur", ".gif", ".ico", ".jpg", ".jpeg", ".png", ".svg", ".svgz", and ".webp") to be accessed cross-origin from anywhere on the internet. implementing the save feature now that the server has been configured to allow retrieval of the images cross-origin, we can write the code that allows the user to save them to local local storage, just as if they were being served from the same domain the code is running on. ...
...And 3 more matches
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
e, you can see the time input's value by entering a time and seeing how it changes afterward. first, a look at the html. this is simple enough, with the label and input as we've seen before, but with the addition of a <p> element with a <span> to display the value of the time input: <form> <label for="starttime">start time: </label> <input type="time" id="starttime"> <p> value of the <code>time</code> input: <code> "<span id="value">n/a</span>"</code>. </p> </form> the javascript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change. when this happens, the contents of the <span> are replaced with the new value of the input element. var starttime = document.getelementbyid("starttime"); var...
... an input element change. when this happens, the contents of the <span> are replaced with the new value of the input element. var starttime = document.getelementbyid("starttime"); var valuespan = document.getelementbyid("value"); starttime.addeventlistener("input", function() { valuespan.innertext = starttime.value; }, false); when a form including a time input is submitted, the value is encoded before being included in the form's data. the form's data entry for a time input will always be in the form name=hh%3amm, or name=hh%3amm%3ass if seconds are included (see using the step attribute). additional attributes in addition to the attributes common to all <input> elements, time inputs offer the following attributes: attribute description list the id of the...
...he specified string isn't a valid time, no maximum value is set. min a string specifying the earliest time to accept, given in the time value format described previously. if the value specified isn't a valid time string, no minimum value is set. readonly a boolean attribute which, if present, means this field cannot be edited by the user. its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property. note: because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step the step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. only values which are equal to the basis for step...
...And 3 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
aximum value. there is a special case: if the data type is periodic (such as for dates or times), the value of max may be lower than the value of min, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 pm to 4 am. maxlength valid for text, search, url, tel, email, and password, it defines the maximum number of characters (as utf-16 code units) the user can enter into the field. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the field has no maximum length. this value must also be greater than or equal to the value of minlength. the input will fail constraint validation if the length of the text entered into the field is greater than maxlength utf-16 code units long. b...
... information. there is a special case: if the data type is periodic (such as for dates or times), the value of max may be lower than the value of min, which indicates that the range may wrap around; for example, this allows you to specify a time range from 10 pm to 4 am. ...
...see client-side validation for more information. multiple the boolean multiple attribute, if set, means the user can enter comma separated email addresses in the email widget or can choose more than one file with the file input. see the email and file input type. name a string specifying a name for the input control. ...
...And 3 more matches
Enumerability and ownership of properties - JavaScript
.in loops unless the property's key is a symbol. ownership of properties is determined by whether the property belongs to the object directly and not to its prototype chain. properties of an object can also be retrieved in total. there are a number of built-in means of detecting, iterating/enumerating, and retrieving object properties, with the chart showing below which are available. some sample code follows which demonstrates how to obtain the missing categories. property enumerability and ownership - built-in methods of detection, retrieval, and iteration functionality own object own object and its prototype chain prototype chain only detection enumerable nonenumerable enumerable and nonenumerable ...
......
... enumerable and nonenumerable object.keys getownpropertynames getownpropertysymbols getownpropertynames, getownpropertysymbols – filtered to exclude enumerables using propertyisenumerable getownpropertynames getownpropertysymbols not available without extra code not available without extra code iterable enumerable nonenumerable enumerable and nonenumerable object.keys getownpropertynames getownpropertysymbols getownpropertynames, getownpropertysymbols – filtered to exclude enumerables using propertyisenumerable ...
...And 3 more matches
Introduction - JavaScript
a server. for example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server. this means that in the browser, javascript can change the way the webpage (dom) looks. and, likewise, node.js javascript on the server can respond to custom requests from code written in the browser. javascript and java javascript and java are similar in some ways but fundamentally different in some others. the javascript language resembles java but does not have java's static typing and strong type checking. javascript follows most java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from livescript to ...
...hether methods are public, private, or protected, and you do not have to implement interfaces. variables, parameters, and function return types are not explicitly typed. java is a class-based programming language designed for fast execution and type safety. type safety means, for instance, that you can't cast a java integer into an object reference or access private memory by corrupting java bytecodes. java's class-based model means that programs consist exclusively of classes and their methods. java's class inheritance and strong typing generally require tightly coupled object hierarchies. these requirements make java programming more complex than javascript programming. in contrast, javascript descends in spirit from a line of smaller, dynamically typed languages such as hypertalk and dbas...
...sole the single-line input mode of the web console is great for quick testing of javascript expressions, but although you can execute multiple lines, it's not very convenient for that. for more complex javascript, you can use the multi-line line input mode. ...
...And 3 more matches
JavaScript modules - JavaScript
ml page. this is very similar to how we apply a regular script to a page, with a few notable differences. first of all, you need to include type="module" in the <script> element, to declare this script as a module. to import the main.js script, we use this: <script type="module" src="main.js"></script> you can also embed the module's script directly into the html file by placing the javascript code within the body of the <script> element: <script type="module"> /* javascript module code here */ </script> the script into which you import the module features basically acts as the top-level module. if you omit it, firefox for example gives you an error of "syntaxerror: import declarations may only appear at top level of a module". you can only use import and export statements inside modul...
...e.js export { name as squarename, draw as drawsquare, reportarea as reportsquarearea, reportperimeter as reportsquareperimeter }; // in main.js import { squarename, drawsquare, reportsquarearea, reportsquareperimeter } from './modules/square.js'; and it would work just the same. what style you use is up to you, however it arguably makes more sense to leave your module code alone, and make the changes in the imports. this especially makes sense when you are importing from third party modules that you don't have any control over. creating a module object the above method works ok, but it's a little messy and longwinded. an even better solution is to import each module's features inside a module object. the following syntax form does that: import * as module from '...
... you can see an example of our shape d...
...And 3 more matches
Arrow function expressions - JavaScript
d to the bound target function (the growup() function in the example above). an arrow function does not have its own this. the this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. so while searching for this which is not present in the current scope, an arrow function ends up finding the this from its enclosing scope. ...
...rom the surrounding lexical context, strict mode rules with regard to this are ignored. var f = () => { 'use strict'; return this; }; f() === window; // or the global object all other strict mode rules apply normally. correction: start note: the previous statement seems false. strict mode should prevent creating global variables when assigning to an undeclared identifier in a function. ...
... => (z1 = x + 1) x => (z1 = x + 1) > z1 vm51891:1 uncaught referenceerror: z1 is not defined at <anonymous>:1:1 (anonymous) @ vm51891:1 > f3(10) 11 > z1 11 f2 illustrates that when explicitly setting the arrow function to apply strict mode, it does throw an error when attempting to assign an undeclared variable. https://www.ecma-international.org/ecma-262/10.0/index.html#sec-strict-mode-code https://www.ecma-international.org/ecma-262/10.0/index.html#sec-arrow-function-definitions-runtime-semantics-evaluation correction: end invoked through call or apply since arrow functions do not have their own this, the methods call() and apply() can only pass in parameters. any this argument is ignored. var adder = { base: 1, add: function(a) { var f = v => v + this.base; retur...
...And 3 more matches
Intl.DisplayNames - JavaScript
eractive-examples and send us a pull request. constructor intl.displaynames() creates a new intl.displaynames object. static methods intl.displaynames.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale. ...
...me's default locale. instance methods intl.displaynames.prototype.of() this method receives a code and returns a string based on the locale and options provided when instantiating intl.displaynames. intl.displaynames.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object. examples region code display names to create an intl.displaynames for a locale and get the display name for a region code. // get display names of region in english let regionnames = new intl.displaynames(['en'], {type: 'region'}); regionnames.of('419'); // "latin america" regionnames.of('bz'); // "belize" regionnames.of('us'); // "united states" regionnames.of('ba'); // "bosnia & herzegovina" regionnames.of('mm...
... // get display names of script in english let scriptnames = new intl.displaynames(['en'], {type: 'script'}); // get script names scriptnames.of('latn'); // "latin" scriptnames.of('arab'); // "arabic" scriptnames.of('kana'); // "katakana" // get display names of script in traditional chinese sc...
...And 3 more matches
Intl.NumberFormat() constructor - JavaScript
'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new intl.numberformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension key is allowed: nu the numbering system to be used. possible values include: "adlm", "ahom", "arab", "arabext", "bali", "beng", "bhks", "brah", "cakm", "cham", "deva", "diak", "fullwide", "gong", "gonm", "gujr", "guru", "hanidec", "hmng", "hmnp", "java", "kali", "khmr", "knda", "lana", "lanatham", "laoo", "latn", "lepc", "limb", "mathbold", "mathdbl", "mathmono", "mathsanb", "mat...
...", "sind", "sinh", "sora", "sund", "takr", "talu", "tamldec", "telu", "thai", "tibt", "tirh", "vaii", "wara", "wcho". options optional an object with some or all of the following properties: compactdisplay only used when notation is "compact". takes either "short" (default) or "long". currency the currency to use in currency formatting. possible values are the iso 4217 currency codes, such as "usd" for the us dollar, "eur" for the euro, or "cny" for the chinese rmb — see the current currency & funds code list. there is no default value; if the style is "currency", the currency property must be provided. currencydisplay how to display the currency in currency formatting. possible values are: "symbol" to use a localized currency symbol such as €, this is the defa...
...you can enable this formatting by setting the currencysign option to "accounting". the default value is "standard". ...
...And 3 more matches
Object.prototype.toSource() - JavaScript
you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. ...
... you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. ...
... you can call tosource() while debugging to examine the contents of an object. overriding the tosource() method it is safe for objects to override the tosource() method. ...
...And 3 more matches
Transitioning to strict mode - JavaScript
ecmascript 5 introduced strict mode which is now implemented in all major browsers (including ie10). while making web browsers interpret code as strict is easy (just add 'use strict'; at the top of your source code), transitioning an existing code base to strict mode requires a bit more work. this article aims at providing guidance for developers. gradual transition strict mode has been designed so that the transition to it can be made gradually. it is possible to change each file individually and even to transition code to strict mode down to the function granularity. differences from non-strict to strict syntax errors when adding 'use strict';, the following cases will throw a syntaxerror before the script is executing: octal syntax var n = 023; with statement using delete on a v...
...ion in blocks if (a < b) { function f() {} } obvious errors declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} this is no longer the case in ecmascript 2015 (bug 1041128). declaring two function parameters with the same name function f(a, b, b) {} these errors are good, because they reveal plain errors or bad practices. they occur before the code is running. new runtime errors javascript used to silently fail in contexts where what was done was an error. strict mode throws in such cases. if your code base contains such cases, testing will be necessary to be sure nothing is broken. once again, it can happen at the function granularity level. setting a value to an undeclared variable function f(x) { 'use strict'; var a = 12; b = a...
...ar s = document.getelementbyid('thing').style; s.opacity = 1; (function fadeout() { // name the function if((s.opacity-=.1) < 0) s.display = 'none'; else settimeout(fadeout, 40); // use the name of the function })(); semantic differences these differences are very subtle differences. it's possible that a test suite doesn't catch this kind of subtle difference. careful review of your code base will probably be necessary to be sure these differences don't affect the semantics of your code. fortunately, this careful review can be done gradually down the function granularity. this in function calls in function calls like f(), the this value was the global object. in strict mode, it is now undefined. when a function was called with call or apply, if the value was a primitive value, ...
...And 3 more matches
Image file type and format guide - Web media technologies
cs) svg is an xml-based vector graphics format that specifies the contents of an image as a set of drawing commands that create shapes, lines, apply colors, filters, and so forth. svg files are ideal for diagrams, icons, and other images which can be accurately drawn at any size. as such, svg is popular for user interface elements in modern web design. svg files are text files containing source code that, when interpreted, draws the desired image. for instance, this example defines an drawing area with initial size 100 by 100 units, containing a line drawn diagonally through the box: <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <line x1="0" y1="80" x2="100" y2="20" stroke="black" /> </svg> svg can be used in web content in two ways: you can directly write the <svg> e...
...are. compression most tiff files are uncompressed, but lossless packbits and lzw compression are supported, as is lossy jpeg compression. licensing no license required (aside from any associated with libraries you might use); all known patents have expired. webp image webp supports lossy compression via predictive coding based on the vp8 video codec, and lossless compression that uses substitutions for repeating data. lossy webp images average 25–35% smaller than jpeg images of visually similar compression levels. lossless webp images are typically 26% smaller than the same images in png format. webp also supports animation: in a lossy webp file, the image data is represented by a vp8 bitstream, which may contain multiple frames. lossles...
... 18 65 no 19 (blink) no maximum dimensions 16,383×16,383 pixels supported color modes lossy webp stores the image in 8-bit y'cbcr 4:2:0 (yuv420) format. lossless webp uses 8-bit argb color, with each component taking 8 bits for a total of 32 bits per pixel. compression lossless (huffman, lz77, or color cache codes) or lossy (vp8). licensing no license required; source code is openly available. xbm (x window system bitmap file) xbm (x bitmap) files were the first to be supported on the web, but are no longer used and should be avoided, as their format has potential security concerns. modern browsers have not supported xbm files in many years, but when dealing with older content, you may...
...And 3 more matches
Media type and format guide: image, audio, and video content - Web media technologies
Web › Media › Formats
still and video imagery on the web. the modern web has powerful features to support the presentation and manipulation of media, with several media-related apis supporting various types of content. generally, the media formats supported by a browser are entirely up to the browser's creators, which can complicate the work of a web developer. this guide provides an overview of the media file types, codecs, and algorithms that may comprise media used on the web. it also provides browser support information for various combinations of these, and suggestions for prioritization of formats, as well as which formats excel at specific types of content. references images image file type and format guide covers support of image file types and content formats across the major web browsers, as wel...
...on about each type: benefits, limitations, and use cases of interest to web designers and developers. image file types for web designers fundamental information about the various image file types that may be useful for web designers, including best practices and use cases for each type, and guidelines for choosing the right image file format for specific types of content. ...
...f content. media file types and codecs media containers (file types) a guide to the file types that contain media data. some are audio-specific, while others may be used for either audio or combined audiovisual content such as movies. includes overviews of each of the file types supported by the major web browsers, along with browser support information and supported features. web audio codec guide a guide to the audio codecs allowed for by the common media containers, as well as by the major browsers. includes benefits, limitations, key specifications and capabilities, and use cases. it also covers each browser's support for using the codec in given containers. ...
...And 3 more matches
Mobile first - Progressive web apps (PWAs)
in so that different devices can receive an optimal experience without having to shoulder the burden of many resources that they don't need. see below for more details. a simple example to demonstrate the concepts, i wanted to cover in this article, i created a very simple app containing a nav menu, heading and single column of text. you can see my mobile first example running live, or grab the code to play with it on github. to make my simple example i created a sample app structure from a mozilla mortar template. i installed the volo automation tool by running the following on the command line sudo npm install -g volo (you'll also need to get node.js too if you don't already have it) i then created my sample project using volo create myapp mozilla/mortar-app-stub this creates a sample...
...e i created a sample app structure from a mozilla mortar template. i installed the volo automation tool by running the following on the command line sudo npm install -g volo (you'll also need to get node.js too if you don't already have it) i then created my sample project using volo create myapp mozilla/mortar-app-stub this creates a sample project inside a directory called myapp. the app's code files are inside the www folder. volo has a number of useful commands available, of which we will just use a couple: volo server: starts a local web server at localhost:8080 and runs your app through it: great for easy testing. volo build: builds a minified code version of your app, ready for production deployment, in a www-built folder. volo build base=www-built: runs the built version thro...
.../p> <a id="bottom" href="#top">back to top</a> </div> </article> <button id="install-btn">install</button> default mobile css for the css, i first added some styles into our app.css stylesheet to provide a reasonable narrow-screen layout. there is very little going on here, and anyone with a basic understanding of css should be able to understand most of it by just looking at the source code in app.css. particular bits of interest to point out are as follows. article { display: table; } nav { display: table-caption; caption-side: bottom; } this is a rather nice hacky bit of css you can use to make the navigation menu display at the bottom, even though it is at the top in the source order. and it works in ie8+. display: table makes the <article> and its children display in a ...
...And 3 more matches
Communicating using "port" - Archive of obsolete content
ote that the global self object is completely different from the self module, which provides an api for an add-on to access its data files and id. in the content script the port object is available as a property of the global self object. thus, to emit a message from a content script: self.port.emit("mycontentscriptmessage", mycontentscriptmessagepayload); to receive a message from the add-on code: self.port.on("myaddonmessage", function(myaddonmessagepayload) { // handle the message }); compare this to the technique used to receive built-in messages in the content script. for example, to receive the context message in a content script associated with a context menu object, you would call the on function attached to the global self object: self.on("context", function() { // handle ...
...ges in the content script. for example, to receive the context message in a content script associated with a context menu object, you would call the on function attached to the global self object: self.on("context", function() { // handle the message }); so the port property is essentially used here as a namespace for user-defined messages. accessing port in the add-on script in the add-on code, the channel of communication between the add-on and a particular content script context is encapsulated by the worker object. thus the port object for communicating with a content script is a property of the corresponding worker object. however, the worker is not exposed to add-on code in quite the same way in all modules. the panel and page-worker objects integrate the worker api directly. so ...
...ing back to the page-mod port.emit() the port.emit() function sends a message from the "main.js", or another add-on module, to a content script, or vice versa. it may be called with any number of parameters, but is most likely to be called with a name for the message and an optional payload. the payload can be any value that is serializable to json. from the content script to the main add-on code: var mymessagepayload = "some data"; self.port.emit("mymessage", mymessagepayload); from the main add-on code (in this case a panel instance) to the content script: var mymessagepayload = "some data"; panel.port.emit("mymessage", mymessagepayload); port.on() the port.on() function registers a function as a listener for a specific named message sent from the other side using port.emit(). i...
...And 2 more matches
Modules - Archive of obsolete content
unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names. we will show how to do each of these things using the built-in components object provided by xulrunner application such as firefox and thunderbird. to improve encapsulation, each module should be defined in the scope of its own global object. this is made possible by the use of sandboxes. ...
...pt function is an ordinary object, which has the global object of the loading script as its prototype. this breaks encapsulation, as it allows the script being loaded to access the built-in constructors of the loading script, which are defined on its global object. the problem with breaking encapsulation like this is that malicious scripts can use it to get the loading script to execute arbitrary code, by overriding one of the methods on the built-in constructors. if the loading script has chrome privileges, then so will any methods called by the loading script, even if that method was installed by a malicious script. to avoid problems like this, the object passed to loadsubscript should be a true global object, having its own instances of the built-in constructors. this is exactly what sandb...
...n contrast, compartments with content privileges can only use those features available to ordinary websites. the sandbox constructor takes a url parameter, which is used to determine the set of privileges for the compartment in which the sandbox will be created. passing an xul url will result in a compartment with chrome privileges (note, however, that if you ever actually do this in any of your code, gabor will be forced to hunt you down and kill you). otherwise, the compartment will have content privileges by default. rewriting the loadscript function using sandboxes, we end up with: function loadscript(url, imports) { let global = components.utils.sandbox(url); global.imports = imports; global.exports = {}; loader.loadsubscript(url, global); return global.exports; } n...
...And 2 more matches
XUL Migration Guide - Archive of obsolete content
and create a directory there called "chrome". in that directory you can keep your "content", "locale", and "skin" subdirectories: this allows you to refer to objects in these directories from "chrome.manifest" using a relative path, like "chrome/content". this is provided only as a migration aid, and it's still a good idea to port xul windows to html. content scripts in a xul-based add-on, code that uses xpcom objects, code that manipulates the browser chrome, and code that interacts with web pages all runs in the same context. but the sdk makes a distinction between: add-on scripts, which can use the sdk apis, but are not able to interact with web pages content scripts, which can access web pages, but do not have access to the sdk's apis content scripts and add-on scripts communi...
...rty packages you're likely to lose the security and compatibility benefits of using the sdk. using the low-level apis in addition to the high-level apis, the sdk includes a number of low-level apis some of which, such xhr and window/utils, expose powerful browser capabilities. but note that unlike the supported apis, low-level apis do not come with a compatibility guarantee, so we do not expect code using them will necessarily continue to work as new versions of firefox are released. in this section we'll use low-level modules how to: modify the browser chrome using dynamic manipulation of the dom directly access the tabbrowser object modifying the browser chrome this example uses the action button api, which is only available from firefox 29 onwards. the window/utils module give...
...} } require("sdk/ui/button/action").actionbutton({ id: "highlight-active-tab", label: "highlight active tab", icon: "./icon-16.png", onclick: highlightactivetab }); security implications the sdk implements a security model in which an add-on only gets to access the apis it explicitly imports via require(). this is useful, because it means that if a malicious web page is able to inject code into your add-on's context, it is only able to use the apis you have imported. for example, if you have only imported the notifications module, then even if a malicious web page manages to inject code into your add-on, it can't use the sdk's file module to access the user's data. but this means that the more powerful modules you require(), the greater is your exposure if your add-on is compromis...
...And 2 more matches
remote/parent - Archive of obsolete content
erequire("./remote.js", module); processes.port.emit("message-from-main", "hello from main"); processes.port.on("message-from-remote", function(process, message) { console.log("remote says: " + message); }); child process privileges a module loaded into a child process can't do everything that the same module loaded into the parent process can. multiprocess firefox restricts the things that code running in child processes is allowed to do. for example, when the child process is sandboxed, modules won't be able to access the file system. we don't yet have a full list of all the modules that a module in the child process can't load, but the sorts of things listed in limitations of frame scripts broadly apply. examples property retrieval this first example shows fetching a simple proper...
...o the module immediately. you can use an absolute path to the module or a relative path. if you use a relative path, you must use the module parameter. const { remoterequire } = require("sdk/remote/parent"); remoterequire("./my-module.js", module); note that even single-process applications have a process that contains content frames. for consistency and to make writing multiprocess compatible code easier, remoterequire() will also create a new module loader and load modules in the main process. parameters id : string the module to load. to use a relative path you must pass the module parameter. module : object the module to resolve the relative module id against. to resolve relative to the loading module, pass module here. properties processes a processes object. frames a frames ...
...nds messages to and receives messages from all frames. events attach event emitted when a new frame is created. the event handler is called with a frame representing the new frame. detach event emitted when a frame is removed. for example, the user might have closed a content tab. the event handler is called with the frame that detached. process a process provides a way to communicate with code running in one of the application's processes. properties port an event emitter that can be used to send and receive events to and from code running in the process. isremote a boolean property that indicates whether the attached process is remote from the main process. events detach event emitted when this process disconnects from the application. it may have been closed normally or it ma...
...And 2 more matches
ui/sidebar - Archive of obsolete content
el, the content must be local, typically loaded from the add-on's data directory via a url constructed using self.data.url(): var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: require("sdk/self").data.url("sidebar.html") }); from firefox 34, you can use "./sidebar.html" as an alias for self.data.url("sidebar.html"). so you can rewrite the above code like this: var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: "./sidebar.html" }); you can include javascript and css from the html as you would with any web page, for example using <script> and <link> tags containing a path relative to the html file itself. <!doctype html> <html> <head> <link href="stuff.css" type="text/css" rel="style...
... <link href="stuff.css" type="text/css" rel="stylesheet"> </head> <body> <script type="text/javascript" src="stuff.js"></script> </body> </html> you can update the sidebar's content by setting the sidebar's url property. this will change the sidebar's content across all windows. communicating with sidebar scripts you can't directly access your sidebar's content from your main add-on code, but you can send messages between your main add-on code and scripts loaded into your sidebar. on the sidebar end of the conversation, sidebar scripts get a global variable addon that contains a port for sending and receiving messages. on the add-on side, you need to get a worker object for the sidebar before you can send or receive messages. there are two events emitted by the sidebar which wi...
...ar scripts get a global variable addon that contains a port for sending and receiving messages. on the add-on side, you need to get a worker object for the sidebar before you can send or receive messages. there are two events emitted by the sidebar which will give you a worker: attach and ready. listen to attach if the first message in your add-on goes from the sidebar scripts to the main add-on code, and listen to ready if the first message goes from the main add-on code to the sidebar script. using attach the attach event is triggered whenever the dom for a new sidebar instance is loaded and its scripts are attached. the sidebar script may not be initialized yet, so you can't reliably send messages to the sidebar script right away: however, you can start listening to messages from the sc...
...And 2 more matches
Chrome Authority - Archive of obsolete content
rovide the usual components.* aliases: cc an alias for components.classes. ci an alias for components.interfaces. cu an alias for components.utils. cr an alias for components.results. cm an alias for components.manager. components an alias for components itself (note the lower-case). from this you can access less-frequently-used properties like components.stack and components.issuccesscode. note: the require("chrome") statement is the only way to access chrome functionality and the components api. the components object should not be accessed from modules. the sdk tools will emit a warning if it sees module code which references components directly. your modules should refrain from using chrome privileges unless they are absolutely necessary. chrome-authority-using modules must re...
...they reference. when the manifest implementation is complete the runtime loader will actually prevent modules from require()ing modules that are not listed in the manifest. likewise, it will prevent modules from getting chrome authority unless the manifest indicates that they have asked for it. this will ensure that reviewers see the same authority restrictions that are enforced upon the running code, increasing the effectiveness of the time spent reviewing the add-on. (until this work is complete, modules may be able to sneak around these restrictions). the manifest is built with a simple regexp-based scanner, not a full javascript parser. developers should stick to simple require statements, with a single static string, one per line of code. if the scanner fails to see a require entry, the...
...mplete, modules may be able to sneak around these restrictions). the manifest is built with a simple regexp-based scanner, not a full javascript parser. developers should stick to simple require statements, with a single static string, one per line of code. if the scanner fails to see a require entry, the manifest will not include that entry, and (once the implementation is complete) the runtime code will get an exception. ...
...And 2 more matches
Dialogs and Prompts - Archive of obsolete content
this page has some code snippets used to display and process dialog boxes. see working with windows in chrome code for introductory information and more discussion and examples. describing dialog windows dialogs in mozilla whenever you want to create a dialog in your application, use <dialog> (instead of usual <window>) as root element in the xul file. this will: handle a few keyboard events (enter/esc and more), which is good for keyboard accessibility. add ok and cancel buttons in an order that is consistent with os default (but the button set and layout is highly customizable, see below). simple dialog code the following xul code defines a simple dialog with two buttons, ok and cancel (buttons="accept,cancel" attribute on dialog). <?xml version="1.0"?> <?xml-stylesheet href="chr...
......
...el buttons from script, use this: // disable the ok and cancel btns document.documentelement.getbutton("accept").disabled = true; document.documentelement.getbutton("cancel").disabled = true; links dialog.xml — xbl bindings for <dialog> and <dialogheader> elements. passing parameter to a dialog and getting return values from it. ...
...And 2 more matches
Finding window handles - Archive of obsolete content
t to get the handle you need. note: starting in gecko 2.0, only the top level browser window has an hwnd. web content windows (in tabs) do not have their own hwnds. typically the top level browser window hwnd has no children, although if there are windowed plugins (such as flash) visible in the window, they will have hwnds whose parent is the top level browser window hwnd. here is some simple code that can get access to mozilla window handles. this code can be used from external application or from an xpcom component within an extension. finding the content window handle hwnd hcontent = 0; // first we need to find the main browser window hwnd hff = ::findwindowex(0, 0, "mozillauiwindowclass", 0); if (hff) { // next we step down through a fixed structure hwnd htemp; htemp...
...at should not be exposed to outside, and could change every time firefox updates, all you need is nsibasewindow.idl(it's not in gecko_sdk, get this from the latest firefox source, or http://mxr.mozilla.org/mozilla/sourc...basewindow.idl), and use xpidl to compile it to .h file, although that's stll a unfrozen interface, but it should be a lot better. ...
...lot better. notice that by using only the c++ part of this code will get the the parent window handle of the nsibasewindow you give as a param. that means if you use the top level nsibasewindow as a param, null will be returned in the chain and cause crash of firefox, that's a bug of firefox.(https://bugzilla.mozilla.org/show_bug.cgi?id=489045) now, let's move forward. first, in javascript, the code gets the nsibasewindow we want, it's a direct child of the top nsibasewindow. var basewindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .treeowner .queryin...
...And 2 more matches
HTML to DOM - Archive of obsolete content
safely parsing simple html to dom when using xmlhttprequest to get the html of a remote webpage, it is often advantageous to turn that html string into dom for easier manipulation. however, there are potential dangers involved in injecting remote content in a privileged context in your extension, so it can be desirable to parse the html safely. ...
...create your own function using unique name, id, and so forth. var frame = document.getelementbyid("sample-frame"); if (!frame) { // create frame frame = document.createelement("iframe"); // iframe (or browser on older firefox) frame.setattribute("id", "sample-frame"); frame.setattribute("name", "sample-frame"); frame.setattribute("type", "content"); frame.setattrib...
...it to a data uri and use that to load in the browser element. using a hidden xul iframe (alternate example) sometimes, a browser element is overkill, or does not meet your needs, or you can't fulfill its requirements. while working on donkeyfire, i discovered the iframe xul element, and it is very easy to implement it. as an example, i will show a browser overlay .xul file, and some javascript code to access it. here is some xul code you can add to your browser overlay .xul file. don't forget to modify the id and name! <vbox hidden="false" height="0"> <iframe type="content" src="" name="donkey-browser" hidden="false" id="donkey-browser" height="0"/> </vbox> then, in your extension's "load" event handler: onload: function() { donkeybrowser = document.getelementbyid("donkey-browser");...
...And 2 more matches
Sidebar - Archive of obsolete content
with which ever extension going last "winning". web panels sidebar content such as web pages can be safely loaded as sidebar in the "viewwebpanelssidebar". bookmarks with "load this bookmark in sidebar" checked in the properties open in the "viewwebpanelssidebar". a web page can use window.sidebar to create bookmark with that property. to open a page in the "viewwebpanelssidebar" from chrome code (browser/addon/extension) such as from menuitem, it can call: openwebpanel(atitle, auri); accessing the sidebar from a browser.xul script the sidebar content is always in a document separate from the main browser document (the sidebar is actually implemented as a xul browser element). this means you can't directly access the sidebar content from a script referenced from a browser.xul overlay. ...
...separate from the main browser document (the sidebar is actually implemented as a xul browser element). this means you can't directly access the sidebar content from a script referenced from a browser.xul overlay. to access your sidebar's window or document objects, you need to use the contentwindow or contentdocument properties of document.getelementbyid("sidebar") respectively. ...
...ox is open: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; if (sidebarwindow.location.href == "chrome://browser/content/web-panels.xul") { // act on the sidebar content only if it is the web panels } accessing the browser.xul window from a sidebar script see accessing the elements of the top-level document from a child window section of working with windows in chrome code. ...
...And 2 more matches
JavaScript timers - Archive of obsolete content
but there are some javascript native functions (timers) which allow us to delay the execution of arbitrary instructions: settimeout() setinterval() setimmediate() requestanimationframe() the settimeout() function is commonly used if you wish to have your function called once after the specified delay. the setinterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. the setimmediate() function can be used instead of the settimeout(fn, 0) method to execute heavy operations in ie. ...
...gain and again, such as animations. the setimmediate() function can be used instead of the settimeout(fn, 0) method to execute heavy operations in ie. the requestanimationframe() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. 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 w...
...ons, just like cleartimeout() for settimeout(). using javascript timers within animations (javascript daemons management) in computer science a daemon is a task that runs as a background process, rather than being under the direct control of an interactive user. in javascript programming language, all daemons are processes created by javascript timers or by a worker instantiation. here are some code snippets which simplify and abstract the management of daemons. requestanimationframe() requestanimationframe() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. the method takes as an argument a callback to be invoked before the repaint. performance.now() performance.now() returns a timestamp...
...And 2 more matches
Enhanced Extension Installation - Archive of obsolete content
storing the previous state. items that are installed must be visible in the extension manager user interface, even if the extension type is just an integration hook that has no meaningful ui presence. extension installation and registration is also prohibitively difficult/annoying for developers, who are forced to either dangerously hand-edit all the appropriate manifest files, or package their code as a xpi and install it that way every time they make a change. the state of the world install locations in firefox 1.0 extensions can be installed into only two locations: the firefox user's profile directory directory, e.g. ~/.mozilla/firefox/abcdefgh.default/extensions/ the firefox application directory, e.g. c:\program files\mozilla firefox\extensions extension metadata the extensi...
...s profile - during startup this file is checked and if the version info held by the running app disagrees with the info held by this file, a compatibility check is run on all installed items. when changes are made to the extensions datasource - new items are installed, old items uninstalled, enabled or disabled, a .autoreg file is written to the profile directory as well, which tells the startup code that the system has been modified, so that it destroys the component registries, finishes pending transactions and regenerates metadata appropriately. datasource structure the extension manager implements a rdf datasource which contains a composite of the two xml/rdf datasources at the two install locations. the composite datasource handles all read-only information requests, and when data must...
... _profileextensions // the rdf/xml datasource for the items at the // profile install location _globalextensions // the rdf/xml datasource for the items at the // global install location. }; tracking install locations since there are only two locations, the installed location of an extension is expressed throughout the code using a boolean value, often referred to as isprofile - true if the item is installed in the profile directory's extensions folder. this boolean relationship itself is not stored directly in the datasource. rather, if the system needs to know where an item is located, it checks to see if the item is a member of the the appropriate type container (urn:mozilla:extension:root or urn:mozilla:theme:ro...
...And 2 more matches
Adding sidebars - Archive of obsolete content
to add rich interfaces without requiring new windows or complicated overlays. sidebars take as much space as the user wants them to, and provide a frame where you can add elaborate data and controls. you're probably familiar with the bookmarks and history sidebars. if not, you can open either one from the view > sidebar menu. they also have shortcuts to open or close them using the keyboard. the code required to add a sidebar is very simple, as explained in creating a firefox sidebar. it's even simpler than that. all you need is to overlay the view sidebar menu. <menupopup id="viewsidebarmenu"> <menuitem id="xulschoolhello-sidebar" label="&xulschoolhello.sidebar.title;" accesskey="&xulschoolhello.sidebar.accesskey;" type="checkbox" autocheck="false" group="sidebar" sideba...
...ild. --> </hbox> <hbox> <!-- content for the second child. --> </hbox> </deck> note how this is one of the few cases where an attribute of an element is named using camel case instead of all small caps. the size of the deck depends on the size of the largest child node, just like in a tabbox. we recommend that you use hbox or vbox elements as children of a deck or stack. the code is easier to read and maintain this way. a deck can be very useful when you have a large piece of xul code that only changes in a small way depending on different circumstances. for instance, you could have a window that is used for two different purposes, and the only difference between the two cases is a label that has a value in one case and something else in another. using a .properties fi...
...ul when you have a large piece of xul code that only changes in a small way depending on different circumstances. for instance, you could have a window that is used for two different purposes, and the only difference between the two cases is a label that has a value in one case and something else in another. using a .properties file and a string bundle is a viable option, but it involves a lot of code for something so simple, specially if that's the only case where you need dynamic text. the alternative is to use a deck with the two labels, and change the selected index depending on the purpose of the window. this way you can still use dtd, and the code remains simple. a stack is like a deck, except that all of its children are always on display, one of top of the other. it allows you to deco...
...And 2 more matches
Handling Preferences - Archive of obsolete content
the main menu: on windows, tools > options on mac, firefox > preferences on linux, edit > preferences note: keep in mind the usage of the terms "preferences" and "options" in different platforms. if you need to refer to the term "preference" in any of your locale files, you must change the string depending on the operating system. tip: you can use window.navigator.platform in your chrome code to figure out the operating system firefox is running on. you can use the hidden dom window in non-chrome code. firefox loads user preferences from a number of sources. each source is a js file that contains some special functions not available in regular code. the following files are used: default preferences: these are stored in the directory defaults/pref in the firefox installation dire...
... defaults file. it makes it easier to compile a list of the preferences your extensions handle, and to document what they do. the preferences file you need to create should be defaults/preferences/yourextensionname.js, under your extension root. the naming of the js file is not compulsory, but it is the standard most extensions use. note: the purpose of the defaults directory is to hold non-code files your extension needs. in the past we have used this directory to store xslt files for xml transformations and local storage template files (more on this later). it's the best place to put miscellaneous files your extension needs. download this sample hello world using preferences. there are a couple of additions in the makefiles, to include the preference file xulschoolhello.js. the cont...
...it does 2 things: check if the preferences window is already open. in that case, just give it focus. make the window modal in systems where the instant apply rule is not used. notice that this is a preference that users can switch, so checking for the operating system is not good enough. the general philosophy in...
...And 2 more matches
Firefox addons developer guide - Archive of obsolete content
rules: file and directory names: italic method and variable names: class name if you want to add a fixme, add: fixme: a message notes: the original document is in japanese and distributed via the xuldev.org website. so there may be still some reference to the xuldev website (we want to host source code on mdc, not on xuldev), and to japanese things (like some specific locales, which have been translated to french since non-latin characters are not well supported). there are a few things that could be done to make this fit the site better, and for general cleaning up: tables should use the "standard-table" css class so they're styled the same as those on the rest of mdc. there should be some introductory text on the table of contents page at https://developer.mozilla.org/...
...urly apostrophes instead of straight ones as is done everywhere else in mdc. the stuff about installing the dom inspector (https://developer.mozilla.org/en/firefox_addons_developer_guide/let%27s_build_a_firefox_extension#install_the_dom_inspector) is not accurate for firefox 3 or later, since it's no longer included in the firefox installer and must be downloaded from amo. filenames should use <code> styling. this is available from the style drop-down menu in the editor. variable and function names use <code> styling. xpi should be in all caps instead of written as ("xpi"). method and function names should have parentheses after them. for example, here: https://developer.mozilla.org/en/firefox_addons_developer_guide/let's_build_a_firefox_extension#init_method the text of the paragraph s...
... if you use the interface template when mentioning interfaces by name, mdc will automatically format them and generate links to their documentation, like this: nsiconsoleservice. if you prefer, you can just link to the articles directly. ...
...And 2 more matches
Adding preferences to an extension - Archive of obsolete content
previous articles in this series won't be rehashed here, so if you haven't already seen them: creating a status bar extension creating a dynamic status bar extension also, for reference, you may want to take a look at preferences system and the preferences api. download the sample you can download a copy of this sample to look over, or to use as the basis for your own extension. get the code here: download the sample update the manifests the install manifest and chrome manifest need to be updated. by and large, the changes are simply changing the id of the extension. however, we do need to add one new line to the install.rdf file: <em:optionsurl>chrome://stockwatcher2/content/options.xul</em:optionsurl> this line establishes the url of the xul file that describes the options di...
...ifests the install manifest and chrome manifest need to be updated. by and large, the changes are simply changing the id of the extension. however, we do need to add one new line to the install.rdf file: <em:optionsurl>chrome://stockwatcher2/content/options.xul</em:optionsurl> this line establishes the url of the xul file that describes the options dialog. please note that if you are using code from this tutorial to add to an existing extension, you must uninstall and reinstall your extension to enable the preferences button for your extension in the add-ons list. establish the defaults in order to set a default preference for the stock to monitor, we need to add a new folder to our extension's package, called "defaults", which in turn contains another folder called "preferences". in...
... "preferences". inside that, we create a file, defaults.js, that describes the default value of our preferences: pref("extensions.stockwatcher2.symbol", "goog"); the standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the example above. the javascript code in order to monitor changes to our preferences, we need to install an observer using the nsiprefbranch2 interface. to do that, we need to reimplement our code into an object. that involves turning each function into a member of the stockwatcher class. let's take a look at each function in the class. startup() the stockwatcher.startup() function is called when our extension is first loaded. it...
...And 2 more matches
Creating a Mozilla Extension - Archive of obsolete content
s). a mozilla extension is an installable enhancement to the mozilla browser that provides additional functionality (for example linky, which adds an item to the context menu for opening multiple links in a document or selection). ...
...ent to the mozilla browser that provides additional functionality (for example linky, which adds an item to the context menu for opening multiple links in a document or selection). this tutorial walks you through the process of building a mozilla extension that adds an icon to mozilla's status bar showing the current status of the mozilla source code (i.e. whether or not the latest version of the code is compiling successfully and passing tests). ...
...pening multiple links in a document or selection). this tutorial walks you through the process of building a mozilla extension that adds an icon to mozilla's status bar showing the current status of the mozilla source code (i.e. whether or not the latest version of the code is compiling successfully and passing tests). the extension will access tinderbox, mozilla.org's webtool for tracking source code status, to get the status of the code. ...
...And 2 more matches
Documentation for BiDi Mozilla - Archive of obsolete content
this is preliminary documentation of the changes introduced to mozilla as part of the bidi support contributed by ibm (a.k.a. ibmbidi), written by simon montagu and posted to the mozilla-layout mailing list. while it was published in 2001 and might not be totally accurate, it does help understanding the internals of the bidi code. overview of bidi processing bidi text is reordered according to the unicode bidi algorithm (uba). the implementation is based on ibm's international components for unicode (icu), which was chosen after comparing and testing the available open-source implementations. as far as we could discover, icu is the only one which is 100% compatible with uba, including support for explicit directional controls (lro, rlo, etc, and their html equivalents). bidi process...
...bidiutils are used. note that we are not affected by buggy bidi implementations on specific platforms, since the platform never sees a text fragment with mixed directionality, and is not expected to do anything more complicated than displaying left-to-right text from left to right or right-to-left text from right to left. in some circumstances, even on a platform with bidi capability, the layout code has to reverse text fragments or to allow for the fact that they are displayed in reverse. in general, this happens whenever we are dealing with less than a whole frame. examples of this are in nstextframe::painttextslowly; nstextframe::paintunicodetext when a selection is displayed; nstextframe::getposition; nstextframe::getpointfromoffset. text in visual mode must also be reversed before displ...
... other bidi functionality clipboard: based on bidi options in preferences, the text mode of the clipboard may be "logical", "visual" or "as source". in "as source" mode, the text copied into the clipboard is exactly the same (from a bidi point of view) as the original source. ...
...And 2 more matches
generateCRMFRequest() - Archive of obsolete content
rack. 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. deprecatedthis feature has been removed from the web standards. though some browsers may still support it, it is in the process of being dropped. avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. be aware that this feature may cease to work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. crmfobje...
... warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. crmfobject = crypto.generatecrmfrequest("requesteddn", "regtoken", "authenticator", "escrowauthoritycert", "crmf generation done code", keysize1, "keyparams1", "keygenalg1", ..., keysizen, "keyparamsn", "keygenalgn"); this method will generate a sequence of crmf requests that has n requests. one request for each key pair that is generated. the first three parameters will be applied to every request. the "escr...
...paramsn", "keygenalgn"); this method will generate a sequence of crmf requests that has n requests. one request for each key pair that is generated. the first three parameters will be applied to every request. the "escrowauthoritycert" parameter will only be used for requests that pertain to a key that is being escrowed. after the "escrowauthoritycert" parameter, the method takes some javascript code that is invoked when the crmf request is ready. finally, there are 1 or more sets of key generation arguments. each key generation will be associated with its own request. all the requests will have the same dn. argument description "requesteddn" an rfc 1485 formatted dn to include in the certificate request. "regtoken" a value used to authenticate the user to ...
...And 2 more matches
Java in Firefox Extensions - Archive of obsolete content
note: the global java object has been removed in gecko 16.0, so this page is out of date. you should still be able to use the java plugin's scripting functionality, see liveconnect for the pointers. note bug 834918 about click-to-play effect on java plugins in chrome and bug 775301. if you are in need of calling java code from within a firefox extension, you can make use of liveconnect. ...
...removed in gecko 16.0, so this page is out of date. you should still be able to use the java plugin's scripting functionality, see liveconnect for the pointers. note bug 834918 about click-to-play effect on java plugins in chrome and bug 775301. if you are in need of calling java code from within a firefox extension, you can make use of liveconnect. liveconnect gives your extension's javascript code (linked from or contained in xul code) access to 2 objects: java and packages (note that per this thread, although the new documentation for the liveconnect reimplementation states that these globals will be deprecated (in the context of applets), "firefox and the java plug-in will continue to support the global java/packages keywords, in particular in the context of firefox extensions."). these ...
...pplets), "firefox and the java plug-in will continue to support the global java/packages keywords, in particular in the context of firefox extensions."). these 2 objects let you make use of the standard jdk classes, e.g., var ajavalist = new java.util.linkedlist(); if you want to load your own jars, then you can create your own java class loader. the following technique only works in javascript code linked from or contained in xul files. if you wish to call java code from within javascript code that implements some xpcom components, at this time, you need a different technique (refer to the complete java firefox extension). a good reason for calling java from within an xpcom component rather than from xul is to maintain a singleton (some singular java object) across all firefox windows. if y...
...And 2 more matches
XML in Mozilla - Archive of obsolete content
in special circumstances external dtds as explained above and will use this information to recognize id type attributes, default attribute values, and general entities. other notes a lot of the document object model (dom, w3c recommendations and drafts) applies to xml. likewise, the cascading style sheets (css, w3c recommendations and drafts) style language can be used to style xml documents. the code for most the core xml can be found in the following directories on the mozilla mercurial repository: content/xml/, parser/expat/ and parser/htmlparser/. the newsgroup to discuss xml in mozilla depends a bit on the nature of the question. for example, dom related questions should probably be discussed in the mozilla.dev.tech.dom newsgroup, while style issues should be discussed on mozilla.dev.tech...
...ath1() scheme obsolete since gecko 1.9.1 internet-draft document.load(), document.async part of dom level 3 load & save module, a w3c working draft xhtml we have reasonable xhtml support, most things should work. we treat xhtml documents differently depending on the mime type (or file suffix if files are loaded from local discs). ...
...l 3 load & save module, a w3c working draft xhtml we have reasonable xhtml support, most things should work. we treat xhtml documents differently depending on the mime type (or file suffix if files are loaded from local discs). files that go through the html code path are not checked for well-formedness. you will also notice not all xhtml features are supported when you exercise the html code path. mime type file suffix code path text/xml application/xml application/xhtml+xml xml xht xhtml xml text/html html htm html the entire document need not be xhtml. you can use xhtml elements inside an arbitrary xml document by using the xhtml namespace. see the tes...
...And 2 more matches
Install Wizards (aka: Stub Installers) - Archive of obsolete content
ipt, usually named install.js, which contains javascript directives for actions to take during an install including adding files and directories, removing old or obsolete files and directories, executing command line tools, etc. to learn more about the xpinstall and installer packages please refer to the annotated browser xpi installer and the xpinstall api reference. what do we mean by engine code? the xpinstall engine processes installer packages by reading instructions from their install scripts to extract files and take other install actions. the same xpinstall engine is used by the browser and the stub installers on all platforms. the xpinstall engine source resides at: <http://lxr.mozilla.org/seamonkey/sou...xpinstall/src/> what do we mean by stub installer? the install wizards us...
...ted software packages. this saves low-bandwidth users considerable time since they do not need to download software packages they may not be interested in. (the stub installer accomplishes this by downloading the xpinstall engine along with the selected software packages. ...
... do not need to download software packages they may not be interested in. (the stub installer accomplishes this by downloading the xpinstall engine along with the selected software packages. ...
...And 2 more matches
getLastError - Archive of obsolete content
the getlasterror method does not return errors from methods that return objects, such as getfolder. ...
...the getlasterror method does not return errors from methods that return objects, such as getfolder. ...
...the getlasterror method does not return errors from methods that return objects, such as getfolder. ...
...And 2 more matches
XPJS Components Proposal - Archive of obsolete content
nsregisterself nsgetfactory nsunregisterself (optional) nscanunload (optional) each .js file might implement one or more components. we will have one native module - called the xpjsmanager - which holds this system together. the xpjsmanager is in charge of loading these .js files, helping them register themselves, and acting as an intermediary between the xpcom component manager and the js code. xjs components are not run in browser windows. each .js file (let's call it a module) is started up and run in the context of a relatively 'raw' js global object. the standard (non-dom) js classes will be available. the xpconnectcomponents object will be available. and some additional yet to be defined objects may be available. the xpconnectcomponents object allows access to the whole repositor...
...dard (non-dom) js classes will be available. the xpconnectcomponents object will be available. and some additional yet to be defined objects may be available. the xpconnectcomponents object allows access to the whole repository of native and js xpcom components, so this is not as isolated an environment as it might at first sound. a 'load' or 'import' function will also be provided to let the js code import other .js files where libraries of code might be stored. this is akin to 'static' libraries. accessing other components/services via xpcom/xpconnect is more akin to 'dynamic' libraries. when a xpjs component module is first installed - or at autoregistration time - the xpjsmanager will load the .js file into a fresh js environment, let its top level script run to do whatever initializatio...
...onment, let its top level script run to do whatever initialization it wants to do, and then it will call the module's nsregisterself function (passing the filespec of the .js file). at this point the module will use the (new) methods on the components object to register itself with the component manager as a factory module for one or more classid or progid. this registration function that the js code calls (e.g. components.registercomponentspec) will be provided by the xpjsmanager. the xpjsmanager will receive this call from the js code, store the mapping of clsid to .js filespec in the registry for its own use later, and then call the real component manager to do the registration. however, the xpjsmanager will pass the component manager its *own* filespec. so, at some future point some chun...
...And 2 more matches
A XUL Bestiary - Archive of obsolete content
ckage mentioned in the previous example as a "stand-alone" chrome. this special option allows you to create and access chromes independent of the mozilla browser and begins to suggest some possibilities for xul-as-platform beyond the simple restyling of the browser. package a package is in some ways like a chrome, but it is specific to the mozilla architecture. a package is a chunk of interface code that sits in a particular place within mozilla's package hierarchy. like a chrome, that chunk usually contains xul content, css and graphic skin information, localization strings, and maybe some platform-specific code. the navigator is a package defined in mozilla/bin/chrome/navigator, the mail/news component is a package in mozilla/bin/chrome/mailnews/, and so on. each package directory typicall...
...o on. the dom and the aom form a kind of continuum, the whole of which is manipulable from the standards upon which xul is based. near synonyms for xul there is much confusion about the words that begin with "x" in the mozilla open source project. the mozilla xparchitecture section below describes xpcom, xpidl, and xpconnect, three somewhat related technologies for getting access to application code from the interface. this section describes xul, xptoolkit, and xpfe, which are in some respects synonymous and in others quite different. in briefest terms, xul is the xml-based language used for creating interfaces, xptoolkit is the set of xul widgets (menus, toolbar, etc.) actually assembed for this purpose -- the building blocks of the interface, as it were -- and xpfe, the cross platform fro...
...stener" is a special attribute of an object that listens to its own events. the document, for example, has an "onload" event listener to listen for its "load" event. xul buttons have "oncommand" event listeners. the event listener is really a convenience; instead of using it, you could find out when an object fired an event, then go find out what that event was, and then write some event handling code as a response to that event, but the event listener provides an easy mechanism for writing event handlers for specific, common events. an event handler is a snippet of code that you write in response to an event. an "onload" event handler says, in effect, when this document loads, i want to this to happen. and the event listener attribute provides a very convenient place in which to write event ...
...And 2 more matches
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
dow). this needs to be looked into. adding the toolbar button toolkit applications have customizable toolbars; therefore, it's common practice for extensions to add their toolbar buttons to the toolbar palette, rather than adding them directly to the toolbar. the latter is possible, but is not recommended and is harder to implement. adding a button to the toolbar palette is very easy. ...
... buttons, put more <toolbarbutton> elements inside the <toolbarpalette> element. wrap elements other than <toolbarbutton> in <toolbaritem>. adding the button bootstrap style adding a button to the browserpalette on runtime in a bootstrap addon is a bit different because the browserpalette is indirectly reached. a simple document.getelementbyid('browsertoolbarpalette') will not work. this is the code to create and add it in. let button = doc.createelement("toolbarbutton"); button.setattribute("id", button_id); button.setattribute("label", "replace bookmark"); button.setattribute("class", "toolbarbutton-1 chromeclass-toolbar-additional"); button.setattribute("tooltiptext", "replace an existing bookmark"); button.style.liststyleimage = "url(" + icon + ")"; button.addeventlistener("command", ma...
... here are some discussions at mozillazine about adding a toolbar button in a bootstrap ...
...And 2 more matches
Cross Package Overlays - Archive of obsolete content
n view this by changing the overlay to a window. the only thing that is special here is the id used on the toolbox. this value (browser-toolbox) is the same as the identifier of the toolbox in the browser window (navigator.xul). this means that the overlay will apply to the toolbox in the browser window and the content will be added as an extra toolbar. ...
...the overlay to a window. the only thing that is special here is the id used on the toolbox. this value (browser-toolbox) is the same as the identifier of the toolbox in the browser window (navigator.xul). this means that the overlay will apply to the toolbox in the browser window and the content will be added as an extra toolbar. ...
...to a window. the only thing that is special here is the id used on the toolbox. this value (browser-toolbox) is the same as the identifier of the toolbox in the browser window (navigator.xul). this means that the overlay will apply to the toolbox in the browser window and the content will be added as an extra toolbar. ...
...And 2 more matches
More Event Handlers - Archive of obsolete content
in the addeventlistener form, the first argument passed to the listener function will be the event object. other arguments can be passed to a listener function, if required. ...
...splayed. the default action can be prevented with the event object's preventdefault method, as in the example below. example 3 : source view <button label="types" type="menu"> <menupopup onpopupshowing="event.preventdefault();"> <menuitem label="glass"/> <menuitem label="plastic"/> </menupopup> </button> alternatively, for attribute event listeners, you can just return false from the code. note that preventing the default action is not the same as stopping event propagation with the stoppropagation method. even if the default action has been prevented, the event will still continue to propagate. similarly, calling the stoppropagation method won't prevent the default action. you must call both methods to stop both from occuring. note that once propagation or the default action has ...
...the time the next event fires. obviously, it would be much too inefficient to send a mousemove event for every pixel the mouse is moved. element relative coordinates you will often want to get the coordinates of an event relative to the element where the event occurred rather than the entire window. you can do this by subtracting the element's position from the event position, as in the following code. var element = event.target; var elementx = event.clientx - element.boxobject.x; var elementy = event.clienty - element.boxobject.y; xul elements have a box object that can be retrieved using the boxobject property. we'll learn more about the box object in a later section, but it holds information pertaining to how the element is displayed, including the x and y position of the element. in this ...
...And 2 more matches
Property Files - Archive of obsolete content
$s files found in the %1$s directory. here, the property file contains three properties. these would be read by a script and displayed to the user. a property file can also include comments. a line that begins with a hash sign ('#') is treated as a comment: # this is a comment welcomemessage=hello, world! # this is another comment goodbyemessage=come back soon! stringbundles you could write the code to read properties yourself, however xul provides the stringbundle element which does this for you. the element has a number of functions which can be used to get strings from the property file and get other locale information. this element reads in the contents of a property file and builds a list of properties for you. you can then look up a particular property by name. <stringbundleset id="str...
...using its id then, it looks up the string 'notfoundalert' in the property file. the function getstring() returns the value of the string or null if the string does not exist. finally, the string is displayed in an alert box. text formatting the next method is getformattedstring(). this method also gets a string with the given key name from the bundle. in addition, each occurrence of formatting code (e.g. %s) is replaced by each successive element in the supplied array. var dir = "/usr/local/document"; var count = 10; var strbundle = document.getelementbyid("strings"); var result = strbundle.getformattedstring("resultmessage", [ dir, count ]); alert(result); this example will display following message in an alert box. 10 files found in the /usr/local/document directory. you will notice t...
...replaced by each successive element in the supplied array. var dir = "/usr/local/document"; var count = 10; var strbundle = document.getelementbyid("strings"); var result = strbundle.getformattedstring("resultmessage", [ dir, count ]); alert(result); this example will display following message in an alert box. 10 files found in the /usr/local/document directory. you will notice the formatting codes %1$s and %2$s is used, and replaced different order in the array. formatting code %n$s is specify the position of corresponding parameter directly. although the word order is not the same in all the languages, by using getformattedstring() the specification of the order can be put out the property files. in case you need to format a string that already contains the percentage character in it (to...
...And 2 more matches
XUL Structure - Archive of obsolete content
the form of html source and transforms it into a document tree. the tree is then converted into a set of objects that can be displayed on the screen. style sheets (css), images, and other technologies are used to control the presentation. xul functions in much the same way. in fact, in mozilla, all document types, whether they are html or xul, or even svg, are all handled by the same underlying code. this means that the same css properties may be used to style both html and xul, and many of the features can be shared between both. however, there are some features that are specific to html, such as forms, and others which are specific to xul, such as overlays. since xul and html are handled in the same way, you can load both from either your local file system, from a web page, or from an exte...
...es can be created by using a zip utility. when the user downloads the zipped file, the packaged files will be installed onto the user's machine. the extension will hook into the browser using a xul specific feature called an overlay which allows the xul from the extension to mesh with the xul in the browser. ...
...eem like the extension has modified the browser, but in reality, the code is all separate, and the extension may be easily uninstalled. registered packages are not required to use overlays, of course. if they don't, you won't be able to access them via the main browser interface, but you can still access them via the chrome url, if you know what it is. standalone xul applications may include xul code in a similar way, but, of course, the xul for the application will be included as part of the installation, instead of having to be installed separately as an extension. however, this xul code will be registered in the chrome system such that the application can display the ui. it is worth noting that the mozilla browser itself is actually just a set of packages containing xul files, javascript ...
...And 2 more matches
Using the Editor from XUL - Archive of obsolete content
throw away their changes, or cancel. note that if they cancel, the close operation is aborted. the user clicks the close widget in their os/window manager. in this case, the onclose method on the <window> element is called. the user chooses 'close' from the file menu, uses the key shortcut, or quits the application, causing all windows to be closed. before each window is closed, javascript code in globaloverlay.js tries to call a trytoclose method on each window. in editor.js, we set this to call editorcanclose(). if the user chooses to save the document, or throw away their changes, then the window is closed. when the last reference to the nseditorshell goes away (as a result of nseditorboxobject releasing its reference) it releases the owning reference on the editor. editor event h...
...mouse listener is used to do middle-mouse paste (which is a unix copy/paste feature). this happens in response to mouseclick with button 2. it also forces an ime commit. nstexteditorfocuslistener editor responds to focus and blur events by showing and hiding the caret or selection as appropriate. nstexteditortextlistener the nsidomtextlistener interface that this implements is used by the ime code. in response to the handletext event, the editor sets the inline input composition string. nstexteditorcompositionlistener nstexteditorcompositionlistener implements another ime-related interface, nsidomcompositionlistener. this is called by ime at the start, end, and to query the current composition. nstexteditordraglistener the drag listener handles drag and drop events in the editor. it re...
...gs for items that you double-click on. the path of a key press so what happens to a key press once it's got to the nstexteditorkeylistener? how does that end up in the document? let's trace through. nstexteditorkeylistener::keypress() gets the key press event. for normal character keys, that falls into nshtmleditor::editorkeypress(). nshtmleditor::editorkeypress() gets the character code from the key event, puts that into a string, and calls nshtmleditor::typedtext(), which simply calls nshtmleditor::inserttext(). nshtmleditor::inserttext() hides quite a bit of complexity in some stack-based classes. nsautoplaceholderbatch is a utility class that wraps text insertion with calls to turn off selection and layout updating (to avoid flicker), and the maintenance of a placeho...
...And 2 more matches
XUL Event Propagation - Archive of obsolete content
to use events effectively in xul, you must be aware of what the actual process for raising, listening to, and handling events is. collectively, this process is referred to as the event model. events are used for different purposes, but they play a particularly important role in creating interactive xul-based user interfaces, since it is events that bring the information about user actions to the code behind the interface. the following image describes in a very basic way how the various actors in the event model interact with one another. the user clicks a button in the interface. this button responds to the user action by raising an event, a message meant to travel from one element within the interface to another. in this case, the event raised was the "click" event, but a variety of eve...
...ok for a listener; it propagates or "bubbles up" the hierarchy of nodes within the interface until it is either handled in some way or passes out of the interface unhandled. any element that is interested in the event -- any part of the interface, in other words, that needs to know about and respond to the user's click action on the button -- "handles" the event with an event handler, or chunk of code to be executed when the given event is "heard". the availability of event listeners is also somewhat pre-determined, though xul provide generalized event listeners (i.e., oncommand event listeners) for most of the elements in the widget hierarchy. event handlers are written by you, the developer of the interface. very often, the event raised by the element is heard by the element itself and hand...
...ers is also somewhat pre-determined, though xul provide generalized event listeners (i.e., oncommand event listeners) for most of the elements in the widget hierarchy. event handlers are written by you, the developer of the interface. very often, the event raised by the element is heard by the element itself and handled right there before it bubbles up any higher. this is the case in the example code in the diagram, where the onclick event listener for the button element handles the click event by displaying a simple alert dialog: <button value="click me" onclick="alert('thank you')" /> the opposite of event bubbling is event capturing. where event bubbling propagates an event from its target up higher into the node hiearchy, event capturing intercepts an event before it is received by oth...
...And 2 more matches
Building XULRunner with Python - Archive of obsolete content
ipt. this gives access to python features and modules and builds on mark hammond's pyxpcom work from active state. xpcom components can also be created in python. currently (mar 07) python is not enabled by default so a custom build of mozilla is needed. this page provides instructions in the hope of eliminating much trial and error. you should also read the the developer documentation on source code and building as wells as pyxpcom xulrunner with python promises to be a good platform for accessibility projects and both jambu alternative input and the iaccessible2 test tool are using it. of particular interested is access to msaa and iaccessible2 via the python comtypes package. development machine setup first a word of warning that zonealarm has exhibited memory leaks that cause build m...
...t having created amozilla project directory (e.g.c:\projects\mozilla or/c/projects/mozilla in msys) create the following .mozconfig file. note this is complete and does not require the checkout of any other project specific .mozconfig files as sometimes shown. it effectively specifies a release build that is not particularly suitable for debugging xulrunner itself. it uses the trunk (or latest) code in cvs so may be unstable. mk_add_options moz_objdir=@topsrcdir@/../obj-xulrunner mk_add_options moz_co_project=xulrunner ac_add_options --enable-application=xulrunner ac_add_options --enable-extensions=python,default ac_add_options --disable-javaxpcom ac_add_options --disable-activex ac_add_options --disable-activex-scripting ac_add_options --disable-tests ac_add_options --enable-optimize to ...
...d_options moz_objdir=@topsrcdir@/../obj-xulrunner mk_add_options moz_co_project=xulrunner ac_add_options --enable-application=xulrunner ac_add_options --enable-extensions=python,default ac_add_options --disable-javaxpcom ac_add_options --disable-activex ac_add_options --disable-activex-scripting ac_add_options --disable-tests ac_add_options --enable-optimize to check out all the required source code and build it the first time with no local client.mk file, execute cd /c/projects cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot co mozilla/client.mk cd mozilla make -f client.mk for subsequent updates from cvs followed by a build, use cd /c/projects/mozilla make -f client.mk which will also checkout client.mk itself for build only, without checkouts, use make -f client.mk build...
...And 2 more matches
How to enable locale switching in a XULRunner application - Archive of obsolete content
control with the available locales the available package locales are declared in the chrome manifest. ...
...en-gb/ locale localeswitchdemo fr-fr locale/fr-fr/ how are you going to populate the xul listbox? ...
.... the dynamic list population requires an xpcom to query the currently selected locale as well as all locales available in the application package. ...
...And 2 more matches
calICalendarView - Archive of obsolete content
is, however, no practical obstacle to the interface being implemented by any javascript object associated with a group of dom nodes, even non-anonymous xul nodes. in the vast majority of cases, the dom corresponding to an implementation of calicalendarview will be rather complex. this explains the need for the fairly large list off attributes and methods that must be implemented, so that outside code can be able to gain a decent picture of the current state of those nodes. it should be noted, however, that the methods and attributes implemented by a calicalendarview need not behave in any predictable fashion. for instance, when the showdate method of the the calendar-multiday-view (an implementation of this interface) will sometimes show an entire week of dates, and sometimes show only the si...
...required predictability allows calicalendarview implementations to be re-used in a variety of sitatuations. it also fueled the development, however, of the more predictable, but less flexible calidecoratedview, which usually contains an embedded calicalendarview. calendar/base/public/calicalendarview.idlscriptable please add a summary to this article. ...
...playcalendar in order to be notified of additions, modifications, and deletions of items it may be displaying. note that in most cases, this attribute will be set by the consumers of calicalendarview very early in an application/extension's loading process. controller the controller for a calicalendarview is an implementation of calicalendarviewcontroller and provides an integral link with the code in which a calicalendarview may be used. this link allows the calicalendarview to have a way of creating, modifying, and deleting events based on user interaction with the dom nodes it controls, often without requiring any other user interaction. in general, therefore, a calicalendarview will not provide its own controller, but rather rely on other code to set this attribute. implementations shou...
...And 2 more matches
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
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/" > <channel> <t...
...n, 15 may 2005 13:02:08 -0500</lastbuilddate> <link>http://www.example.com</link> <item> <title>a link in here</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/114</guid> <pubdate>sun, 15 may 2005 13:02:08 -0500</pubdate> <link>http://www.example.com/blog/2005/05/15/114</link> <content:encoded><![cdata[this is a <a href="http://example.com/">link</a>.]]></content:encoded> </item> <item> <title>some italics html</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/113</guid> <pubdate>sun, 15 may 2005 10:55:12 -0500</pubdate> <link>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/113</link> ...
... <a href="http://example.com/">link</a>.]]></content:encoded> </item> <item> <title>some italics html</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/113</guid> <pubdate>sun, 15 may 2005 10:55:12 -0500</pubdate> <link>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/113</link> <content:encoded><![cdata[this is <i>italics</i>.]]></content:encoded> </item> <item> <title>some bold html</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/112</guid> <pubdate>sun, 15 may 2005 08:14:11 -0500</pubdate> <link>http://www.example.com/blog/2005/05/15/112</link> <content:encoded><![cdata[thi...
...And 2 more matches
Tamarin Tracing Build Documentation - Archive of obsolete content
tamarin source versions the following instructions are for obtaining and building the tamarin tracing source code. for instructions on tamarin central, please see tamarin build documentation supported platforms operating system processor status windows xp x86 supported, acceptance and performance tests automated in buildbot mac os x 10.4 x86 supported, acceptance and performance tests automated in buildbot linux - ubuntu 8.0.4 x86 supported, acceptance and performance tests automated in buildbot windows mobile (pocket pc 5.0) armv4t supported, acceptance and performance tests automated in buildbot raw image (no os) armv5 supported, acceptance and performance tests not done linux (nokia n810) armv5 supported, acceptance and performance tests not done current build stat...
...tracing tamarin-tracing building tamarin building tamarin will create all the libraries for the avmplus and garbage collector (mmgc), and create a standalone executable, avmshell, for executing files in the abc file format. running avmshell without any arguments will list the available options. note that additional command-line arguments are only available in the debug configuration. the tamarin codebase contains a cross-platform build system for mozilla developers. the cross-platform build system is used for daily automated build testing so it is the most reliable system. the tamarin codebase has the ability to build additional code which supports debugging hooks. in the xcode project, this is the debug_debugger and release_debugger configurations. the flash player builds tamarin with the de...
...cross-platform build first, you must have the mozilla build prerequisites for your platform. ...
...And 2 more matches
Old Proxy API - Archive of obsolete content
ilities between implementations and the behavior may change in the future. warning: the spidermonkey proxy implementation is a prototype and the proxy api and semantics specifications are unstable. the spidermonkey implementation may not reflect the latest specification draft. it is subject to change anytime. it is provided as an experimental feature. do not rely on it for production code. introduction proxies are objects for which the programmer has to define the semantics in javascript. the default object semantics are implemented in the javascript engine, often written in lower-level languages like c++. proxies let the programmer define most of the behavior of an object in javascript. they are said to provide a meta-programming api. terminology catch-all mechanism (or "i...
...his bound to a new object delegating to the proxy's prototype. handler is an object that implements the handler api. handler api there are two kinds of traps: fundamental and derived traps. if one of the fundamental traps isn't implemented and the proxy is used in a way that expects the fundamental trap to be defined, then an error is thrown. ...
...ndamental trap to be defined, then an error is thrown. if a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on the proxy. if the derived trap is undefined, a default implementation using the fundamental traps is used. in other words: fundamental traps are required, derived traps are optional. fundamental traps emulated javascript code handler method description object.getownpropertydescriptor(proxy, name) getownpropertydescriptor: function(name) -> propertydescriptor | undefined should return a valid property descriptor object, or undefined to indicate that no property with name exists in the emulated object. object.getpropertydescriptor(proxy, name) getpropertydescriptor: function(name) -> pro...
...And 2 more matches
Writing JavaScript for XHTML - Archive of obsolete content
pplication/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.) to test the following examples locally, use firefox's extension switch. just write an ordinary (x)html file and save it once as test.html and once as test.xhtml. problem: nothing works after switching the mime type suddenly no inline script works anymore. even the plain old alert() method is gone. the code looks something like this: <script type="text/javascript"> //<!-- window.alert("hello world!"); //--> </script> solution: the cdata trick this problem usually arises, when inline scripts are included in comments. this was common practice in html, to hide the scripts from browsers not capable of js. in the age of xml comments are what they were intended: comments. before processing t...
...hide the scripts from browsers not capable of js. in the age of xml comments are what they were intended: comments. before processing the file, all comments will be stripped from the document, so enclosing your script in them is like throwing your lunch in a piranha pool. ...
..., so enclosing your script in them is like throwing your lunch in a piranha pool. moreover, there's really no point to commenting out your scripts -- no browser written in the last ten years will display your code on the page. the easy solution is to do away with the commenting entirely: <script type="text/javascript"> window.alert("hello world!"); </script> this will work so long as your code doesn't contain characters which are "special" in xml, which usually means < and &. ...
...And 2 more matches
Building Mozilla XForms - Archive of obsolete content
mercurial, the extensions live in separate repositories. before you can start building the xforms extension, you should check your mozilla build environment by doing a regular firefox build. have a look at the build instructions for detailed information for your platform. ...
...latform. ...
.../toolkit version source code notes status firefox 2.0 gecko 1.8.1 cvs, branch mozilla_1_8_branch not developed any more last release: 0.8.5ff2 firefox 3.0 gecko 1.9.0 cvs, branch head not developed any more last release: 0.8.5ff3 firefox 3.5 gecko 1.9.1 xforms/schema-validation code does not build with firefox 3.5 any more not supported firefox 3.6 gecko 1.9.2 xforms/schema-validation code does not build with firefox 3.6 any more not developed any more last release: 0.8.6 firefox 4 gecko 2.0 mercurial, repositories mozilla-central xforms schema-validation mostly works upcoming 0.8.7 release if you have your first working firefox build, you can go on with building the xforms extension. ...
...And 2 more matches
Archived open Web documentation - Archive of obsolete content
is a non-native jxon algorithm. e4x tutorial this tutorial walks you through the basic syntax of e4x (ecmascript for xml). with e4x, programmers can manipulate an xml document with a syntax more familiar to javascript programming. talk:array.foreach() ok, in the end i didn't remove the old code as it isn't hosted anywhere (i thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document. iterator the iterator function returns an object which implements legacy iterator protocol and iterates over enumerable properties of an object. liveconnect (pl...
...vior of an object in javascript. they are said to provide a meta-programming api. parallelarray the goal of parallelarray was to enable data-parallelism in web applications. the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be limited to the parallelizable subset of js that firefox supports. properly using css and javascript in xhtml documents xhtml™ 1.0 the extensible hypertext markup language (second edition) defines xhtml to be a reformulation of h...
... to write entire web apps -- the same language which billions of web pages already use, every day. sharp variables in javascript a sharp variable is a syntax in object initializers that allows serialization of objects that have cyclic references or multiple references to the same object. ...
...And 2 more matches
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
by following the guidelines that have been put into place, organizations like aol can ...
...um ) iana (internet assigned numbers authority ) ecma international like the processes and standards that accountants and project managers must follow, the above-mentioned standards organizations provide focus and direction for the development engineering community. by following the guidelines that have been put into place, organizations like aol can enhance user experience, interoperability, code reuse, shared resources, and goodwill while reducing costs. i will discuss each of these items in the following paragraphs. interoperability the key to interoperability is settling on a standard that has a potential for long-term use. an organization must have the assurance that the standard they choose to incorporate into their development process will be relevant in the future. in other words...
...eroperability the key to interoperability is settling on a standard that has a potential for long-term use. an organization must have the assurance 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 funct...
...And 2 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
ity on a binary level due to the jri/jni switch. the new mozilla xpcom architecture allows xpcom components be scriptable via a different mechanism called xpconnect. we leverage some of these ideas to help you make your netscape communicator 4.x plugins exposed to javascript in mozilla based browsers. in order to make it still possible to script plugins, some changes have been made to the mozilla code. the changes allow to make existing 4.x plugins scriptable with only minor modifications in their code. the present document describes the steps of what should be done to the plugin code to turn it scriptable again. what's in the mozilla code? a couple of lines have been added to the dom code asking a plugin to return a scriptable iid and a pointer to a scriptable instance object. the old plugin ...
...windows command uuidgen should be sufficient. an interface definition (.idl) file describing the plugin scriptable interface should be added to the project (see example 1). a scriptable instance object should be implemented in the plugin. this class will contain native methods callable from javascript. this class should also inherit from nsiclassinfo an...
...n native methods callable from javascript. this class should also inherit from nsiclassinfo and implement its methods to be able to request all necessary privileges from the mozilla security manager (see example 2). two new cases for the above mentioned new variables should be added to the plugin implementation of npp_getvalue (see example 3). ...
...And 2 more matches
Index - Game development
beginner, webgl babylon.js is one of the most popular 3d game engines used by developers. as with any other 3d library it provides built-in functions to help you implement common 3d functionality more quickly. in this article we'll take you through the real basics of using babylon.js, including setting up a development environment, structuring the necessary html, and writing the javascript code. 18 building up a basic demo with playcanvas 3d, animation, beginner, canvas, games, playcanvas, tutorial, webgl, camera, lighting, rendering of course, it depends on your approach — designers may favor the online editor while programmers will prefer having the full control over the coding environment and will probably use the engine's source files. the good thing is that y...
...uted directly by the graphics pipeline. there are two types of shaders: vertex shaders and fragment (pixel) shaders. vertex shaders transform shape positions into 3d drawing coordinates. fragment shaders compute the renderings of a shape's colors and other attributes. 25 async scripts for asm.js games, javascript, asm.js, async every medium or large game should compile asm.js code as part of an async script to give the browser the maximum flexibility to optimize the compilation process. in gecko, async compilation allows the javascript engine to compile the asm.js off the main thread when the game is loading and cache the generated machine code so that the game doesn't need to be compiled on subsequent loads (starting in firefox 28). to see the difference, toggle javascrip...
...ols using the gamepad api controls, gamepad api, gamepads, games, javascript, controllers the gamepad api is very easy to develop with. now it's easier than ever to deliver a console-like experience to the browser without the need for any plugins. you can play the full version of the hungry fridge game directly in your browser, install it from the firefox marketplace or check the source code of the demo along with all the other resources on the gamepad api content kit. 30 implementing game control mechanisms controls, desktop, gamepad, games, javascript, laptop, mobile, keyboard, mouse, touch one of html5's main advantages as a game development platform is the ability to run on various platforms and devices. streamlining cross device differences creates multiple ...
...And 2 more matches
Load the assets and print them on screen - Game development
« previousnext » this is the 3rd step out of 16 in the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson03.html. our game will feature a ball rolling around the screen, bouncing off a paddle, and destroying bricks to earn points — familiar, huh? in this article we'll look at how to add sprites into our gameworld. having a ball let's start by creating a javascript variable to represent our ball. add the following line between the game initialization code (our var game... block) and the preload() function: var ball; note: for the sake of this tutorial, we will use global variables. the purpose of the tutorial is to teach phaser-specific approaches to game development rathe...
...asier using phaser than using pure javascript. to load the asset, we will use the game object created by phaser, executing its load.image() method. add the following new line just inside the preload() function, at the bottom: function preload() { // ... ...
... our game code — for example, in our ball variable name — so we need to make sure it is the same. the second parameter is the relative path to the graphic asset. in our case, we will load the image for our ball. (note that the file name does not also have to be the same, but we'd recommend it, as it makes everything easier to follow.) of course, to load the image, it must be available in our code directory. grab the ball image from github, and save it inside an /img directory in the same place as your index.html file. ...
...And 2 more matches
Plug-in Development Overview - Gecko Plugin API Reference
re to provide and how it will interact with the browser and the special media for which the plug-in is created. decide the mime type for the plug-in (see registering plug-ins). set up your development environment properly. you can use a variety of environments to create a plug-in, but make sure that you have the necessary files from the plugin sdk. create a plug-in project. write your plug-in code and implement the appropriate plug-in api methods for basic plug-in operation. you'll find an overview of the plug-in api methods in this chapter, as well as separate chapters for all of the major functional areas of the plug-in api. also see making plug-ins scriptable for more information about making plug-ins accessible from the browser. build the plug-in for your operating system. see "buildi...
... for description language: for language in use in the mime types and file extensions strings, multiple values are separated by the "|" character, for example: video/quicktime|audio/aiff|image/jpeg the version stamp will be loaded only if it has been created with the language set to "us english" and the character set to "windows multilingual" in your development environment. the resource code for this language and character set combination is 040904e4. unix on unix, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser loads each library and calls into the np_getmimedescription entry point. this exported c function should return a string containing the type, extension list, and typ...
..._posturl, except that it notifies the plug-in of the result when the operation completes. for information about using these methods, see urls. starting in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), you can get the origin of the document in a secure, convenient way by calling npn_getvalue() to retrieve the value of the variable npnvdocumentorigin. the returned value is the unicode serialization of the document's origin converted to nfkc-encoded (that is, normalized) utf-8. your plug-in must free the returned string's memory by calling npn_memfree() when you're done with it. getting version and ui information the netscape group of plug-in api methods provides some basic services to the plug-in. you can use these netscape methods: to identify the browser in which your p...
...And 2 more matches
Test your skills: WAI-ARIA - Learn web development
this aim of this skill test is to assess whether you've understood our wai-aria basics article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. wai-aria 1 in our first aria task, we present you with a section of non-semantic markup, which is obviously meant to be a list. ...
... tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. wai-aria 1 in our first aria task, we present you with a section of non-semantic markup, which is obviously meant to be a list. assuming you are not able to change the elements used, how can you allow screenreader users to recognize this as a list? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. wai-aria 2 in our second wai-aria task, we present a simple search form, and we want you to add in a couple of wai-aria features to improve its accessibility: how can you allow the search form to be called out as a separate landmark on the page by screenre...
... wai-aria 3 for this final wai-aria task, we return to an example we previously saw in the css and javascript skilltest. as before, we have a simple app that presents a list of animal names. clicking one of the animal names causes a further description of that...
...And 2 more matches
WAI-ARIA basics - Learn web development
and properties like aria-required or aria-posinset to provide further clues as to functionality. one thing to remember though — you should only use wai-aria when you need to! ideally, you should always use native html features to provide the semantics required by screenreaders to tell their users what is going on. sometimes this isn't possible, either because you have limited control over the code, or because you are creating something complex that doesn't have an easy html element to implement it. in such cases, wai-aria can be a valuable accessibility enhancing tool. but again, only use it when necessary! note: also, try to make sure you test your site with a variety of real users — non-disabled people, people using screenreaders, people using keyboard navigation, etc. they will hav...
...ssibility is the built-in keyboard accessibility of features such as buttons, form controls, and links. generally, you are able to use the tab key to move between controls, the enter/return key to select or activate controls, and occasionally other controls as needed (for example the up and down cursor to move between options in a <select> box). ...
...er/return key to select or activate controls, and occasionally other controls as needed (for example the up and down cursor to move between options in a <select> box). however, sometimes you will end up having to write code that either uses non-semantic elements as buttons (or other types of control), or uses focusable controls for not quite the right purpose. you might be trying to fix some bad code you've inherited, or you might be building some kind of complex widget that requires it. in terms of making non-focusable code focusable, wai-aria extends the tabindex attribute with some new values: tabindex="0" — as indicated above, this value allows elements that are not normally tabbable to become tabbable. this is the most useful value of tabindex. tabindex="-1" — this allows not no...
...And 2 more matches
Debugging CSS - Learn web development
html for you. if you incorrectly closed an element, for instance opening an <h2> but closing with an </h3>, the browser will figure out what you were meaning to do and the html in the dom will correctly close the open <h2> with an </h2>. the browser will also normalize all of the html, and the dom will also show any changes made by javascript. view source in comparison, is simply the html source code as stored on the server. the html tree in your devtools shows exactly what the browser is rendering at any given time, so it gives you an insight into what is really going on. inspecting the applied css select an element on your page, either by right/ctrl-clicking on it and selecting inspect, or selecting it from the html tree on the left of the devtools display. try selecting the element with ...
...magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier. do you have valid html and css? browsers expect your css and html to be correctly written, however browsers are also very forgiving and will try their best to display your webpages even if you have errors in the markup or stylesheet. if you have mistakes in your code the browser needs to make a guess at what you meant, and it might make a different decision to what you had in mind. in addition, two different browsers might cope with the problem in two different ways. a good first step therefore is to run your html and css through a validator, to pick up and fix any errors. css validator html validator is the property and value supported by the browser y...
...an work out how to make the new selector specific enough to override it. make a reduced test case of the problem if the issue isn't solved by the steps above, then you will need to do some more investigating. the best thing to do at this point is to create something known as a reduced test case. being able to "reduce an issue" is a really useful skill. it will help you find problems in your own code and that of your colleagues, and will also enable you to report bugs and ask for help more effectively. a reduced test case is a code example that demonstrates the problem in the simplest possible way, with unrelated surrounding content and styling removed. this will often mean taking the problematic code out of your layout to make a small example which only shows that code or feature. to creat...
...And 2 more matches
Test your skills: Images and Form elements - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...following changes to the way this form looks: use attribute selectors to target the search field and button inside .myform. make the form field and button use the same text size as the rest of the form. give the form field and button 10 px of padding. give the button a purple background (i used rebeccapurple), white foreground, no border and rounded corners of 5px. try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work int...
...And 2 more matches
Test your skills: Overflow - Learn web development
the aim of these tasks is to help you check your understanding of overflow in css. note: you can try out solutions in the interactive editors below, however, it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one the content is overflowing the box because it has a fixed height. keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. ...
... or further help section at the bottom of this page. task one the content is overflowing the box because it has a fixed height. keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. test by removing some of the text from the html, that if there is only a small amount of text that does not overflow, no scrollbar appears. ...
... assessment or further help you can practice these examples in the interactive editors mentioned above. ...
...And 2 more matches
Flexbox - Learn web development
ox makes a lot of layout tasks much easier. let's dig in! introducing a simple example in this article we are going to get you to work through a series of exercises to help you understand how flexbox works. to get started, you should make a local copy of the first starter file — flexbox0.html from our github repo — load it in a modern browser (like firefox or chrome), and have a look at the code in your code editor. you can see it live here also. you'll see that we have a <header> element with a top level heading inside it, and a <section> element containing three <article>s. we are going to use these to create a fairly standard three column layout. specifying what elements to lay out as flexible boxes to start with, we need to select which elements are to be laid out as flexible bo...
...ng their container. this is quite an advanced flexbox feature, and we won't be covering it any further in this article. the minimum size value we discussed above. this can be specified individually using the flex-basis longhand value. we'd advise against using the longhand flex properties unless you really have to (for example, to override something previously set). they lead to a lot of extra code being written, and they can be somewhat confusing. horizontal and vertical alignment you can also use flexbox features to align flex items along the main or cross axis. let's explore this by looking at a new example — flex-align0.html (see it live also) — which we are going to turn into a neat, flexible button/toolbar. at the moment you'll see a horizontal menu bar, with some buttons jammed...
...x items sit on the cross axis. by default, the value is stretch, which stretches all flex items to fill the parent in the direction of the cross axis. if the parent hasn't got a fixed width in the cross axis direction, then all flex items will become as long as the longest flex items. this is how our first example got equal height columns by default. the center value that we used in our above code causes the items to maintain their intrinsic dimensions, but be centered along the cross axis. this is why our current example's buttons are centered vertically. you can also have values like flex-start and flex-end, which will align all items at the start and end of the cross axis respectively. see align-items for the full details. you can override the align-items behavior for individual flex...
...And 2 more matches
Test your skills: position - Learn web development
the aim of this task is to get you working with the css position property and values covered in our lesson on position. you will be working through two small tasks which use different elements of the material you have just covered. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. ...
... position two in the below example if you scroll the box the sidebar scrolls with the content. ...
...allenge, can you change the target to display underneath the text? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. position two in the below example if you scroll the box the sidebar scrolls with the content. change it so that the sidebar stays in place and only the content scrolls. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online share...
...And 2 more matches
Getting started with CSS - Learn web development
way. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, and html basics (study introduction to html.) objective: to understand the basics of linking a css document to an html file, and be able to do simple text formatting with css. starting with some html our starting point is an html document. you can copy the code from below if you want to work on your own computer. save the code below as index.html in a folder on your machine. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>getting started with css</title> </head> <body> <h1>i am a level one heading</h1> <p>this is a paragraph of text. in the text is a <span>span element</span> and also a <a href="http://example.c...
.../span> and also a <a href="http://example.com">link</a>.</p> <p>this is the second paragraph. it contains an <em>emphasized</em> element.</p> <ul> <li>item one</li> <li>item two</li> <li>item <em>three</em></li> </ul> </body> </html> note: if you are reading this on a device or an environment where you can't easily create files, then don't worry — live code editors are provided below to allow you to write example code right here in the page. adding css to our document the very first thing we need to do is to tell the html document that we have some css rules we want it to use. there are three different ways to apply css to an html document that you'll commonly come across, however, for now, we will look at the most usual and useful way of doing s...
...a css file. to link styles.css to index.html add the following line somewhere inside the <head> of the html document: <link rel="stylesheet" href="styles.css"> this <link> element tells the browser that we have a stylesheet, using the rel attribute, and the location of that stylesheet as the value of the href attribute. you can test that the css works by adding a rule to styles.css. using your code editor add the following to your css file: h1 { color: red; } save your html and css files and reload the page in a web browser. the level one heading at the top of the document should now be red. if that happens, congratulations — you have successfully applied some css to an html document. if that doesn't happen, carefully check that you've typed everything correctly. you can continue to ...
...And 2 more matches
Styling links - Learn web development
o 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 the reset button. if you get really stuck, press the show solution button to insert the example we showed above. ...
... 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 the reset button. if you get really stuck, press the show solution button to insert the example we showed above. ...
...font-family: 'open sans light',helvetica,arial,sans-serif;"> <h2>html input</h2> <textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"><p>there are several browsers available, such as <a href="#">mozilla firefox</a>, <a href="#">google chrome</a>, and <a href="#">microsoft edge</a>.</p></textarea> <h2>css input</h2> <textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">a { } a:link { } a:visited { } a:focus { } a:hover { } a:active { }</textarea> <h2>output</h2> <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div> <div class="controls"> <input id="reset" type="button" value="reset" style="margin: 10px 1...
...And 2 more matches
How do you set up a local testing server? - Learn web development
they feature asynchronous requests. some browsers (including chrome) will not run async requests (see fetching data from the server) if you just run the example from a local file. this is because of security restrictions (for more on web security, read website security). they feature a server-side language. server-side languages (such as php or python) require a special server to interpret the code and deliver the results. running a simple local http server to get around the problem of async requests, we need to test such examples by running them through a local web server. one of the easiest ways to do this for our purposes is to use python's simplehttpserver (or http.server, depending on the version of python installed.) to do this: install python. if you are using linux or maco...
... you can choose another port by running the server command followed by an alternative port number, e.g. python3 -m http.server 7800 (python 3.x) or python -m simplehttpserver 7800 (python 2.x). you can then access your content at localhost:7800. running server-side languages locally python's simplehttpserver (python 2.0) http.server (python 3.0) module is useful, but it doesn't know how to run code written in languages such as python, php or javascript. to handle that you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. here are a few examples: to run python server-side code, you'll need to use a python web framework. flask is also a good (slightly less heavyweight) alternative to django. to run this you'll need to install pyt...
...d to use a python web framework. flask is also a good (slightly less heavyweight) alternative to django. to run this you'll need to install python/pip, then install flask using pip3 install flask. ...
...And 2 more matches
The web and web standards - Learn web development
standard for ecmascript, which javascript is based on), khronos (who publish technologies for 3d graphics, such as webgl), and others. "open" standards one of the key aspects of web standards, which timbl and the w3c agreed on from the start, is that the web (and web technologies) should be free to both contribute and use, and not encumbered by patents/licensing. therefore anyone can write the code to build a website for free, and anyone can contribute to the standards creation process, where the specs are written. because web technologies are created openly, in collaboration between many different companies, it means that no one company gets to control them, which is a really good thing. you wouldn't want a single company suddenly deciding to put the entire web behind a paywall, or releas...
..."> if we adopted a house-building analogy, html would be like the foundations and walls of the house, which give it structure and hold it together. cascading style sheets (css) is a rule-based language used to apply styles to your html, for example setting text and background colors, adding borders, animating things, or laying out a page in a certain way. as a simple example, the following code would turn our html paragraph red: p { color: red; } in the house analogy, css is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice. javascript is the programming language we use to add interactivity to web sites, from dynamic style switching, to fetching updates from the server, right through to complex 3d graphics. the following simple javascript...
... hairdryer — the things that give your house useful functionality tooling once you've learned the "raw" technologies that can be used to build web pages (such as html, css, and javascript), you'll soon start to come across various tools that can be used to make your work easier or more efficient. examples include: the developer tools inside modern browsers that can be used to debug your code. testing tools that can be used to run tests to show whether your code is behaving as you intended it to. libraries and frameworks built on top of javascript that allow you to build certain types of web site much more quickly and effectively. so-called "linters", which take a set of rules, look at your code, and highlight places where you haven't followed the rules properly. minifiers, which ...
...And 2 more matches
Document and website structure - Learn web development
large font" very useful? note: colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion). ...
...for the right job. to implement such semantic mark up, html provides dedicated tags that you can use to represent such sections, for example: header: <header>. navigation bar: <nav>. main content: <main>, with various content subsections represented by <article>, <section>, and <div> elements. sidebar: <aside>; often placed inside <main>. footer: <footer>. active learning: exploring the code for our example our example seen above is represented by the following code (you can also find the example in our github repository). we'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual. <!doctype html> <html> <head> <meta charset="utf-8"> <title>my page title</title> <link href="https://fonts.googl...
... of england</a></li> <li><a href="#">it never stops raining</a></li> <li><a href="#">oh well...</a></li> </ul> </aside> </main> <!-- and here is our main footer that is used across all the pages of our website --> <footer> <p>©copyright 2050 by nobody. all rights reversed.</p> </footer> </body> </html> take some time to look over the code and understand it — the comments inside the code should also help you to understand it. we aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound html structure, and then laying it out with css. we'll wait for this until you start to study css layout as part of the css topic. html layout elements in more detail it's good to under...
...And 2 more matches
Test your skills: HTML text basics - Learn web development
this aim of this skill test is to assess whether you've understood our html text fundamentals article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html text basics 1 in this task we want you to mark up the provided html using semantic heading and paragraph elements. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html text basics 2 in this task we want you to turn the first un-marked up list into an unordere...
...the provided html using semantic heading and paragraph elements. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html text basics 2 in this task we want you to turn the first un-marked up list into an unordered list, and the second one into an ordered list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. ...
...ist. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html text basics 3 in this task you are provided with a paragraph, and your aim is to use some inline elements to mark up a couple of appropriate words with strong importance, and a couple with emphasis. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. y...
...And 2 more matches
Function return values - Learn web development
previous overview: building blocks next there's one last essential concept about functions for us to discuss — return values. some functions don't return a significant value, but others do. it's important to understand what their values are, how to use them in your code, and how to make functions return useful values. we'll cover all of these below. prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code. objective: to understand function return values, and how to make use of them. what are return values? return values are just what they sound like — the values that a function returns when it has completed. you've already met return values a number of ti...
... takes a string, // replaces one substring with another, and returns // a new string with the replacement made the replace() function is invoked on the mytext string, and is passed two parameters: the substring to find ('cold'). the string to replace it with ('warm'). when the function completes (finishes running), it returns a value, which is a new string with the replacement made. in the code above, the result of this return value is saved in the variable newstring. if you look at the replace() function mdn reference page, you'll see a section called return value. it is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible. some functions don't return any value. (in these cases, our reference pages list the...
...) * number); } this could be written as follows: function random(number) { const result = math.floor(math.random() * number); return result; } but the first version is quicker to write, and more compact. we are returning the result of the calculation math.floor(math.random() * number) each time the function is called. this return value appears at the point the function was called, and the code continues. so when you execute the following: ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); if the three random() calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this: ctx.arc(500, 200, 35, 0, 2 * math.pi); the function calls on the line are run first, and their return values substituted for the function calls, befo...
...And 2 more matches
Silly story generator - Learn web development
ure quantities and units in the story into uk equivalents if the uk radio button is checked before the generate button is pressed. will generate another random silly story if you press the button again (and again...) the following screenshot shows an example of what the finished program should output: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. basic setup: create a new file called main.js, in the same directory as your index.html file. apply the external javascript file to your html by inserting a <script> element into your html referencing main.js. put it just before the closing </body> tag. initial variables and functions: in the raw text file, copy ...
...o complete the following sections describe what you need to do. basic setup: create a new file called main.js, in the same directory as your index.html file. apply the external javascript file to your html by inserting a <script> element into your html referencing main.js. put it just before the closing </body> tag. initial variables and functions: in the raw text file, copy all of the code underneath the heading "1. complete variable and function definitions" and paste it into the top of the main.js file. this gives you three variables that store references to the "enter custom name" text field (customname), the "generate random story" button (randomize), and the <p> element at the bottom of the html body that the story will be copied into (story), respectively. in addition you've ...
... store the first, big long, string of text inside a variable called storytext. store the first set of three strings inside an array called insertx. store the second set of three strings inside an array called inserty. store the third set of three strings inside an array called insertz. placing the event handler and incomplete function: now return to the raw text file. copy the code found underneath the heading "3. event listener and partial function definition" and paste it into the bottom of your main.js file. this: adds a click event listener to the randomize variable so that when the button it represents is clicked, the result() function is run. adds a partially-completed result() function definiton to your code. for the remainder of the assessment, you'll be fi...
...And 2 more matches
Handling text — strings in JavaScript - Learn web development
g. single quotes vs. double quotes in javascript, you can choose single quotes or double quotes to wrap your strings in. both of the following will work okay: let sgl = 'single quotes.'; let dbl = "double quotes"; sgl; dbl; there is very little difference between the two, and which you use is down to personal preference. you should choose one and stick to it, however; differently quoted code can be confusing, especially if you use two different quotes on the same string! the following will return an error: let badquotes = 'what on earth?"; the browser will think the string has not been closed because the other type of quote you are not using to contain your strings can appear in the string. for example, both of these are okay: let sgldbl = 'would you eat a "fish supper"?'; let...
...gl = "i'm feeling blue."; sgldbl; dblsgl; however, you can't include the same quote mark inside the string if it's being used to contain them. the following will error, as it confuses the browser as to where the string ends: let bigmouth = 'i've got no right to take my place...'; this leads us very nicely into our next subject. escaping characters in a string to fix our previous problem code line, we need to escape the problem quote mark. escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. in javascript, we do this by putting a backslash just before the character. try this: let bigmouth = 'i\'ve got no right to take my place...'; bigmouth; this works fine. you can escape other characters in the same way, e.g. \", a...
...see escape notation for more details. concatenating strings concatenate is a fancy programming word that means "join together". ...
...And 2 more matches
Getting started with Ember - Learn web development
ntaxes: javascript (or optionally, typescript) ember's own templating language, which is loosely based on handlebars. the templating language is used to make build and runtime optimizations that otherwise wouldn't be possible. most importantly, it is a superset of html — meaning that anyone who knows html can make meaningful contributions to any ember project with minimal fear of breaking code. designers and other non-developers can contribute to page templates without any knowledge of javascript, and interactivity can be added later. this language also enables lighter asset payloads due to compiling the templates into a "byte code" that can be parsed faster than javascript. the glimmer vm enables extremely fast dom change tracking without the need to manage and diff a cached virtual ...
...e ember guides on accessibility on what it means for website / app design. that said, because this tutorial is a focus on the javascript side of making a small web application, todomvc's value comes from providing pre-made css and recommended html structure, which eliminates small differences between implementations, allowing for easier comparison. later on in the tutorial, we'll focus on adding code to our application to fix some of todomvc's biggest faults. installing the ember tooling ember uses a command-line interface (cli) tool for building and scaffolding parts of your application. you'll need node and npm installed before you can install ember-cli. go here to find out how to install node and npm, if you haven't already got them. now type the following into your terminal ...
...vascript via babel and webpack integration. automated testing environment that runs your tests in the browser, allowing you to test like a user. transpilation, and minification, of both css and javascript for production builds. conventions for minimizing the differences between applications (allowing easier mental context switching). getting ready to build our ember project you'll need a code editor before continuing to interact with your brand new project. if you don't have one configured already, the ember atlas has some guides on how to set up various editors. installing the shared assets for todomvc projects installing shared assets, as we're about to do, isn't normally a required step for new projects, but it allows us to use existing shared css so we don't need to try to guess...
...And 2 more matches
Ember app structure and componentization - Learn web development
<li> <a href="#">all</a> <a href="#">active</a> <a href="#">completed</a> </li> </ul> <button type="button" class="clear-completed"> clear completed </button> </footer> </section> the rendered output should now be as follows: this looks pretty complete, but remember that this is only a static prototype. ...
...eted</a> </li> </ul> <button type="button" class="clear-completed"> clear completed </button> </footer> </section> the rendered output should now be as follows: this looks pretty complete, but remember that this is only a static prototype. now we need to break up our html code into dynamic components; later we'll turn it into a fully interactive app. ...
...work over time as we upgrade, add features, refactor, etc. testing is outside the scope of this tutorial, although generally testing should be implemented as you develop, rather than after, otherwise it tends to be forgotten about. if you're curious about testing, or why you would want to have automated tests, check out the official ember tutorial on testing. before we start adding any component code, let’s create the scaffolding for the other components. enter the following lines into your terminal, one by one: ember generate component todo-list ember generate component todo ember generate component footer you’ll now see the following inside your todomvc/app/components directory: now that we have all of our component structure files, we can cut and paste the html for each component ...
...And 2 more matches
Introduction to automated testing - Learn web development
sounds like a lot of work, doesn't it? we agree — testing all the things we've looked at in previous articles manually can be a real pain. fortunately, there are tools to help us automate some of this pain away. there are two main ways in which we can automate the tests we've been talking about in this module: use a task runner such as grunt or gulp, or npm scripts to run tests and clean up code during your build process. this is a great way to perform tasks like linting and minifying code, adding in css prefixes or transpiling nascent javascript features for maximum cross-browser reach, and so on. use a browser automation system like selenium to run specific tests on installed browsers and return results, alerting you to failures in browsers as they crop up. commercial cross-browser te...
...mentioned above. note: the above two categories are not mutually exclusive. it is possible to set up a task runner to access a service like sauce labs, or lambdatest via an api, run cross browser tests, and return results. we will look at this below as well. using a task runner to automate testing tools as we said above, you can drastically speed up common tasks such as linting and minifying code by using a task runner to run everything you need to run automatically at a certain point in your build process. for example, this could be every time you save a file, or at some other point. inside this section we'll look at how to automate task running with node and gulp, a beginner-friendly option. setting up node and npm most tools these days are based on node.js, so you'll need to install ...
...nning'); }); this requires the gulp module we installed earlier, and then runs a basic task that does nothing except for printing a message to the terminal — this is useful for letting us know that gulp is working. each gulp task is written in the same basic format — gulp's task() method is run, and given two parameters — the name of the task, and a callback function containing the actual code to run to complete the task. you can run your gulp task with the following commands — try this now: gulp adding some real tasks to gulp to add some real tasks to gulp, we need to think about what we want to do. a reasonable set of basic functionalities to run on our project is as follows: html-tidy, css-lint, and js-hint to lint and report/fix common html/css/js errors (see gulp-htm...
...And 2 more matches
Gecko info for Windows accessibility vendors
tml, xhtml, cascading style sheets (css) and the document object model (dom). microsoft active accessibility (msaa) an api devised by microsoft so that accessibility aids can track what's going on inside the user interface of any software package that supports it. ...
...essibility (msaa) an api devised by microsoft so that accessibility aids can track what's going on inside the user interface of any software package that supports it. if you seriously need to understand msaa, you'll need to read the docs on msdn and play with the sample apps and code that come with msaa sdk 1.3. (i recommend sdk 1.3 because the msaa sdk 2.0 doesn't come with the source code to the testing tools. the other differences are not important). dom: document object model this is the w3c's specification for how web content is exposed to javascript and other languages. it covers content, style and events. inside the gecko process, code has full access to dom apis. however, exposing the entire dom to external software packages is quite involved, partially...
...going forward, this may be the only way to efficiently find the content area, as mozilla will begin to become a windowless application, with an exception for plugins which create their own window. when you see the content window receive focus, first check the role. if it is role_pane or role_document then this should be treated as a document for the default modality o...
...And 2 more matches
Index
retire one of your extensions. this article suggests the steps you might want to follow, as well as offering some pointers to a suitable timeline. 682 submitting an add-on add-ons, beginner, tutorial, webextensions this article walks through the process of publishing an add-on. if you just want to get started, head to the submit a new add-on page on amo. 683 source code submission add-ons, extensions, review policy, distribution to complete the review process at addons.mozilla.org (amo), reviewers must be able to read the code in your extension. some build processes render extension code difficult to read. these processes include minifying your code, as well as the use of module bundlers or similar tools, such as webpack. in this case, when you upload ...
... 684 themes add-ons, look & feel, themes themes allow you to change the look and feel of the user interface and personalize it to your tastes. ...
... 684 themes add-ons, look & feel, themes themes allow you to change the look and feel of the user interface and personalize it to your tastes. ...
...And 2 more matches
Choosing the right memory allocator
use these if you link against xpcom or xpcom glue; this includes extensions with binary components. ...
...ional information. ns_alloc() == nsimemory::alloc() ns_realloc() == nsimemory::realloc() ns_free() == nsimemory::free() nsmemory::clone() (note: not part of nsimemory) see infallible memory allocation for information about how to allocate memory infallibly; that is, how to use memory allocators that will only return valid memory buffers, and never return null. allocating strings in xpcom code see "callee-allocated parameters" in the xpcom strings guide; use tonewcstring() or tonewunicode() to allocate strings that will be passed out. these methods convert ns*string to nsimemory allocated, unowned [pruni]char* buffers. do not use nscrt::strdup for returning values from an xpcom object, as that uses a different allocator. nspr memory allocators you should only use the nspr allocator...
...avoid using them elsewhere. ...
...And 2 more matches
Debugging JavaScript
this document is intended to help developers writing javascript code in mozilla, mainly for mozilla itself, but it may also be useful for web developers. it should give pointers to tools, aids and tricks which make debugging your code easier. web console this is the first place to go when you're debugging a web page; open the web console using the web console option in the web developer menu. this shows any javascript errors in your app, as well as any logging calls from the console api. browser console the browser console lets you see all javascript errors and logging in the browser, including from firefox code. to enable it, go to about:config in the url bar and set devtools.chrome.enabled to true, or set the "enable chrome and add-on debugging" option in the developer tool setti...
...developer > browser console. you can also start the browser console when you launch firefox, by launching firefox from the command line and passing --jsconsole as a flag: /path/to/firefox --jsconsole log to the browser console using the standard console api after importing console.jsm: let console = (cu.import("resource://gre/modules/console.jsm", {})).console; console.log("hello from firefox code"); error console this is obsolete and is no longer enabled in firefox by default. use the web console or the browser console instead. browser debugger (built-in) on firefox 19 or later, it's possible to use the built-in js debugger on the browser itself. go to about:config and set the following two prefs: devtools.chrome.enabled: true devtools.debugger.remote-enabled: true after you restar...
...with the devtools.debugger.prompt-connection set to false in about:config. this can be a security risk, especially if you also set the devtools.debugger.force-local preference to false.) then, the browser toolbox displays the available tools for debugging. (note that before firefox 28, only the script debugger was available.) the use of these tools are the same as the built-in tools. ...
...And 2 more matches
Creating Custom Events That Can Pass Data
standard mouse/keyboard events) and, depending on the data passed along with this event, you want firefox to react differently. note that starting with version 6, firefox supports dom level 3 customevent, which lets you dispatch custom events with arbitrary data from javascript. (see bug 427537) requirements in order to do this you must be able to do all of the following: download mozilla source code build mozilla creating custom firefox extensions with the mozilla build system. this is the foundation for everything we'll do. what's in a name despite whatever you may have been taught in your english class, there's a lot in a name when it's an event name. as of gecko 1.8, if your event names do not start with "nsdom" and their interfaces do not start with "nsidom" then you can forget about pa...
..._data({truncated name}, nsdomgenericsh, dom_default_scriptable_flags) around line 2900: dom_classinfo_map_begin({truncated name}, nsidom{truncatedname}) dom_classinfo_map_entry(nsidom{truncated name}) dom_classinfo_event_map_entries dom_classinfo_map_end remember, {truncated name} is the same as above. ...
... same as above. mozilla/content/events/src/nseventdispatcher.cpp note: in the mozilla 1.8.x branch this code is actually in mozilla/content/events/src/nseventlistenermanager.cpp this is quite an important file since this holds the createevent method which acts as a factory method dom events. the change you want to make is in nseventdispatcher::createevent(). ...
...And 2 more matches
Developer guide
t only help you get started as a mozilla contributor, but that you'll find useful to refer to even if you are already an experienced contributor. documentation topics getting started a step-by-step beginner's guide to getting involved with mozilla. for new mozilla developers a directory of articles which are particularly helpful for new mozilla developers. working with mozilla source code a code overview, how to get the code, and the coding style guide. build instructions how to build firefox, thunderbird, seamonkey, or other mozilla applications. development process overview an overview of the entire mozilla development process. managing multiple profiles when working with prerelease versions of firefox, it's often helpful to have multiple firefox profiles, such as one for...
... firefox, it's often helpful to have multiple firefox profiles, such as one for each channel, or for different kinds of testing. getting documentation updated how to ensure that documentation is kept up to date as you develop. mozilla modules and module ownership this article provides information about mozilla's modules, what the role of a module owner is, and how module owners are selected. code snippets useful code samples for a wide variety of things you might need to figure out how to do. mozilla development strategies tips for how to make the most of your time working on the mozilla project. debugging find helpful tips and guides for debugging mozilla code. performance performance guides and utilities to help you make your code perform well (and to play nicely with others). t...
... compatibility guidelines for modifying scriptable and binary apis in mozilla. customizing firefox information about creating customized versions of firefox. task-graph generation what controls the jobs that run on a push to version control? how can you change that? obsolete build caveats and tips a place to put build tips which are no longer relevant to building the latest version of the code from main but are relevant when building old codebases. firefox source docs web-hosted documentation built from the mozilla-central source code. tools bugzilla the bugzilla database used to track issues for mozilla projects. dxr next generation of searching mozilla's source code. in active development. searchfox another option for mozilla code searching. indexes js as well as c++, i...
...And 2 more matches
Security best practices for Firefox front-end engineers
this policy includes all dom apis that take a string and parse it into a dom tree. ...
...this policy includes all dom apis that take a string and parse it into a dom tree. ...
... string and parse it into a dom tree. we use our built-in sanitizer with the following flags: sanitizerallowstyle sanitizerallowcomments sanitizerdropforms sanitizerlogremovals the sanitizer removes all scripts (script tags, event handlers) and form elements (form, input, keygen, option, optgroup, select, button, datalist). the canonical truth for the list of whitelisted elements is the source code. ...
...And 2 more matches
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
o be large incompatibilities between implementations and the behavior may change in the future. the html browser api is an extension of the html <iframe> element that allows web apps to implement browsers or browser-like applications. it was originally used in firefox os to implement browser applications before that project was cancelled; since firefox 47 it is available to desktop chrome code and used in places like the firefox devtools. it consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-level browser window to the embedded content. this means that window.top, window.parent, window.frameelement, etc. should not reflect the frame hierarchy. api extensions: the api includes several ne...
...pages, stop loading, move forward and back in history, and zoom in and out of the page. to run the demo, the best approach is to clone the github repo locally (or just download it directly if you don't do github), open webide, open the repo as a packaged app, then run it either on a simulator or a real device if you have one. in any case, you should at least download the repo and refer to the code as you read the sections below. the html an <iframe> is turned into a browser iframe by setting the mozbrowser attribute on it: <iframe src="http://mozilla.org" mozbrowser> in addition, the <iframe> can be loaded in its own child process — separate to the page embedding this frame — by including the remote attribute. <iframe src="http://hostname.tld" mozbrowser remote> warning: this la...
...to implement the browser controls, and a search bar. the search bar also contains buttons, as well as a form to type search requests into. you can see the full html listing here. the javascript implementation to wire up the functionality required by our simple browser, we've written some basic javascript (see the full javascript listing.) wiring up the back and forward buttons early on in the code we implement two simple event listeners to move the browser back and forward in history when the relevant buttons are pressed: back.addeventlistener('touchend',function() { browser.goback(); }); fwd.addeventlistener('touchend',function() { browser.goforward(); }); the functions can be handled using the browser api htmliframeelement.goback() and htmliframeelement.goforward() methods. you'll...
...And 2 more matches
HTTP Cache
api here is a detailed description of the http cache v2 api, examples included. this document only contains what cannot be found or may not be clear directly from the idl files comments. the cache api is completely thread-safe and non-blocking. there is no ipc support. it's only accessible on the default chrome process. when there is no profile the new http cache works, but everything is stored only in memory not obeying any particular limits. it is strongly encoraged to not use the old cache api any more - nsicacheservice et al. it will soon be completely obsoleted and removed (bug 913828). ...
... consumer, from the point of view the cache, takes a role of the writer. other parallel consumers, if any, are blocked until the writer calls setvalid on the cache entry. the consumer is then responsible to validate the partial content cache entry with the network server and attempt to load the rest of the data. when the server responds positively (in case of an http server with a 206 response code) the writer (in this order) opens the output stream on the cache entry and calls setvalid to unblock other pending openers. concurrent read/write is engaged. lifetime of an existing entry that doesn't pass server revalidation such a cache entry is first examined in the nsicacheentryopencallback.oncacheentrycheck callback, where the consumer finds out it must be revalidated with the server b...
...ing a new storage should there be a need to add a new distinct storage for which the current scoping model would not be sufficient - use one of the two following ways: [preffered] add a new <your>storage method on nsicachestorageservice and if needed give it any arguments to specify the storage scope even more. implementation only should need to enhance the context key generation and parsing code and enhance current - or create new when needed - nsicachestorage implementations to carry any additional information down to the cache service. [not preferred] add a new argument to nsiloadcontextinfo; be careful here, since some arguments on the context may not be known during the load time, what may lead to inter-context data leaking or implementation problems. adding more distinction to nsil...
...And 2 more matches
WebChannel.jsm
components.utils.import("resource://gre/modules/webchannel.jsm"); constructor webchannel(string webchannelid, nsiuri originorpermission); 2nd argument is a valid origin that should be part of requests for this channel. webchannel(string webchannelid, string originorpermission); 2nd argument is a permission for which the permission manager will be checked to determine if the request is allowed. ...
...allback for messages on this channel. removes the channel from the webchannelbroker. parameters none send() sends messages over the webchannel id using the "webchannelmessagetocontent" event. parameters message the message object that will be sent sendercontext the sendercontext parameter passed to the .listen method. ...
... channel. removes the channel from the webchannelbroker. parameters none send() sends messages over the webchannel id using the "webchannelmessagetocontent" event. parameters message the message object that will be sent sendercontext the sendercontext parameter passed to the .listen method. ...
...And 2 more matches
QA phase
now we'll walk you through performing some quality assurance testing on your work to make sure you're on the right track. if you're localizing mozilla websites, your work will display soon after you've committed it without needing a language pack. since such is the case, this part of the guide may not be entirely applicable to you. ...
...if you haven't installed them yet, now is the time to do it. preliminary instructions we will be using the following file directories for this example: your working directory (root)/ mozilla-aurora (en-us source, pulled from http://hg.mozilla.org/releases/mozilla-aurora )/ l10n-central (directory for l10n directories, one per l10n; often referred to as "l10n base")/ your-locale-code (a directory with your l10n files, in this example we'll use x-testing) example: root/mozilla-aurora & root/l10n-central/x-testing additionally, you will need to copy and translate the toolkit/defines.inc file directly from en-us before you can build. this is due to a bug in the build logic. please either follow the above structure closely or adjust the commands below according to your custom...
...ains the necessary build instructions. ...
...And 2 more matches
Fonts for Mozilla 2.0's MathML engine
all math fonts (stix, asana or mathjax fonts) from your package manager or get them from this zip archive. on android, firefox os and other platforms where the instructions above do not work: install the mathml-fonts add-on. this requires gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) or higher. overview mathematical formulas make use of various symbols represented by specific unicode characters. mozilla can display any of these symbols provided suitable unicode fonts are installed. furthermore, in accordance with the w3c css2 recommendation on fonts, authors can specify an ordered list of particular fonts which they prefer (using the font-family property of css), with the assurance that mozilla's font engine will hunt for alternate fonts whenever their specified fonts are not...
...an ordered list of particular fonts which they prefer (using the font-family property of css), with the assurance that mozilla's font engine will hunt for alternate fonts whenever their specified fonts are not found on a particular user's system. if no appropriate font is ultimately found for a given character, mozilla will instead display a box containing the hexadecimal representation of the unicode code point for the character. some mathematical operators are also drawn by using glyphs for larger variants of the character (e.g. summation symbol) or by assembling glyphs for a few pieces of the character (e.g braces). these variant or part glyphs do not in general have unicode assignments, and so font-specific support is required for some characters. mozilla has general support for the common...
...for other characters, mozilla has font-specific support. ...
...And 2 more matches
NSPR Error Handling
pr_bad_descriptor_error the file descriptor used as an argument in the preceding function is invalid. ...
... pr_bad_descriptor_error the file descriptor used as an argument in the preceding function is invalid. ...
... pr_bad_descriptor_error the file descriptor used as an argument in the preceding function is invalid. ...
...And 2 more matches
JSS FAQ
Mozilla › Projects › NSS › JSS › JSS FAQ
if i don't call setcipherpolicy, is the domestic policy used by default? my ssl connection is hanging on windows? how can i tell which ssl/tls ciphers jss supports? how can i debug my ssl connection? can you explain jss ssl certificate approval callbacks? ...
... yes, jss 3.2 and higher supports 64 bit. you will need jdk 1.4 or higher and all the 64 bit versions of nspr, and nss. as well you must use the java flag -d64 to specify the 64-bit data model. is jss fips compliant? nss is a fips-certified software library. jss is considered a fips-compliant software library since it only uses nss for any and all crypto routines. ...
...cify the 64-bit data model. is jss fips compliant? nss is a fips-certified software library. jss is considered a fips-compliant software library since it only uses nss for any and all crypto routines. is there any sample code and documentation? the using jss document describes how to set up your environment to run jss. the only other documentation is the javadoc. jss example code is essentially developer test code; with that understanding, the best directory to look for sample code is in the org/mozilla/jss/tests directory: http://lxr.mozilla.org/mozilla/source/security/jss/org/mozilla/jss/tests org/mozilla/jss/tests/closedbs.java org/mozilla/jss/tests/keyfactorytest.java org/mozilla/jss/tests/digesttest.java org/mozilla/jss/tests/jcasigtest.java...
...And 2 more matches
JSS Provider Notes
this page has been moved to http://www.dogtagpki.org/wiki/jss_provider. the mozilla-jss jca provider newsgroup: mozilla.dev.tech.crypto overview this document describes the jca provider shipped with jss. the provider's name is "mozilla-jss". it implements cryptographic operations in native code using the nss libraries. contents signed jar file installing the provider specifying the cryptotoken supported classes what's not supported signed jar file jss 3.2 implements several jce (java cryptography extension) algorithms. these algorithms have at various times been export-controlled by the us government. sun therefore requires that jar files implementing jce algorithms be digitally signed by an approved organization. netscape has this approval and signs the offic...
...he jar file using the jarsigner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. this means you will not be able to use the jss provider for jce algorithms. you have two choices. use the binary release of jss from mozilla.org. apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension. then you can sign your own jss jar file. installing the provider in order to use any part of jss, including the jca provider, you must first call cryptomanager.initialize(). by default, the jca provider will be installed in the list of providers maintained by the java.sec...
...a the following transformations are supported for generatepublic() and generateprivate(): from to rsapublickeyspec rsapublickey dsapublickeyspec dsapublickey x509encodedkeyspec rsapublickey dsapublickey rsaprivatecrtkeyspec rsaprivatekey dsaprivatekeyspec dsaprivatekey pkcs8encodedkeyspec rsaprivatekey dsaprivatekey ...
...And 2 more matches
Mozilla-JSS JCA Provider notes
contents signed jar file installing the provider specifying the cryptotoken supported classes what's not supported signed jar file jss implements several jce (java cryptography extension) algorithms. these algorithms have at various times been export-controlled by the us government. ...
... signature on the jar file using the jarsigner tool, which is distributed with the jdk. if you build jss yourself from source instead of using binaries downloaded from mozilla.org, your jar file will not have a valid signature. this means you will not be able to use the jss provider for jce algorithms. you have two choices. use the binary release of jss from mozilla.org. apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension. then you can sign your own jss jar file. installing the provider in order to use any part of jss, including the jca provider, you must first call cryptomanager.initialize(). by default, the jca provider will be installed in the list of providers maintained by the java.security.secur...
... dsaprivatekey getx() is not supported because nss does not support extracting data from private keys. keyfactory supported algorithms notes dsa rsa the following transformations are supported for generatepublic() and generateprivate(): from to rsapublickeyspec rsapublickey dsapublickeyspec dsapublickey x509encodedkeyspec rsapublickey dsapublickey rsaprivatecrtkeyspec rsaprivatekey dsaprivatekeyspec dsaprivatekey pkcs8encodedkeyspec rsaprivatekey dsaprivatekey getkeyspec() is not supported. this method exports key material in plaintext and is therefore insecure. note that a public key's data can be accessed directly...
...And 2 more matches
NSS 3.12.4 release notes
la.org/pub/mozilla.org/security/nss/releases/nss_3_12_4_rtm/src/. major changes in nss 3.12.4 nss 3.12.4 is the version that we submitted to nist for fips 140-2 validation. currently nss 3.12.4 is in the "review pending" state in the fips 140-2 pre-validation list at http://csrc.nist.gov/groups/stm/cmvp/documents/140-1/140inprocess.pdf added crl distribution point support (see cert.h). cert_decodecrlissuingdistributionpoint cert_findcrlissuingdistpointexten the old documentation of the expression matching syntax rules was incorrect, and the new corrected documentation is as follows for public nssutil functions (see portreq.h): port_regexpvalid port_regexpsearch port_regexpcasesearch these functions will match a string with a shell expression. the expressions accepted are based loo...
...pressions inside unions may not include unions or exclusions. inside a union, to be matched and not treated as a special character, these characters must be escaped: \ ( | ) [ ~ except when they occur inside a bracketed expression, where only \ and ] require escaping. new functions in the nss shared library: pk11_isinternalkeyslot (see pk11pub.h) secmod_opennewslot (see pk11pub.h) new error codes (see secerr.h): sec_error_bad_info_access_method sec_error_crl_import_failed new oids (see secoidt.h) sec_oid_x509_any_policy the nssckbi pkcs #11 module's version changed to 1.75. obsolete code for win16 has been removed. support for openvms has been removed. bugs fixed the following bugs have been fixed in nss 3.12.4. bug 321755: implement crldistributionpoint extension in libpkix...
...solete code for win16 has been removed. support for openvms has been removed. bugs fixed the following bugs have been fixed in nss 3.12.4. ...
...And 2 more matches
NSS 3.12.5 release_notes
l_renegotiate_never: never renegotiate at all (default). ssl_renegotiate_unrestricted: renegotiate without restriction, whether or not the peer's client hello bears the renegotiation info extension (as we always did in the past). unsafe. tls compression enable tls compression with: ssl_enable_deflate: enable tls compression with deflate. off by default. (see ssl.h) error codes: ssl_error_decompression_failure (see sslerr.h) ssl_error_renegotiation_not_allowed (see sslerr.h) new context initialization and shutdown functions see nss.h for details. the 2 new functions are: nss_initcontext nss_shutdowncontext parameters for these functions are used to initialize softoken. these are mostly strings used to internationalize softoken. memo...
... the parameter "input" of this function is changed from unsigned char * to const unsigned char *. pk11_configurepkcs11 (see nss.h) the name of some parameters have been slightly changed ("des" became "desc"). deprecated headers the header file key.h is deprecated. please use keyhi.h instead. additional documentation in pk11pub.h: the caller of pk11_derencodepublickey should free the returned secitem with a secitem_freeitem(..., pr_true) call. pk11_readrawattribute allocates the buffer for returning the attribute value. the caller of pk11_readrawattribute should free the data buffer pointed to by item using a secitem_freeitem(item, pr_false) or port_free(item->data) call. in secasn1.h: if both pool and dest are null, the caller should f...
... bug 525056: timing attack against ssl3ext.c:ssl3_serverhandlesessionticketxtn() bug 526689: ssl3 & tls renegotiation vulnerability docu...
...And 2 more matches
NSS 3.16.3 release notes
05:00:e1:25:f5:c8:36 cn = quovadis root ca 3 g3 sha1 fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d the trust bits were changed for the following ca certificates ou = class 3 public primary certification authority sha1 fingerprint: a1:db:63:93:91:6f:17:e4:18:55:09:40:04:15:c7:02:40:b0:ae:6b turned off websites and code signing trust bits (1024-bit root) ou = class 3 public primary certification authority sha1 fingerprint: 74:2c:31:92:e6:07:e4:24:eb:45:49:54:2b:e1:bb:c5:3e:61:74:e2 turned off websites and code signing trust bits (1024-bit root) ou = class 2 public primary certification authority - g2 sha1 fingerprint: b3:ea:c4:47:76:c9:c8:1c:ea:f2:9d:95:b6:cc:a0:0...
... sha1 fingerprint: cb:a1:c5:f8:b0:e3:5e:b8:b9:45:12:d3:f9:34:a2:e9:06:10...
... ou = class 2 public primary certification authority - g2 sha1 fingerprint: b3:ea:c4:47:76:c9:c8:1c:ea:f2:9d:95:b6:cc:a0:08:1b:67:ec:9d turned off code signing trust bit (change requested by ca) cn = verisign class 2 public primary certification authority - g3 sha-1 fingerprint: 61:ef:43:d7:7f:ca:d4:61:51:bc:98:e0:c3:59:12:af:9f:eb:63:11 turned off code signing trust bit (change requested by ca) cn = ac raíz certicámara s.a. sha1 fingerprint: cb:a1:c5:f8:b0:e3:5e:b8:b9:45:12:d3:f9:34:a2:e9:06:10:d3:36 turned off websites trust bit (change requested by ca) cn = netlock uzleti (class b) tanusitvanykiado sha1 fingerprint: 87:9f:4b:ee:05:df:98:58:3b:e3:60:d6:33:e7:0d:3f:fe:98:71:af turned off w...
...And 2 more matches
nss tech note3
lients to use strong crypto. certusagesslca ............... an intermediate or root ca cert allowed to issue ssl client or ssl server certs or other intermediate ssl ca certs. certusageemailsigner ......... used to verify s/mime email signatures certusageemailrecipient ...... used to encrypt s/mime emails. certusageobjectsigner ........ used to verify signatures on files of executable code, e.g. jar files. certusagestatusresponder ..... used by an ocsp responder certusageverifyca ............ a ca of any kind. each cert has a "type" and a "key usage", each of which may contain one or more valid values. each of the above seccertusages translates into a required set of cert type and key usage for the certificate itself, and into another set of required cert type and key usage for ...
...quired depends on the key's algorithm. for rsa keys, the required usage is key_encipherment. for other types of keys, it is key_agreement. cert extensions: one vital certificate extension is the "basic constraints" extension. it tells nss whether the cert is a ca cert, or not, and affects every other aspect of how the cert is interpreted by nss. the oid for this extension is { 2 5 29 19 }, encoded in hex as 0x55, 0x1d, 0x13. if the extension is present and has the value true, then this cert is taken to be a ca cert. otherwise it is not (except that trust flags may override this, see discussion of trust flags farther below). netscape has its own openly defined cert type extension, which can be used to explicitly set the cert type in any cert. the cert type extension has bits in it that ...
...be a ca cert. otherwise it is not (except that trust flags may override this, see discussion of trust flags farther below). netscape has its own openly defined cert type extension, which can be used to explicitly set the cert type in any cert. the cert type extension has bits in it that correspond directly to the cert types named above. the oid for this extension is { 2 16 840 1 113730 1 1 } encoded in hex as 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x01 in addition to netscape's own cert type extension, nss recognizes various x.509 extensions. the x.509 key usage extension has oid { 2 5 29 0f } encoded in hex as 0x55, 0x1d, 0x0f. if present, this extension directly determines the values of the 8 key usages defined above. if absent, the cert is assumed to be valid for all key us...
...And 2 more matches
nss tech note7
in nss? there are a few possibilities. rsa key pairs may be generated inside a crypto module (also known as a token). use pk11_generatekeypair() to generate a key pair in a crypto module. key pairs may be generated elsewhere, exported in encrypted form, and imported into a crypto module. public keys may be imported into nss. call seckey_importderpublickey() with type=ckk_rsa to import a der-encoded rsa public key. if you have the modulus and public exponent, you need to first encode them into an rsa public key and then import the public key into nss. pkcs #1 defines an rsa public key as a sequence of modulus and public exponent, both of which are integers. here is the asn.1 type definition: rsapublickey ::= sequence { modulus integer, -- n publicexponent integer -- e } the fo...
...y. if you have the modulus and public exponent, you need to first encode them into an rsa public key and then import the public key into nss. pkcs #1 defines an rsa public key as a sequence of modulus and public exponent, both of which are integers. here is the asn.1 type definition: rsapublickey ::= sequence { modulus integer, -- n publicexponent integer -- e } the following sample code (error handling omitted for brevity) encodes a rsapublickey from a modulus and a public exponent and imports the public key into nss. struct myrsapublickey { secitem m_modulus; secitem m_exponent; } inpubkey; secitem derpubkey; seckeypublickey *pubkey; const sec_asn1template myrsapublickeytemplate[] = { { sec_asn1_sequence, 0, null, sizeof(myrsapublickey) }, { sec_asn1_intege...
...offsetof(myrsapublickey,m_modulus), }, { sec_asn1_integer, offsetof(myrsapublickey,m_exponent), }, { 0, } }; prarenapool *arena; /* * point inpubkey.m_modulus and m_exponent at the data, and * then set their types to unsigned integers. */ inpubkey.m_modulus.type = siunsignedinteger; inpubkey.m_exponent.type = siunsignedinteger; arena = port_newarena(der_default_chunksize); sec_asn1encodeitem(arena, &derpubkey, &inpubkey, myrsapublickeytemplate); pubkey = seckey_importderpublickey(&derpubkey, ckk_rsa); port_freearena(arena, pr_false); public keys may be extracted from certificates. given a certficate (certcertificate *), use cert_extractpublickey() to extract its public key. the returned public key may be used after the certificate is destroyed. when the ke...
...And 2 more matches
nss tech note8
background information on libssl's cache functions and sids nss technical note: 8 27 february 2006 nelson b. bolyard here is some background information on libssl's cache functions and sids. a sid (or sslsessionid struct) contains all the info needed to restart the ssl session at a later time on another socket. the protocol code builds such a structure, and then asks the cache code (client or server) to save the info. the protocol code can also ask to remove a sid from the cache. every ssl socket has two function pointers, ss->sec.cache and ss->sec.uncache, which have the following types: typedef void (*sslsessionidcachefunc) (sslsessionid *sid); typedef void (*sslsessioniduncachefunc)(sslsessionid *sid); there are two separate implementations of each function, one for clients ...
...c->cache = ssl_sid_cache; sec->uncache = ssl_sid_uncache; which are functions defined in sslsnce.c, the server session cache source file. for clients these pointers point to sec->cache = cachesid; sec->uncache = lockanduncachesid; which are functions defined in sslnonce.c, the client session cache source file. the same cache/uncache api is used by both client and server code. as originally designed, before calling the cache function, the caller was responsible to fill in the session creation time (which might not be the same as the time of insertion into the cache) and the session expiration time, among other things. since nss 1.0, up until nss 3.4, there were two global variables that contained the expected session lifetimes for ssl2 and ssl3 sessions. extern prui...
... which client programs could set these values. however since nss was delivered as archive libraries, client programs merely declared these two variables for themselves, and then were able to alter those variables directly. for server programs, the function for initializing the server session cache would set these two variables according to two of the arguments to that function. ...
...And 2 more matches
New NSS Samples
new nss sample code this collection of sample code demonstrates how nss can be used for cryptographic operations, certificate handling, ssl, etc. it also demonstrates some best practices in the application of cryptography. these new examples are a work in progress. ...
...es how nss can be used for cryptographic operations, certificate handling, ssl, etc. it also demonstrates some best practices in the application of cryptography. these new examples are a work in progress. ...
...or cryptographic operations, certificate handling, ssl, etc. it also demonstrates some best practices in the application of cryptography. these new examples are a work in progress. ...
...And 2 more matches
PKCS 12 functions
the public functions listed here perform pkcs #12 operations required by some of the nss tools and other applications. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
... public functions listed here perform pkcs #12 operations required by some of the nss tools and other applications. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
... sec_pkcs12addcertandkey mxr 3.2 and later sec_pkcs12addpasswordintegrity mxr 3.2 and later sec_pkcs12createexportcontext mxr 3.2 and later sec_pkcs12createpasswordprivsafe mxr 3.2 and later sec_pkcs12createunencryptedsafe mxr 3.2 and later sec_pkcs12decoderfinish mxr 3.2 and later sec_pkcs12decodergetcerts mxr 3.4 and later sec_pkcs12decoderimportbags mxr 3.2 and later sec_pkcs12decoderiterateinit mxr 3.10 and later sec_pkcs12decoderiteratenext mxr 3.10 and later sec_pkcs12decodersettargettokencas mxr ...
...And 2 more matches
OLD SSL Reference
ssl" illustrates their use in sample client and server applications. initialization initializing caches configuration communication functions used by callbacks cleanup chapter 2 getting started with ssl this chapter describes how to set up your environment, including certificate and key databases, to run the nss sample code. the sample code and makefiles are available via lxr in the sslsamples directory. ssl, pkcs #11, and the default security databases setting up the certificate and key databases setting up the ca db and certificate setting up the server db and certificate setting up the client db and certificate ver...
...eeds for communicating with cryptographic modules. in particular, these functions are used for obtaining certificates, keys, and passwords. ...
...ng with cryptographic modules. in particular, these functions are used for obtaining certificates, keys, and passwords. ...
...And 2 more matches
S/MIME functions
the public functions listed here perform s/mime operations using the s/mime toolkit. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
... the public functions listed here perform s/mime operations using the s/mime toolkit. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
... 3.2 and later nss_cmscontentinfo_setcontent_digesteddata mxr 3.2 and later nss_cmscontentinfo_setcontent_encrypteddata mxr 3.2 and later nss_cmscontentinfo_setcontent_envelopeddata mxr 3.2 and later nss_cmscontentinfo_setcontent_signeddata mxr 3.2 and later nss_cmsdecoder_cancel mxr 3.2 and later nss_cmsdecoder_finish mxr 3.2 and later nss_cmsdecoder_start mxr 3.2 and later nss_cmsdecoder_update mxr 3.2 and later nss_cmsdigestcontext_cancel mxr 3.2 and later nss_cmsdigestcontext_finishmultiple mxr 3.2 and later ...
...And 2 more matches
NSS_3.12.3_release_notes.html
or unset, softoken will trigger an assertion failure in debug builds, and will report an error in non-debug builds. if set to "disabled", softoken will ignore forks, and behave as it did in older versions. if set to any other non-empty value, softoken will report an error in both debug and non-debug builds. nss_use_decoded_cka_ec_point boolean (any non-empty value to enable) tells nss to send ec key points across the pkcs#11 interface in the non-standard unencoded format that was used by default before nss 3.12.3. the new key point format is a der encoded asn.1 octet string. nss_use_shexp_in_cert_name boolean (any non-empty value to ...
...gn depend on the softoken only bug 371522: auto-update of crls stops after first update bug 380784: pk11mode in non fips mode failed. bug 394077: libpkix need to return revocation status of a cert bug 412468: modify certutil bug 417092: modify pkix_certselector api to return an error if cert was rejected. ...
...m (handy for wince) bug 464223: certutil didn't accept certificate request to sign. ...
...And 2 more matches
certutil
specify the trust attributes to modify in an existing certificate or to apply to a certificate when creating it or adding it to a database. there are three available trust categories for each certificate, expressed in the order ssl, email, object signing for each trust setting. ...
...for example: -t "tcu,cu,tuw" use the -l option to see a list of the current certificates and trust attributes in a certificate database. -u certusage specify a usage context to apply when validating a certificate ...
...meca o objectsigningca o critical x.509 certificate extensions are described in rfc 5280. -6 | --extkeyusage keyword,keyword add an extended key usage extension to a certificate that is being created or added to the database. several keywords are available: o serverauth o clientauth o codesigning o emailprotection o timestamp o ocspresponder o stepup o critical x.509 certificate extensions are described in rfc 5280. -7 emailaddrs add a comma-separated list of email addresses to the subject alternative name extension of a certificate or certificate request tha...
...And 2 more matches
Property cache
nly used in the interpreter. the property cache was introduced in bug 365851. basics in general, accessing a property of a native object entails: a property lookup; examining the shape to see how the property can be accessed; actually carrying out the property access. the property cache is a per-thread cache of the results of steps 1 and 2. when executing certain property-accessing bytecode instructions, the interpreter populates the cache to speed future execution of the same instruction. the jit reads the property cache too, as it needs the same information when recording such an instruction. if there is a cache miss, the jit performs parts 1 and 2 of the property access and fills the cache to avoid redoing that work in the interpreter. (in some cases this is necessary for correc...
...escribe the context in which a property lookup occurs. the values consist of two word-sized members. entry->vcap caches the results of part 1 above, telling which object contains the desired property. entry->vword is described in the section entry value words below. it caches the results of part 2, if the property is simple enough for optimized access, or a pointer to the js::shape if not. the opcodes that take advantage of the property cache, as of june 2009, are: getprop, get{x,this,arg,local}prop, and length; name; setprop, bindname, and setname; callprop and callname; and {inc,dec}name and name{inc,dec}. elem opcodes do not use it. nor do {inc,dec}prop or prop{inc,dec}. nor do operations such as add that only need to look up a property (.tostring) in unusual cases. throughout this artic...
...here come to be more than 224 objects that need distinct shapes, the shape rules can no longer be satisfied. the property cache cannot operate without them, so it is disabled permanently. see bug 440834. property cache entries each entry in the property cache hash table is either populated or not; unpopulated entries have .kpc == null. if an entry is populated, the .kpc field points to the bytecode instruction at which it was populated. the entry is valid only for subsequent lookups that occur at the same instruction, for several reasons: the script, not the property cache entry, contains the id of the property being accessed. a property cache entry could be valid for a getprop but not a setprop, e.g. because the property has a setter and not a getter; or vice versa. lookups for jof_na...
...And 2 more matches
JSErrorReport
t is loaded. callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports. linebuf const char * text of the line that caused the error, minus the trailing newline character. tokenptr const char * pointer to the error token in *linebuf. uclinebuf const char16_t * unicode line buffer. this is the buffer that contains the original data. uctokenptr const char16_t * pointer to the error token in *uclinebuf. flags unsigned the logical or of zero or more of the following flags: jsreport_warning this "error" is really only a warning. it will not cause the current operation to fail. jsreport_exce...
... logical or of zero or more of the following flags: jsreport_warning this "error" is really only a warning. it will not cause the current operation to fail. jsreport_exception an exception is being raised. a jserrorreporter might choose to ignore a jserrorreport that has this flag set, since the exception may be caught and handled by javascript code. jsreport_strict this error is only being reported because the engine is in strict mode. jsreport_strict_mode_error this condition is an error in strict mode code, a warning if js_has_strict_option(cx), and otherwise should not be reported at all. we check the strictness of the context's top frame's script; where that isn't appropriate, the caller s...
...l. we check the strictness of the context's top frame's script; where that isn't appropriate, the caller should do the right checks itself instead of using this flag. the constant jsreport_error is 0 and can be used to indicate an error report without any of the above flags. errornumber unsigned the error number. ucmessage const char16_t * the default unicode error message. messageargs const char16_t ** arguments for the error message. exntype int16_t one of the jsexntype constants. description jserrorreport describes a single error that occurs in the execution of script. in the event of an error, filename will either contain the name of the external source file or url containing the script (script src=) or null, in...
...And 2 more matches
JSPrincipals
obsolete since jsapi 13 getprincipalarray void * (*)(jscontext *, jsprincipals *) pointer to the function that returns an array of principal definitions. ...
...obsolete since jsapi 13 getprincipalarray void * (*)(jscontext *, jsprincipals *) pointer to the function that returns an array of principal definitions. ...
...13 methods name description void dump() this is not defined by the js engine but should be provided by the embedding. added in spidermonkey 17 description jsprincipals is the abstract base class of all principals objects, the objects that identify the source of a function or script and are used to determine its privileges. a principals object is like a java codesource. jsprincipals could be passed into the js engine through the js_newglobalobject function. jsprincipals has refcount property that is the reference count. this is used for memory management. each time an object is referenced, refcount must be increased by one. each time an object is dereferenced, refcount must be decremented by one. when refcount reaches zero, the principals are no longer ...
...And 2 more matches
JS_ConvertArguments
ce to the arguments to convert. added in spidermonkey 31 argc unsigned the number of arguments to convert. obsolete since jsapi 30 argv jsval * pointer to the vector of arguments to convert. obsolete since jsapi 30 this must be an argv pointer created by the js engine and passed to a jsnative or jsfastnative callback, not an array created by application code. in certain error cases, js_convertarguments calls js_argv_callee(argv), which accesses memory outside the range [argv .. argv+argc). js_convertarguments may modify argv in place by replacing an argument with the converted value. (the purpose is to ensure gc safety.) format const char * null-terminated string describing the types of the out parameters and how to convert th...
...es do not need to be rooted. (if conversion creates a new gc thing, the corresponding jsval is written back to argv, which is rooted.) description js_convertarguments provides a convenient way to translate a series of js values into their corresponding js types with a single function call. it saves you from having to write separate tests and elaborate if...else statements in your function code to retrieve and translate multiple js values for use with your own functions. cx is the context for the call. argc indicates the number of js values you are passing in for conversion. argv is a pointer to the array of js values to convert. format is a null-terminated c string. each element of the array indicates the c type into which to convert the next available js value. format can contain on...
.... argv is a pointer to the array of js values to convert. format is a null-terminated c string. each element of the array indicates the c type into which to convert the next available js value. ...
...And 2 more matches
JS_GetLocaleCallbacks
in a js_threadsafe build, the caller must be in a request on this jscontext. callbacks jslocalecallbacks * pointer to a jslocalecallbacks struct. ...
...ild, the caller must be in a request on this jscontext. callbacks jslocalecallbacks * pointer to a jslocalecallbacks struct. ...
... jslocaletolowercase implementation of string.prototype.tolocalelowercase() function. jslocalecompare implementation of string.prototype.localecompare() function. ...
...And 2 more matches
JS_GetStringBytes
it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. convert a javascript string to a c string. syntax char * js_getstringbytes(jsstring *str); const char * js_getstringbytesz(jscontext *cx, jsstring *str); // added in jsapi 1.8.2 name type description cx jscontext * (js_getstringbytesz and js_encodestring only) a context. str jsstring * string to retrieve bytes from. description js_getstringbytes and js_getstringbytesz convert the specified javascript string, str, to a c string (an array of 8-bit chars). if js_cstringsareutf8 is true, then the returned string is utf-8, and the conversion is lossless. otherwise the high byte is simply dropped from each jschar. on success,...
...rwise the high byte is simply dropped from each jschar. on success, the return value is a pointer to the char array, which is null-terminated. on failure, js_getstringbytes returns a pointer to a null-terminated empty string; js_getstringbytesz returns null. note: js_getstringbytes() and js_getstringbytesz() have both been removed as of javascript 1.8.5 (firefox 4). instead, you should use js_encodestring, js_getstringencodinglength, js_encodestringtobuffer. the array returned by js_getstringbytes or js_getstringbytesz is automatically freed when str is finalized by the javascript garbage collection mechanism. the application must not modify the contents of the array. note that for non-ascii strings, if js_cstringsareutf8 is false, these functions can return a corrupted copy of the contents ...
...reed when str is finalized by the javascript garbage collection mechanism. the application must not modify the contents of the array. ...
...And 2 more matches
SpiderMonkey 1.8.8
these release notes are an incomplete draft and were initially seeded from the 1.8.5 release notes, so lots of the information here isn't actually new to spidermonkey 1.8.8 (nor is it even the case that the version number will be 1.8.8!). the mozilla javascript team is pleased to announce the release of spidermonkey 1.8.8. you can download full source code here: insert-actual-link-when-the-release-happens (md5 checksum: insert-actual-hash-here). spidermonkey 1.8.8 is the javascript engine that shipped in firefox 10.0. it continues to improve performance over previous spidermonkey releases, with ongoing jit compilation work and with the introduction of type inference to enable faster jitted code. it also contains new language and api features described in detail below. please l...
...ing in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. —insert-actual-release-date-here platform support spidermonkey 1.8.8 is supported on all the platforms where firefox insert-actual-firefox-version-number-here runs. spidermonkey 1.8.8 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 1.8.8 the following features in earlier versio...
...rsions. it's the same language, just not as fast. migrating to spidermonkey 1.8.8 the following features in earlier versions of spidermonkey have been dropped. the jsresolve_classname and jsresolve_with resolve flags (passed to jsclass.resolve when jsclass.flags contains jsclass_new_resolve) have been removed. spidermonkey 1.8.8 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. a signif...
...And 2 more matches
SpiderMonkey 17
these release notes are an incomplete draft and were initially seeded from the (now-defunct) 1.8.8 release notes, which were themselves seeded from the 1.8.5 release notes, so lots of the information here isn't actually new to spidermonkey 17. the mozilla javascript team is pleased to announce the release of spidermonkey 17. you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/mozjs17.0.0.tar.gz (md5 checksum: 20b6f8f1140ef6e47daa3b16965c9202). spidermonkey 17 is the javascript engine that shipped in firefox 17. it continues to improve performance over previous spidermonkey releases, with ongoing jit compilation work and with the introduction of type inference to enable faster jitted code. it also contains new language and api features described in ...
...e let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. — 25 march 2013 platform support spidermonkey 17 is supported on all the platforms where firefox 17 runs. spidermonkey 17 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions. it's the same language, just not as fast. migrating to spidermonkey 17 the following features in earlier versions ...
...ous versions. it's the same language, just not as fast. migrating to spidermonkey 17 the following features in earlier versions of spidermonkey have been dropped. the jsresolve_classname and jsresolve_with resolve flags (passed to jsclass.resolve when jsclass.flags contains jsclass_new_resolve) have been removed. spidermonkey 17 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most of them still have the same names and do the same things. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a list of the most significant changes. a signif...
...And 2 more matches
WebReplayRoadmap
update graphics with the effects of those changes. object watching (not yet implemented) it would be nice to log the changes to a specific object or one of its properties, so that the points of those changes can be seeked to later. bookmarks (not yet implemented) it would be nice to be able to bookmark points in the recording so that they show up on the timeline and can be seeked to later. code path highlighting (not yet implemented) when paused in a frame, the code path taken through the frame (the lines/expressions executed) could be highlighted somehow, which would make it easier to see what happened in the frame. points on the path could be clicked to seek there, which should offer faster and less clunky navigation than stepping buttons. hide unsupported developer tool features (...
...ecording. dynamic analysis features an important but as-yet unexploited advantage of being able to exactly replay a web replay recording is that the recording can be analyzed without overhead affecting the user's experience. this section describes some analyses that could be performed and be helpful for developers who are either debugging a problem, or trying to understand or improve a complex code base. comparing executions (not yet implemented) comparing the behavior of a recording that exhibits a bug with a second recording that doesn't exhibit the bug should help with quickly locating the source of the problem. doing this well will require some experimentation, but in many cases the buggy recording should hit different locations in the source or exhibit different types from the norma...
...zing one or more recordings to study their behavior in detail. if the debugger could perform this analysis then it could show this information to developers and help them understand the app even when they are not actively debugging a particular recording. static type integration (not yet implemented) static type systems like flow and typescript are great and really useful for managing an app's codebase, but they are unsound by design, and it is pretty easy to satisfy the type system and yet have different types in practice. a recording can be analyzed for the types that appear in practice. these can be compared with the types provided to the type system, and any mismatches can be flagged. the points in the recording where the mismatches occur can be identified, and the debugger can seek ...
...And 2 more matches
Mozilla Projects
compare-locales compare-locales is a python script that helps localizers to check their work without running firefox or another application. crash reporting firefox ships with an open-source crash reporting system. this system is combination of projects: emscripten emscripten is an llvm to javascript compiler. it takes llvm bytecode (e.g. generated from c/c++ using clang, or from another language) and compiles that into javascript, which can be run on the web. firefox sync firefox sync synchronizes state and configuration data used by the browser, such as bookmarks, history, preferences, bookmarks, and so forth among all your devices. jshydra jshydra is a static analys...
...d compiles that into javascript, which can be run on the web. firefox sync firefox sync synchronizes state and configuration data used by the browser, such as bookmarks, history, preferences, bookmarks, and so forth among all your devices. jshydra jshydra is a static analysis tool that is capable of performing analysis of general javascript code. l20n l20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization and application logic. leak monitor leak monitor is a firefox extension by l. david baron that helps extension and chrome developers to find memory leaks. it will pop-up an alert when a window is closed and ...
...dd-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. midas midas is the code name for gecko's built-in rich text editor. midas can be enabled via javascript on an html document. when midas is enabled, the document becomes editable by the user. scripting for midas is based on the dhtml commands supported by internet explorer. internet explorer supports the ability to make an entire document editable by setting the designmode property of the document...
...And 2 more matches
A Web PKI x509 certificate primer
e from one of the cas who already have a root certificate included in the major browsers. firefox uses a default set of x.509v3 root certificates for various certification authorities (cas). the root certificates included by default have their "trust bits" set to indicate if the ca's root certificates may be used to verify certificates for ssl servers, s/mime email users, and/or digitally-signed code objects without having to ask users for further permission or information. cas apply to have their root certificates included by default in mozilla products by following the mozilla ca certificate policy and applying for inclusion as per ca:how_to_apply. users may override the default root certificate settings using the certificate manager. some organizations make use of the set of cas included...
... rfc 3766 2358 200 --- bsi 1976 256 256 in other words, sha1 is now deprecated for new uses. we should use at least 3072 key sizes and at least a 256 ecc curve. thus the recommendation here is for the root to be 4096 if using rsa and p384 for the root key. (p384 also chosen for compatibility as most ssl/tls implementations support this part of suite b). ...
...e should use at least 3072 key sizes and at least a 256 ecc curve. thus the recommendation here is for the root to be 4096 if using rsa and p384 for the root key. (p384 also chosen for compatibility as most ssl/tls implementations support this part of suite b). error codes in firefox here are some common errors that might be encountered when working with certificates in firefox. ...
...And 2 more matches
Setting up the Gecko SDK
o organize the parts of the sdk meaningfully. the two top level header files are special. the file mozilla-config.h lists all of the defines used in the sdk. including this header file in your project ensures that the component you create uses the same defines as the gecko libraries themselves. note that mozilla-config.h may be need to be included before other includes in your component's source code. each module directory is divided into three subdirectories: module subdirectories the bin directory contains static libraries, dynamic libraries, and in some cases tools that may be useful in development. the idl directory contains the public idl files exported by the module. the includes directory contains c++ header files used by your component. xpcom exports a number of binaries that sh...
...sdk's bin directory, d:\projects\xulrunner-sdk\bin. environment setup you can create a batch file to set up the environment for you, but this example tells you from the command prompt. set include=c:\program files\microsoft sdks\windows\v7.0\include;c:\program files (x86)\microsoft visual studio 9.0\vc\include;d:\projects\xulrunner-sdk\include this sets up the compiler to know where included code files are, it looks in the platform sdk, visual studio 9.0 include (installed with the platform sdk), and the gecko sdk includes. set lib=c:\program files\microsoft sdks\windows\v7.0\lib;c:\program files (x86)\microsoft visual studio 9.0\vc\lib;d:\projects\xulrunner-sdk\lib this tells the linker where the default libraries to bind to are. this allows you to created the component without sendi...
...l file. ispecialthing.idl #include "nsisupports.idl" [scriptable, uuid(263ed1ba-5cc1-11db-9673-00e08161165f)] interface ispecialthing : nsisupports { attribute astring name; long add(in long a, in long b); }; next is to build the .h file to compile against and the .xpt for gecko to understand your new interface. xpidl -m header ispecialthing.idl xpidl -m typelib ispecialthing.idl the code add the main code, the real work horse. cspecialthing.h #ifndef __specialthing_impl_h__ #define __specialthing_impl_h__ #include "ispecialthing.h" #include "nsstringapi.h" #define specialthing_contractid "@starkravingfinkle.org/specialthing;1" #define specialthing_classname "specialthing" #define specialthing_cid { 0x245626, 0x5cc1, 0x11db, { 0x96, 0x73, 0x0, 0xe0, 0x81, 0x61, 0x16, 0x5f } }...
...And 2 more matches
Detailed XPCOM hashtable guide
ctures, etc.) nsthashtable<...> pldhash the pldhash implementation is a fairly low-level implementation, written in c. it is extremely flexible, but requires some time to understand and use. a basic guide is included here, but you should read most of xpcom/glue/pldhash.h if you intend to use pldhash. the c++ wrappers for pldhash (see below) are often much easier and safer to use in c++ code, as many potential casting errors are easily avoided. you must declare an entry struct type, deriving from pldhashentryhdr. this entry struct should contain whatever data you wish to store in the hashtable (any pointer or fixed-length data type). note: because of the double-hashing implementation, entries may move in memory when the hashtable is altered. if you need entry pointers to remain cons...
...main constant, you may want to consider using plhashtable instead. you must also initialize a pldhashtableops structure. this serves similarly to a vtable in c++, with pointers to appropriate user-defined functions that initialize, compare, and match entries. because pldhash does not know what datatype your key is, all functions that work with keys are declared using const void*, and your client code must cast these pointers to the appropriate type. pldhashtables can be allocated on the stack or the heap: when allocated on the stack, or as a c++ class member, the table must be initialized using pl_dhashtableinit, and finalized using pl_dhashtablefinish; when allocated on the heap, use pl_newdhashtable and pl_dhashtabledestroy to allocate and delete the table. plhashtable plhashtable i...
...imple key type to a simple data type, they are generally a better choice. nsbasehashtable and friends: nsdatahashtable, nsinterfacehashtable, and nsclasshashtable these c++ templates provide a high-level interface for using hashtables that hides most of the complexities of pldhash. they provide the following features: hashtable operations can be completed without using an entry class, making code easier to read; optional thread-safety: the hashtable can manage a read-write lock around the table; predefined key classes provide automatic cleanup of strings/interfaces nsinterfacehashtable and nsclasshashtable automatically release/delete objects to avoid leaks. nsbasehashtable is not used directly; choose one of the three derivative classes based on the data type you want to store. the ...
...And 2 more matches
Components object
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. warning: this object is only intended for code running with chrome privileges. exposing the object to regular web code was a mistake. if you use this object on your web page, your site might break at any time! in current versions of firefox only a few interfaces required for compatibility are still accessible. don't use components! the components object is the object through which xpconnect functionality is reflected into javascript. the components object is actually a native instance of the nsixpcc...
...ject has the following members: classes array of classes by contractid classesbyid array of classes by cid constructor constructor for constructor of components exception constructor for xpconnect exceptions id constructor for xpcom nsids interfaces array of interfaces by interface name interfacesbyid array of interfaces by iid issuccesscode function to determine if a given result code is a success code lastresult result code of most recent xpconnect call manager the global xpcom component manager results array of known result codes by name returncode pending result for current call stack current javascript call stack utils provides access to several useful features ...
...ending result for current call stack current javascript call stack utils provides access to several useful features utils.atline provides access to the value of the atline property in the javascript environment. utils.createobjectin creates a new object in the scope of the specified object's compartment. may only be called from javascript code. utils.evalinsandbox runs javascript code in a sandbox, usually used to run code with restricted privileges. utils.forcegc forces a garbage collection cycle. utils.getglobalforobject returns the global object with which a given object is associated (through its prototype chain at birth, for example). utils.getweakreference gets a ...
...And 2 more matches
Observer Notifications
serverservice. application startup these are the topics that you can observe on startup, in order of appearance. if your component requires access to the user profile, or any services which require access to the profile (preferences, bookmarks, and so on) then a common pattern is to register with the nsicategorymanager for the app-startup topic which can be done in the component's registration code, and then in that notification register with the observer service for the profile-after-change notification. see receiving startup notifications for more information about how this works. starting in firefox 3.5 components can simply register for the profile-after-change notification in nsicategorymanager. topic description * everything. [nsobserverservice.cpp] ...
...p-finished sent when the browser window and all its components have been loaded and initialized. documents these topics indicate notifications you can monitor related to dom documents. topic subject data description chrome-document-global-created nsidomwindow null sent immediately after a chrome document window has been set up, but before any script code has been executed. this lets extensions inject api into chrome windows as needed (see nsidomglobalpropertyinitializer for an alternative method of doing this, which uses significantly less memory). data is intentionally left blank. content-document-global-created nsidomwindow origin sent immediately after a web content document window has been set up, but before any script c...
...ingcontext children and jswindowactors. additionally, it will have been removed from any windowcontext tree it was part of. io notifications these topics can be used to watch the io service for useful information. topic description offline-requested called to query whether the application can go offline. the attempt to go offline can be canceled. note: if your code chooses to cancel the attempt to go offline, it must notify the user. network:offline-about-to-go-offline called just before all network io is taken offline. network:offline-status-changed called when the offline state has changed. note: the data value for this notification 'offline' or 'online' to indicate the new state. network:link-status-changed ...
...And 2 more matches
imgILoader
bird 8.0 / seamonkey 2.5) implemented by @mozilla.org/image/loader;1 as a service: var imgiloader = components.classes["@mozilla.org/image/loader;1"] .getservice(components.interfaces.imgiloader); method overview imgirequest loadimage(in nsiuri auri, in nsiuri ainitialdocumenturl, in nsiuri areferreruri, in nsiprincipal aloadingprincipal, in nsiloadgroup aloadgroup, in imgidecoderobserver aobserver, in nsisupports acx, in nsloadflags aloadflags, in nsisupports cachekey, in imgirequest arequest, in nsichannelpolicy channelpolicy); imgirequest loadimagewithchannel(in nsichannel achannel, in imgidecoderobserver aobserver, in nsisupports cx, out nsistreamlistener alistener); boolean supportimagewithmimetype(in string mimetype); constants constant value description ...
...quest, in nsichannelpolicy channelpolicy); imgirequest loadimagewithchannel(in nsichannel achannel, in imgidecoderobserver aobserver, in nsisupports cx, out nsistreamlistener alistener); boolean supportimagewithmimetype(in string mimetype); constants constant value description load_cors_anonymous 1 << 16 load_cors_use_credentials 1 << 17 methods loadimage() start the load and decode of an image. imgirequest loadimage( in nsiuri auri, in nsiuri ainitialdocumenturl, in nsiuri areferreruri, in nsiprincipal aloadingprincipal, in nsiloadgroup aloadgroup, in imgidecoderobserver aobserver, in nsisupports acx, in nsloadflags aloadflags, in nsisupports cachekey, in imgirequest arequest, in nsichannelpolicy channelpolicy ); parameters auri the uri to load. aini...
...lags for the request. cachekey arequest a newly created, unused imgirequest object or null for one to be created for you. libpr0n does not keep a strong ref to the observer; this prevents reference cycles. this means that callers of loadimage should make sure to cancel() the resulting request before the observer goes away. ...
...And 2 more matches
nsIAppShellService
boolean createstartupstate(in long awindowwidth, in long awindowheight); obsolete since gecko 1.8 nsixulwindow createtoplevelwindow(in nsixulwindow aparent, in nsiuri aurl, in pruint32 achromemask, in long ainitialwidth, in long ainitialheight, in nsiappshell aappshell); nsiwebnav createwindowlessbrowser (in bool aischrome) void destroyhiddenwindow(); ...
... void hidesplashscreen(); obsolete since gecko 1.8 void initialize(in nsicmdlineservice acmdlineservice, in nsisupports nativeappsupportorsplashscreen); obsolete since gecko 1.8 void quit(in pruint32 aferocity); obsolete since gecko 1.8 void registertoplevelwindow(in nsixulwindow awindow); void run(); obsolete since gecko 1.8 void topleve...
...ws, then quit if successful. obsolete since gecko 1.8 eforcequit 3 force all windows to close, then quit. obsolete since gecko 1.8 methods closetoplevelwindow() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) close a window. void closetoplevelwindow( in nsixulwindow awindow ); parameters awindow a window. native code only!createhiddenwindow creates a hidden window. void createhiddenwindow( in nsiappshell aappshell ); parameters aappshell a widget "appshell" (event processor) to associate with the new window. createstartupstate() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) creates the initial state of the application by launching tasks specfi...
...And 2 more matches
nsIDOMEvent
thunderbird 16.0 / seamonkey 2.13) note: as of gecko 16.0, the nsiprivatedomevent interface was merged into this interface. everything marked as gecko 16.0 was previously available in that interface. see bug 761613. ...
...if the event can bubble the value is true, else the value is false. read only. cancelab...
...if the event can bubble the value is true, else the value is false. read only. cancelable boolean used to indicate whether or not an event can have...
...And 2 more matches
nsIDragService
widget/nsidragservice.idlscriptable implements the drag service for handling drag and drop operations. inherits from: nsisupports last changed in gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40) note: using this interface directly from add-on code is deprecated. add-ons should use the standard datatransfer drag and drop api instead. the only exception is getcurrentsession(), since there's currently no way to check for a drag in progress using standard dom methods or properties. ...
...interface directly from add-on code is deprecated. add-ons should use the standard datatransfer drag and drop api instead. the only exception is getcurrentsession(), since there's currently no way to check for a drag in progress using standard dom methods or properties. ...
...urrently no way to check for a drag in progress using standard dom methods or properties. ...
...And 2 more matches
nsIEditor
node leftnode, in nsidomnode rightnode, in nsidomnode parent); void deletenode(in nsidomnode child); void marknodedirty(in nsidomnode node); direction controller void switchtextdirection(); output methods astring outputtostring(in astring formattype, in unsigned long flags); example: // flags are declared in base/public/nsidocumentencoder.idl // outputselectiononly = 1, outputformatted = 2, // outputraw = 4, outputbodyonly = 8, // outputpreformatted = 16, outputwrap = 32, // outputformatflowed = 64, outputabsolutelinks = 258, // outputencodew3centities = 256, outputcrlinebreak = 512, // outputlflinebreak = 1024, outputnoscriptcontent = 2048, // outputnoframescontent = 4096, ou...
...// tag name are in lower case with <br>. editorapi.outputtostring('text/html', 8); // xml: all in xml with _moz_dirty="" in n...
...// tag name are in lower case with <br>. editorapi.outputtostring('text/html', 8); // xml: all in xml with _moz_dirty="" in new tags, html tags are in upper c...
...And 2 more matches
nsIFrameLoader
entview interface to manage frames across processes if electrolysis is in use to support per-frame processes. ...
...o manage frames across processes if electrolysis is in use to support per-frame processes. ...
...this can be used to decide what operations may or may not be allowed on the loader's docshell. read only. ...
...And 2 more matches
nsISecurityCheckedComponent
caps/idl/nsisecuritycheckedcomponent.idlscriptable provides methods that let an xpcom component define custom rules for accessing it from potentially unprivileged code. inherits from: nsisupports last changed in gecko 1.7 capability strings in gecko, a "capability" is a string identifying a set of actions that code is allowed to perform. two examples: code that has the "universalxpconnect" capability is allowed to access all of xpcom. this includes creating instances of arbitrary xpcom objects and calling methods and setting properties on them. ...
... standard web pages have no special capabilities. ...
.... two examples: code that has the "universalxpconnect" capability is allowed to access all of xpcom. this includes creating instances of arbitrary xpcom objects and calling methods and setting properties on them. code that has the "universalbrowserread" capability is allowed to perform certain actions that allow it to read information from the local system. for example, this capability allows code to set the value of <input type="file"> and access an arbitrary file on disk. standard web pages have no special capabilities. extensions can define their own capabilities and use this interface to only allow access to code trusted with that capability. the two special return values of '"allaccess" or "noaccess" unconditionally allow or deny access to the operation. ...
...And 2 more matches
nsISelectionController
content/base/public/nsiselectioncontroller.idlscriptable please add a summary to this article. ...
... content/base/public/nsiselectioncontroller.idlscriptable please add a summary to this article. ...
...this is still true when the caret is enabled, visible, but in its "off" blink cycle. read only. constants selection co...
...And 2 more matches
nsITraceableChannel
. to xmlhttprequest or to the browser tab that made the request) with your own implementation (see "implementing nsistreamlistener" below). after that your nsistreamlistener implementation will get the response data and will be able to pass the data on to the original nsistreamlistener (possibly modifying it). see nsitraceablechannel, intercept http traffic for a more detailed description with code samples. see modify url before loading page in firefox for an overview of how to modify a request before it is made. method overview nsistreamlistener setnewlistener(in nsistreamlistener alistener); methods setnewlistener() replaces the channel's current listener with a new one, returning the listener previously assigned to the channel. nsistreamlistener setnewlistener( i...
...'@mozilla.org/binaryoutputstream;1', 'nsibinaryoutputstream', 'setoutputstream'); var storagestream = cc('@mozilla.org/storagestream;1', 'nsistoragestream', 'init'); function tracinglistener() { this.receivedchunks = []; // array for incoming data. ...
... as they come. ...
...And 2 more matches
nsITreeView
to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false when the orientation is not drop_on. note: drop_on will only be passed to candrop() if the item is a container; see iscontainer(). boolean candrop( in long index, in long orientation, in nsidomdatatransfer datatransfe...
...constants. datatransfer this parameter, added in gecko 1.9.2, provides the data being dragged, so that it can be examined to determine if a drop is possible. return value true if a drop is allowed at the current location; otherwise false. candropbeforeafter() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method used by the drag feedback code to determine if a drag is allowable at the current location. to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false from candropbeforeafter(). boolean candropbeforeafter( in long index, in boolean before ); parameters index the index of the item. before true to test drop before. false to test drop after. return value true i...
...foreafter(). boolean candropbeforeafter( in long index, in boolean before ); parameters index the index of the item. before true to test drop before. false to test drop after. return value true if a drop event can occur. otherwise false. candropon() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method used by the drag feedback code to determine if a drag is allowable at the current location. to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false from candropbeforeafter(). boolean candropon( in long index ); parameters index the index of the item. return value true if a drop event can occur. otherwise false. cyclecell() called on the view when a cell in ...
...And 2 more matches
nsIUTF8ConverterService
intl/uconv/idl/nsiutf8converterservice.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview autf8string convertstringtoutf8(in acstring astring, in string acharset, in boolean askipcheck); autf8string converturispectoutf8(in acstring aspec, in string acharset); methods convertstringtoutf8() ensure that astring is encoded in utf-8. if not, convert to utf-8 assuming it's encoded in acharset and return the converted string in utf-8. autf8string convertstringtoutf8( in acstring astring, in string acharset, in boolean askipcheck, in boolean aallowsubstitution ); parameters astring a string to ensure its utf8ness. acharset the charset to convert from if astring is not in utf-8. ...
...spect that astring can be mistaken for ascii / utf-8 but is actually not in ascii / utf-8 so that astring has to go through the conversion. skipping asciiness/utf8ness check. the most common case is the input is in 7bit non-ascii character sets like iso-2022-jp, hz or utf-7 (in its original form or a modified form used in imap folder names). aallowsubstitution when true, allow the decoder to substitute invalid input sequences by replacement characters. return value the converted string in utf-8. exceptions thrown ns_error_uconv_noconv when there is no decoder for acharset or error code of nsiunicodedecoder in case of conversion failure. converturispectoutf8() ensure that aspec (after url-unescaping it) is encoded in utf-8. if not, convert it to utf-8, assuming it'...
... substitute invalid input sequences by replacement characters. return value the converted string in utf-8. exceptions thrown ns_error_uconv_noconv when there is no decoder for acharset or error code of nsiunicodedecoder in case of conversion failure. converturispectoutf8() ensure that aspec (after url-unescaping it) is encoded in utf-8. if not, convert it to utf-8, assuming it's encoded in acharset, and return the result. ...
...And 2 more matches
Storage
ent.bindparameters() will ensure that the parameters are bound before execution. you can then execute the statement asynchronously, and the statement will get each set of bindings bound to it before execution asynchronously. executing a statement you may execute statements either synchronously (which is supported in firefox gecko 1.8 and 1.9) or asynchronously (starting in gecko 1.9.1). if your code needs to work with applications based on gecko 1.8 or 1.9, you should the technique covered in the section synchronously below. otherwise, it's strongly recommended that you use asynchronous execution, for performance reasons. asynchronously gecko 1.9.1 introduced support for asynchronous execution of a statement by calling mozistoragestatement.executeasync() on the statement. multiple statem...
...teasync() on the statement. multiple statements can be executed in a transaction by calling mozistorageconnection.executeasync() on the connection and passing in an array of statements. both of these methods have similar signatures that accept an object as input that receives notifications the execution of the statement(s). a c++ example is omitted here because it would be verbose, but real-world code can be found in the mozilla source tree (mxr id search for mozistoragestatementcallback). after you create and bind a statement, your javascript should look something like this to execute a statement asynchronously: statement.executeasync({ handleresult: function(aresultset) { for (let row = aresultset.getnextrow(); row; row = aresultset.getnextrow()) { let value ...
...oduced by the statement. as you step through each row, you can obtain each parameter by name through a helper object (mozistoragestatementrow) in javascript ( ) like so: while (statement.executestep()) { let value = statement.row.column_name; } you can create this helper object yourself if it's not available in your version of gecko. see mozistoragestatementwrapper for details. in c++, the code would look something like this: bool hasmoredata; while (ns_succeeded(statement->executestep(&hasmoredata)) && hasmoredata) { print32 value; rv = statement->getint32(0, &value); ns_ensure_success(rv, rv); } you can obtain other types of data by using the various methods available on mozistoragevaluearray. alternatively, if you do not expect any results but still need to execute a bound ...
...And 2 more matches
XPCOM
ar to microsoft’s com technology. xpcom components can be implemented in c, c++, and javascript, and can be used from c, c++, and javascript. that means you can call javascript methods from c++ and vice versa. for more information on the workings of xpcom look elsewhere.how to pass an xpcom object to a new windowif you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method.interfacing with the xpcom cycle collectorthis is a quick overview of the cycle collector introduced into xpcom for firefox 3, including a description of the steps involved in modifying an existing c++ class to participate in xpcom cycle collection. if you have a class that you think is involved in a...
...this guide provides some explanation and advice on how to choose between them.observer notificationsthe following are topics that you can observe during the course of an application. unless otherwise noted you register for...
... xpcom objects from that language, and to let modules written in that language be used as xpcom objects by all other languages for which there are xpcom bindings.monitoring http activitygecko includes the nsihttpactivityobserver interface, which you can implement in your code to monitor http transactions in real time, receiving a callback as the transactions take place.nscomptr versus refptrgecko code uses both nscomptr and refptr as smart pointers. this guide provides some explanation and advice on how to choose between them.observer notificationsthe following are topics that you can observe during the course of an application. unless otherwise noted you register for the topics using the nsiobserverservice.setting http request headershttp is one of the core technologies behind the web. in add...
...And 2 more matches
XPIDL Syntax
Mozilla › Tech › XPIDL › Syntax
purpose of this document this document is not an introduction to xpidl or idl in general. it is more focused on xpidl syntax and grammar. see xpidl main page for more links and introductory content. simplifications, conventions and notation the syntax is specified according to abnf as defined by rfc 5234, although a few productions use prose for clarity of understanding. ...
...line, and not carriage returns (although xpidl begs to differ). additionally, the use of both c-style (/* ... */) and c++-style (// ... end-of-line) comments are permitted between any two tokens. some productions can only occur at the beginning of lines; to simplify the grammar, i will not mention them in the grammar, especially since they are handled as a preprocessing step before the idl source code is actually parsed. a `%{' that appears at the beginning of a line is the start of a raw code fragment, which extends until the end of a line that begins with `%}'. text inside raw code fragments are not otherwise parsed by xpidl directly. this may be followed by the language, as in `%{c++', to output the raw fragment only in the specified language. a `#include "file"' line instructs the xpidl...
...unlike the c preprocessor, when a file is included multiple times, it acts as if the subsequent includes did not happen; this prevents the need for include guards. xpidl syntax (abnf) the root production here is idl_file. ...
...And 2 more matches
Plug-in Development Overview - Plugins
re to provide and how it will interact with the browser and the special media for which the plug-in is created. decide the mime type for the plug-in (see registering plug-ins). set up your development environment properly. you can use a variety of environments to create a plug-in, but make sure that you have the necessary files from the plugin sdk. create a plug-in project. write your plug-in code and implement the appropriate plug-in api methods for basic plug-in operation. you'll find an overview of the plug-in api methods in this chapter, as well as separate chapters for all of the major functional areas of the plug-in api. also see making plug-ins scriptable for more information about making plug-ins accessible from the browser. build the plug-in for your operating system. see "buildi...
... for description language: for language in use in the mime types and file extensions strings, multiple values are separated by the "|" character, for example: video/quicktime|audio/aiff|image/jpeg the version stamp will be loaded only if it has been created with the language set to "us english" and the character set to "windows multilingual" in your development environment. the resource code for this language and character set combination is 040904e4. unix on unix, plug-ins are found according to the section how gecko finds plug-ins. to determine the mime types and file extensions that the plug-in handles, the browser loads each library and calls into the np_getmimedescription entry point. this exported c function should return a string containing the type, extension list, and typ...
..._posturl, except that it notifies the plug-in of the result when the operation completes. for information about using these methods, see urls. starting in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), you can get the origin of the document in a secure, convenient way by calling npn_getvalue() to retrieve the value of the variable npnvdocumentorigin. the returned value is the unicode serialization of the document's origin converted to nfkc-encoded (that is, normalized) utf-8. your plug-in must free the returned string's memory by calling npn_memfree() when you're done with it. getting version and ui information the netscape group of plug-in api methods provides some basic services to the plug-in. you can use these netscape methods: to identify the browser in which your p...
...And 2 more matches
Debugging service workers - Firefox Developer Tools
owing output shown: this gives you some advice on what to do if you don't have a service worker registered, and were perhaps expecting there to be one registered! let's start by troubleshooting this. getting your service worker to register before you can look at your service worker in action in the applications panel, you need to successfully register it. registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, for example, you'll get an error in the web console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code. if this i...
...ster('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, for example, you'll get an error in the web console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code. if this is not enough to help you figure out the problem, you could also try going to the javascript debugger and stepping through your code to pinpoint exactly where it is going wrong. debugging your service worker in any case, when the service worker is successfully registered, you'll see information about it displayed in the application > service workers view (along with any other service workers registered on the same domain): this gives you a variety of information about your service worker: the url that the service worke...
... are no more such pages still loaded, the new service worker activates. debug important: the debug button is currently enabled only in firefox nightly. when your service worker is running, a debug button is available next to the source information (it is disabled when the service worker is stopped). when pressed, this takes you straight to the javascript debugger view of your service worker code, and you can use the full power of the debugger to debug it — stepping through code, etc. testing a service worker cache if you are using your service worker to store your site assets in cache storage (using the cache api), which is essential for creating offline apps, it can be annoying to test the cache. when you fill up the cache with assets, but then want to alter the behavior slightly,...
...And 2 more matches
Call Tree - Firefox Developer Tools
statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it. ...
...statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it. in this article, we'll use the output of a simple program as an example. ...
... // 190 -> swap() // 1 -> quicksort() // 103 -> partition() // 12 platform data you'll also see some rows labeled gecko, input & events, and so on. these represent internal browser calls. this can be useful information too. ...
...And 2 more matches
Intensive JavaScript - Firefox Developer Tools
an a javascript function, or series of functions, that blocked the main thread for 71.73ms, or more than four times our frame budget. which function, though? by switching to the flame chart view we can find out: this shows us the js call stack at this point in the execution. at the top of the stack is a function called calculateprimes(), and we can see its filename and line number. ...
...ss animation, and each function is short enough that the browser can handle it without the overall frame rate dropping. using requestanimationframe worked to solve the responsiveness problem here, but there are a couple of potential problems with it: it can be difficult to split up a long-running function into separate self-contained functions. even this very simple case produced more complex code. the split-up version takes much longer to run. in fact we can be quite precise about how long it takes: there are 50 iterations, and the browser is producing about 60 frames per second. so it will take almost a second to run all the computations, and that's visible in both the user experience and in the profile. using web workers in this version we'll try to fix the problem using a web worke...
...lmost a second to run all the computations, and that's visible in both the user experience and in the profile. using web workers in this version we'll try to fix the problem using a web worker. web workers enable you to run javascript in a separate thread. the main thread and the worker thread can't call each other directly, but communicate using an asynchronous messaging api. ...
...And 2 more matches
BasicCardResponse - Web APIs
details such as the number/expiry date of the card used to make the payment, and the billing address. properties basiccardresponse.cardnumber read only secure context contains the number of the card used to make the payment. basiccardresponse.cardholdername read only secure context optional contains the cardholder name of the card used to make the payment. basiccardresponse.cardsecuritycode read only secure context optional contains the security code of the card used to make the payment. basiccardresponse.expirymonth read only secure context optional contains the expiry month of the card used to make the payment. basiccardresponse.expiryyear read only secure context optional contains the expiry year of the card used to make the payment. basiccardresponse.billingaddress read...
...s successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr. dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'basiccardresponse' in that specification. working draft initial definition. browser compatibility the compatibil...
...to change preferences in firefox, visit about:config.ie no support noopera no support nosafari ? webview android no support nochrome android ...
...And 2 more matches
Manipulating video using canvas - Web APIs
the document content the html document used to render this content is shown below. ...
...body> </html> the key bits to take away from this are: this document establishes two canvas elements, with the ids c1 and c2. canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. ...
...ument establishes two canvas elements, with the ids c1 and c2. canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chroma-keying effect; c2 is preloaded with the still image that will be used to replace the green background in the video. the javascript code is imported from a script named processor.js. the javascript code the javascript code in processor.js consists of three methods. initializing the chroma-key player the doload() method is called when the xhtml document initially loads. this method's job is to prepare the variables needed by the chroma-key processing code, and to set up an event listener so we can detect when the user starts playing the video. var processor; processor.doload = function ...
...And 2 more matches
Drawing shapes with canvas - Web APIs
. this method tries to close the shape by drawing a straight line from the current point to the start. if the shape has already been closed or there's only one point in the list, this function does nothing. note: when you call fill(), any open shapes are closed automatically, so you don't have to call closepath(). this is not the case when you call stroke(). ...
...of paper and placing it on the next. moveto(x, y) moves the pen to the coordinates specified by x and y. when the canvas is initialized or beginpath() is called, you typically will want to use the moveto() function to place the starting point somewhere else. we could also use moveto() to draw unconnected paths. take a look at the smiley face below. to try this for yourself, you can use the code snippet below. just paste it into the draw() function we saw earlier. <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(75, 75, 50, 0, math.pi * 2, true); // outer circ...
...ees. to convert degrees to radians you can use the following javascript expression: radians = (math.pi/180)*degrees. the following example is a little more 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 pa...
...And 2 more matches
Drawing text - Web APIs
e, alphabetic, ideographic, bottom. the default value is alphabetic. direction = value directionality. possible values: ltr, rtl, inherit. the default value is inherit. these properties might be familiar to you, if you have worked with css before. the following diagram from the whatwg demonstrates the various baselines supported by the textbaseline property. ...
...rit. these properties might be familiar to you, if you have worked with css before. the following diagram from the whatwg demonstrates the various baselines supported by the textbaseline property. ...
...e below and see your changes update live in the canvas: ctx.font = '48px serif'; ctx.textbaseline = 'hanging'; ctx.stroketext('hello world', 0, 100); playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.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...
...And 2 more matches
Using images - Web APIs
external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. it's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind. embedding an image via data: url another possible way to include images is via the data: url. data urls allow you to completely define an image as a base64 encoded string of characters directly in your code. var img = new image(); // create new img element img.src = 'data:image/gif;base64,r0lgodlhcwalaiaaaaaa3pn/zih5baeaaaealaaaaaalaasaaaiuha+hkcuo4lmnvindo7qyrixigbyaow=='; one advantage of data urls is that the resulting image is available immediately without another round trip to the server. another potential advantage is that it is also possible to...
...='; one advantage of data urls is that the resulting image is available immediately without another round trip to the server. another potential advantage is that it is also possible to encapsulate in one file all of your css, javascript, html, and images, making it more portable to other locations. some disadvantages of this method are that your image is not cached, and for larger images the encoded url can become quite long. using frames from a video you can also use frames from a video being presented by a <video> element (even if the video is not visible). for example, if you have a <video> element with the id "myvideo", you can do this: function getmyvideo() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); retu...
...mage(image, x, y) draws the canvasimagesource specified by the image parameter at the coordinates (x, y). svg images must specify a width and height in the root <svg> element. example: a simple line graph in the following example, we will use an external image as the backdrop for a small line graph. using backdrops can make your script considerably smaller because we can avoid the need for code to generate the background. in this example, we're only using one image, so i use the image object's load event handler to execute the drawing statements. the drawimage() method places the backdrop at the coordinate (0, 0), which is the top-left corner of the canvas. <html> <body onload="draw();"> <canvas id="canvas" width="180" height="150"></canvas> </body> </html> function draw() { ...
...And 2 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
he content tree difficult in unexpected ways, depending on where it is located. this article explores when difficulties can occur, and looks at what can be done to mitigate resulting problems. what is whitespace? whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, crlf sequences, carriage returns or line feeds). these characters allow you to format your code in a way that will make it easily readable by yourself and other people. in fact, much of our source code is full of these whitespace characters, and we only tend to get rid of it in a production build step to reduce code download sizes. html largely ignores whitespace? in the case of html, whitespace is largely ignored — whitespace in between words is treated as a single character, and white...
...n a production build step to reduce code download sizes. html largely ignores whitespace? in the case of html, whitespace is largely ignored — whitespace in between words is treated as a single character, and whitespace at the start and end of elements and outside elements is ignored. take the following minimal example: <!doctype html> <h1> hello world! </h1> this source code contains a couple of line feeds after the doctype and a bunch of space characters before, after, and inside the <h1> element, but the browser doesn’t seem to care at all and just shows the words "hello world!" as if these characters didn’t exist at all: this is so that whitespace characters don't impact the layout of your page. creating space around and inside elements is the job of css. ...
... blocks we now have are not going to occupy any space in the final layout, because they don’t contain anything, so we’ll end up with only 2 blocks taking up space in the page. people viewing the web page see the words "hello" and "world!" on 2 separate lines as you’d expect 2 <div>s to be laid out. the browser engine has essentially ignored all of the whitespace that was added in the source code. spaces in between inline and inline-block elements let's move on to look at a few issues that can arise due to whitespace, and what can be done about them. first of all, we'll look at what happens with spaces in between inline and inline-block elements. in fact, we saw this already in our very first example, when we described how whitespace is processed inside inline formatting contexts. w...
...And 2 more matches
Using the Gamepad API - Web APIs
the gamepad api is a way for developers and designers to access and use gamepads and other game controllers. ...
... where developers want to make decisions for the current frame based on the state of the gamepad or gamepads. the navigator.getgamepads() method returns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will be returned if there are no gamepads connected.) this can then be used to get the same information. for example, the first code example above you be rewritten as shown below: window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.gamepad.index]; console.log("gamepad connected at index %d: %s. %d buttons, %d axes.", gp.index, gp.id, gp.buttons.length, gp.axes.length); }); the gamepad object's properties are as follows: id: a string containing some information about the...
...e scenes, this object will be updated every time the gamepad's state changes. using button information let's look at a simple example that displays connection information for one gamepad (it ignores subsequent gamepad connections) and allows you to move a ball around the screen using the four gamepad buttons on the right hand side of the gamepad. you can view the demo live, and find the source code on github. to start with, we declare some variables: the gamepadinfo paragraph that the connection info is written into, the ball that we want to move, the start variable that acts as the id for requestanimation frame, the a and b variables that act as position modifiers for moving the ball, and the shorthand variables that will be used for the requestanimationframe() and cancelanimationframe() ...
...And 2 more matches
Ajax navigation example - Web APIs
clude "include/header.php"; echo "<title>" . $page_title . ...
...ude "include/header.php"; echo "<title>" . $page_title . ...
...>second_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</body>\n</html>"; } ?> third_page.php: <?php $page_title = "third page"; $page_content = "<p>this is the content of <strong>third_page.php</strong>. this content is stored into a php variable.</p>"; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { echo json_encode(array("page" => $page_title, "content" => $page_content)); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this paragraph is shown only when the navigation starts from <strong>third_page.php</strong>.</p> <div id="ajax-content"> <?ph...
...And 2 more matches
Timing element visibility with the Intersection Observer API - Web APIs
last-child) { margin-bottom: 8px; } .ad h2 { margin-top: 0; } .ad div { position: relative; float: right; padding: 0 4px; height: 20px; width: 120px; font-size: 14px; bottom: 30px; border: 1px solid black; background-color: rgba(255, 255, 255, 0.5); } there's nothing magic in here. it's fairly basic css. tying it together with javascript that brings us to the javascript code which makes everything work. let's start with the global variables: let contentbox; let nextarticleid = 1; let visibleads = new set(); let previouslyvisibleads = null; let adobserver; let refreshintervalid = 0; these are used as follows: contentbox a reference to the <main> element's htmlelement object in the dom. this is where we'll insert the articles and ads. nextarticleid each artic...
...to minutes and seconds. this is handled by passing the ad's element into the drawadtimer() function: function drawadtimer(adbox) { let timerbox = adbox.queryselector(".timer"); let totalseconds = adbox.dataset.totalviewtime / 1000; let sec = math.floor(totalseconds % 60); let min = math.floor(totalseconds / 60); timerbox.innertext = min + ":" + sec.tostring().padstart(2, "0"); } this code finds the ad's timer using its id, "timer", and computes the number of seconds elapsed by dividing the ad's totalviewtime by 1000. then it calculates the number of minutes and seconds elapsed before setting the timer's innertext to a string representing that time in the form m:ss. the string.padstart() method is used to ensure that the number of seconds is padded out to two digits if it's less th...
... dividing the ad's totalviewtime by 1000. then it calculates the number of minutes and seconds elapsed before setting the timer's innertext to a string representing that time in the form m:ss. the string.padstart() method is used to ensure that the number of seconds is padded out to two digits if it's less than 10. building the page contents the buildcontents() function is called by the startup code to select and insert into the document the articles and ads to be presented: let loremipsum = "<p>lorem ipsum dolor sit amet, consectetur adipiscing" + " elit. cras at sem diam. vestibulum venenatis massa in tincidunt" + " egestas. morbi eu lorem vel est sodales auctor hendrerit placerat" + " risus. etiam rutrum faucibus sem, vitae mattis ipsum ullamcorper" + " eu. donec nec imperdiet ni...
...And 2 more matches
KeyboardEvent.key - Web APIs
Web › API › KeyboardEvent › key
the keyboardevent interface's key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as shift as well as the keyboard locale and layout. its value is determined as follows: key values see a full list of key values. ...
... if the key cannot be identified, the returned value is unidentified. keyboardevent sequence every keyboardevent is fired in a pre-determined sequence. ...
... if the key cannot be identified, the returned value is unidentified. ...
...And 2 more matches
Recording a media element - Web APIs
let preview = document.getelementbyid("preview"); let recording = document.getelementbyid("recording"); let startbutton = document.getelementbyid("startbutton"); let stopbutton = document.getelementbyid("stopbutton"); let downloadbutton = document...
...to its caller. stopping the input stream the stop() function simply stops the input media: function stop(stream) { stream.gettracks().foreach(track => track.stop()); } this works by calling mediastream.gettracks(), using foreach() to call mediastreamtrack.stop() on each track in the stream. ...
...ew <video> element's srcobject property is set to be the input stream, which causes the video being captured by the user's camera to be displayed in the preview box. since the <video> element is muted, the audio won't play. the "download" button's link is then set to refer to the stream as well. then, in line 8, we arrange for preview.capturestream() to call preview.mozcapturestream() so that our code will work on firefox, on which the mediarecorder.capturestream() method is prefixed. then a new promise which resolves when the preview video starts to play is created and returned. line 10 when the preview video begins to play, we know there's media to record, so we respond by calling the startrecording() function we created earlier, passing in the preview video stream (as the source media to ...
...And 2 more matches
Web-based protocol handlers - Web APIs
handler("web+burger", "http://www.google.co.uk/?uri=%s", "burger handler"); where the parameters are: the protocol. the url template, used as the handler. the "%s" is replaced with the href of the link and a get is executed on the resultant url. the user friendly name for the protocol handler. when a browser executes this code, it should display a prompt to the user, asking permission to allow the web application to register as a handler for the protocol. firefox displays a prompt in the notification bar area: note:the url template supplied when registering must be of the same domain as the webpage attempting to perform the registration or the registration will fail. for example, http://example.com/homepage.html can...
...firefox will, by default, prompt the user before handing off the action. example <!doctype html public "-//w3c//dtd html 4.01//en"> <html lang="en"> <head> <title>web ...
...firefox will, by default, prompt the user before handing off the action. example <!doctype html public "-//w3c//dtd html 4.01//en"> <html lang="en"> <head> <title>web protocol handler s...
...And 2 more matches
OfflineAudioContext.startRendering() - Web APIs
= function(e) { // e.renderedbuffer contains the output buffer } promise-based version: offlineaudioctx.startrendering().then(function(buffer) { // buffer contains the output buffer }); parameters none. returns void. example in this simple example, we declare both an audiocontext and an offlineaudiocontext object. we use the audiocontext to load an audio track via xhr (audiocontext.decodeaudiodata), then the offlineaudiocontext to render the audio into an audiobuffersourcenode and play the track through. after the offline audio graph is set up, you need to render it to an audiobuffer using offlineaudiocontext.startrendering. when the startrendering() promise resolves, rendering has completed and the output audiobuffer is returned out of the promise. at this point we create anoth...
...solves, rendering has completed and the output audiobuffer is returned out of the promise. at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. ...
... this is then played as part of a simple standard audio graph. ...
...And 2 more matches
OfflineAudioContext - Web APIs
er() or by assigning an event listener to the oneventname property of this interface: complete fired when the rendering of an offline audio context is complete. also available using the oncomplete event handler property. examples in this simple example, we declare both an audiocontext and an offlineaudiocontext object. we use the audiocontext to load an audio track via xhr (audiocontext.decodeaudiodata), then the offlineaudiocontext to render the audio into an audiobuffersourcenode and play the track through. after the offline audio graph is set up, you need to render it to an audiobuffer using offlineaudiocontext.startrendering. when the startrendering() promise resolves, rendering has completed and the output audiobuffer is returned out of the promise. at this point we create anoth...
...solves, rendering has completed and the output audiobuffer is returned out of the promise. at this point we create another audio context, create an audiobuffersourcenode inside it, and set its buffer to be equal to the promise audiobuffer. this is then played as part of a simple standard audio graph. ...
... this is then played as part of a simple standard audio graph. ...
...And 2 more matches
PaymentAddress - Web APIs
nt locality or sublocality within a city, for example, a neighborhood, borough, district, or uk dependent locality. paymentaddress.organization read only a domstring specifying the name of the organization, firm, company, or institution at the payment address. paymentaddress.phone read only a domstring specifying the telephone number of the recipient or contact person. paymentaddress.postalcode read only a domstring specifying a code used by a jurisdiction for mail routing, for example, the zip code in the united states or the pin code in india. paymentaddress.recipient read only a domstring giving the name of the recipient, purchaser, or contact person at the payment address. paymentaddress.region read only a domstring containing the top level administrative subdivision of the ...
...or example, the zip code in the united states or the pin code in india. paymentaddress.recipient read only a domstring giving the name of the recipient, purchaser, or contact person at the payment address. paymentaddress.region read only a domstring containing the top level administrative subdivision of the country, for example a state, province, oblast, or prefecture. paymentaddress.regioncode read only a domstring specifying the region of the address, represented as a "code element" of an iso3166-2 country subdivision name (e.g. "qld" for queensland, australia, "ca" for california, and so on). paymentaddress.sortingcode read only a domstring providing a postal sorting code such as is used in france. note: properties for which values were not specified contain empty strings. ...
...this identifies the language in which the address is given, and is intended to aid in localization of the display of the address. ...
...And 2 more matches
RTCOutboundRtpStreamStats.qpSum - Web APIs
the data more compressible. the quantization process and the amount of compression can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. ...
...ss and the amount of compression can be controlled using one or more parameters. it's important to keep in mind that the value of qp can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. the best you can do is make an estimate. you can use the value of rtcsentrtpstreamstats.framesencoded to get the number of frames that have been encoded so far, and compute an average from there. see calculating average quantization below for a function that does this. also, the exact meaning of the qp value depends on the codec being used. for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2. h.264 uses a qp which ranges from 0 to...
... example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcstats object that contains rtp stream statistics, returning 0 if the object doesn't describe an rtp stream. ...
...And 2 more matches
RTCOutboundRtpStreamStats - Web APIs
value indicating the average rtcp interval between two consecutive compound rtcp packets. fircount an integer value which indicates the total number of full intra request (fir) packets which this rtcrtpsender has sent to the remote rtcrtpreceiver. this is an indicator of how often the stream has lagged, requiring frames to be skipped in order to catch up. valid only for video streams. framesencoded the number of frames that have been successfully encoded so far for sending on this rtp stream. only valid for video streams. lastpacketsenttimestamp a domhighrestimestamp indicating the time at which the last packet was sent for this ssrc. the timestamp property, on the other hand, indicates the time at which the rtcoutboundrtpstreamstats object was generated. nackcount an integer value in...
...d. nackcount an integer value indicating the total number of negative acknolwedgement (nack) packets this rtcrtpsender has received from the remote rtcrtpreceiver. perdscppacketssent a record of key-value pairs with strings as the keys mapped to 32-bit integer values, each indicating the total number of packets this rtcrtpsender has transmitted for this source for each differentiated services code point (dscp). plicount an integer specifying the number of times the remote receiver has notified this rtcrtpsender that some amount of encoded video data for one or more frames has been lost, using picture loss indication (pli) packets. only available for video streams. qpsum a 64-bit value containing the sum of the qp values for every frame encoded by this rtcrtpsender. valid only for video...
...videosenderstats object containing statistics about this stream's rtcrtpsender. slicount an integer indicating the number of times this sender received a slice loss indication (sli) frame from the remote peer, indicating that one or more consecutive video macroblocks have been lost or corrupted. available only for video streams. ...
...And 2 more matches
RTCPeerConnection.createOffer() - Web APIs
the createoffer() method of the rtcpeerconnection interface initiates the creation of an sdp offer for the purpose of starting a new webrtc connection to a remote peer. the sdp offer includes information about any mediastreamtracks already attached to the webrtc session, codec, and options supported by the browser, and any candidates already gathered by the ice agent, for the purpose of being sent over the signaling channel to a potential peer to request a connection or to update the configuration of an existing connection. the return value is a promise which, when the offer has been created, is resolved with a rtcsessiondescription object containing the newly-created offer. syntax apromise = mypeerconnection.createoffer([options]); mypeerconnection.createoffer(successcallback, failurecal...
..."inactive"). in modern implementations, the presence of this member with a value true, will ensure there is at least one transceiver set to receive video that has not been stopped, and if there isn't one, one will be created. note: you shouldn't use this legacy property. instead, use rtcrtptransceiver to control whether or not to accept incoming video. voiceactivitydetection optional some codecs and hardware are able to detect when audio begins and ends by watching for "silence" (or relatively low sound levels) to occur. this reduces network bandwidth used for audio by only sending audio data when there's actually something to broadcast. however, in some cases, this is unwanted. for example, in the case of music or other non-voice transmission, this can cause loss of important low-volu...
...io by only sending audio data when there's actually something to broadcast. however, in some cases, this is unwanted. for example, in the case of music or other non-voice transmission, this can cause loss of important low-volume sounds. also, emergency calls should never cut audio when quiet. this option defaults to true (voice activity detection enabled). deprecated parameters in older code and documentation, you may see a callback-based version of this function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of createoffer() instead. the parameters for this form of createoffer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which will ...
...And 2 more matches
RTCRtpCapabilities - Web APIs
the rtcrtpcapabilities dictionary is a data type used to describe the capabilities of an rtcrtpsender or rtcrtpreceiver in response to a call to the rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities() static functions, both of which return an array of rtcrtpcapabilities objects. an rtcrtpcapabilities object contains an array of objects conforming to rtcrtpcodeccapability (each describing the capabilities of one codec) and an array of the supported rtp header extensions for that codec. properties codecs an array of rtcrtpcodeccapability objects, each describing one of the codecs supported by the rtcrtpsender or rtcrtpreceiver. there are some special entries in this array, described below in the section the codecs array. headerextensions an array of objects conforming to ...
...its properties are: the browser will only report distinct capability combinations separately. if two sets of capabilities can be described as one, they will be. ...
...s supported by the rtcrtpsender or rtcrtpreceiver. there are some special entries in this array, described below in the section the codecs array. headerextensions an array of objects conforming to the rtcrtpheaderextensioncapability dictionary. each object contains a single domstring, uri, specifying the uri of the header extension, as described in rfc 5285. description the codecs array the codecs array is an array of objects conforming to the dictionary rtcrtpcodeccapability. each of these objects describes a single codec and its basic capabilities. its properties are: the browser will only report distinct capability combinations separately. ...
...And 2 more matches
Boilerplate 1 - Web APIs
specifically, the html has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. ...
... specifically, the html has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. ...
... specifically, the html has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. the css contains rules for body, canvas, and button. any additional non-trivial css and html will be displayed on the pages of specific examples. ...
...And 2 more matches
Animating textures in WebGL - Web APIs
« previous in this demonstration, we build upon the previous example by replacing our static textures with the frames of an mp4 video file that's playing. this is actually pretty easy to do and fun to watch, so let's get started. you can use similar code to use any sort of data (such as a <canvas>) as the source for your textures. 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>. getting access to the video the first step is to create the <video> element that we'll use to retrieve the video frames: // will set to true when video can be copied to texture var copyvideo = false; function setupvideo(url) { const video = ...
...to autoplay, mute the sound, and loop the video. we then set up two events to make sure the video is playing and the time has been updated. we need both of these checks because it will produce an error if you upload a video to webgl that has no data available yet. checking for both of these events guarantees there is data available and it's safe to start uploading video to a webgl texture. in the code above, we confirm whether we got both of those events; if so, we set a global variable, copyvideo, to true to indicate that it's safe to start copying the video to a texture. and finally, we set the src attribute to start and call play to start loading and playing the video. the video must be loaded from a secure source in order to be used to provide texture data to webgl. that means that you'l...
... we got both of those events; if so, we set a global variable, copyvideo, to true to indicate that it's safe to start copying the video to a texture. and finally, we set the src attribute to start and call play to start loading and playing the video. the video must be loaded from a secure source in order to be used to provide texture data to webgl. that means that you'll not only need to deploy code like using a secure web server, but you'll need a secure server to test with as well. see how do you set up a local testing server? for help. using the video frames as a texture the next change is to inittexture(), which becomes much simpler, since it no longer needs to load an image file. instead, all it does is create an empty texture object, put a single pixel in it, and set its filtering fo...
...And 2 more matches
Using shaders to apply color in WebGL - Web APIs
our sample loads a copy from a cdn in our html's <head>. ...
...e to each pixel, the entire square was rendered as solid white. let's say we want to render a gradient in which each corner of the square is a different color: red, blue, green, and white. the first thing to do is to establish these colors for the four vertices. to do this, we first need to create an array of vertex colors, then store it into a webgl buffer. we'll do that by adding the following code to our initbuffers() function: function initbuffers(){ ... const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.static_dr...
...then a new webgl buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer. to use these colors, the vertex shader needs to be updated to pull the appropriate color from the color buffer: const vssource = ` attribute vec4 avertexposition; ...
...And 2 more matches
Geometry and reference spaces in WebXR - Web APIs
tances webgl measures all distances and lengths in meters. webxr inherits this standard, as well as the fact that the world is a cube two meters wide, two meters tall, and two meters deep. each of the three axes has a minimum value of -1.0 and a maximum of 1.0, with the center of the cube located at (0, 0, 0). this two cubic meter space encompasses the entire universe for the purposes of your code. everything you draw must have its coordinates mapped to fit into this space, either explicitly within your code, or by using a transform to adjust the coordinates of all vertices. the most efficient way, of course, is to design your objects and code to use the same coordinate system as webgl does. the webgl coordinates and lengths are transformed automatically at render time to the size of the ...
... most efficient way, of course, is to design your objects and code to use the same coordinate system as webgl does. the webgl coordinates and lengths are transformed automatically at render time to the size of the viewport in which the scene is being rendered. angles angles are specified using radians. to convert degrees to radians, simply multiply the value in degrees by π/180. the following code snippet shows two simple functions, degreestoradians() and radianstodegrees(), which convert back and forth between the two units for measuring angles. const radians_per_degree = math.pi / 180.0; let degreestoradians = (deg) => deg * radians_per_degree; let radianstodegrees = (rad) => rad / radians_per_degree; times and durations note that for security reasons, domhighrestimestamp usually in...
...the position and facing direction of the space relative to the world space, if the space represents a viewer such as the user's headset, an observer's headset, or a virtual camera. all of this is the browser's responsibility to handle, providing consistent behavior regardless of how capable each of the underlying reference spaces are. no matter how powerful or simple the individual xr device is, code written using webxr will still work, within the limitations of the available hardware. regardless of the type of reference space you choose, its type is xrreferencespace or is a type derived from xrreferencespace. the currently available reference space types, which are defined by the xrreferencespacetype enumeration, are shown below. the reference space returned by xrsession.requestreferencesp...
...And 2 more matches
Using the Web Animations API - Web APIs
i one of the more familiar ways to approach learning the web animations api is to start with something most web developers have played with before: css animations. css animations have a familiar syntax that breaks down nicely for demonstration purposes. the css version here’s a tumbling animation written in css showing alice falling down the rabbit hole that leads to wonderland (see the full code on codepen): notice that the background moves, alice spins, and her color changes at an offset from her spinning. we’re going to focus on just alice for this tutorial. here’s the simplified css that controls alice’s animation: #alice { animation: alicetumbling infinite 3s linear; } @keyframes alicetumbling { 0% { color: #000; transform: rotate(0) translate3d(-50%, -50%, 0);...
...ations where the default animation-timing-function is ease, in the web animations api the default easing is linear — which is what we want here. bring the pieces together now it’s time to bring them both together with the element.animate() method: document.getelementbyid("alice").animate( alicetumbling, alicetiming ) and boom: the animation starts playing (see the finished version on codepen). the animate() method can be called on any dom element that could be animated with css. and it can be written in several ways. instead of making objects for keyframes and timing properties, we could just pass their values in directly, like so: document.getelementbyid("alice").animate( [ { transform: 'rotate(0) translate3d(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offse...
...ayback with play(), pause(), reverse(), and updateplaybackrate() while we can write css animations with the web animations api, where the api really comes in handy is manipulating the animation’s playback. the web animations api provides several useful methods for controlling playback. let’s take a look at pausing and playing animations in the growing/shrinking alice game (check out the full code on codepen): in this game, alice has an animation that causes her to go from small to big which we control via a bottle and a cupcake. both of these have their own animations. pausing and playing animations we’ll talk more about alice’s animation later, but for now, let’s look closer at the cupcake’s animation: var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ ...
...And 2 more matches
Visualizations with Web Audio API - Web APIs
one of the most interesting features of the web audio api is the ability to extract frequency, waveform, and other data from your audio source, which can then be used to create visualizations. this article explains how, and provides a couple of basic use cases. note: you can find working examples of all the code snippets in our voice-change-o-matic demo. basic concepts to extract data from your audio source, you need an analysernode, which is created using the audiocontext.createanalyser() method, for example: var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); this node is then connected to your audio source at some point between your source and your destination, for example: source = audioctx.createmediastreams...
...r example: analyser.getbytetimedomaindata(dataarray); we now have the audio data for that moment in time captured in our array, and can proceed to visualize it however we like, for example by plotting it onto an html5 <canvas>. let's go on to look at some specific examples. ...
...we have one available in voice-change-o-matic; let's look at how it's done. first, we again set up our analyse...
...And 2 more matches
Web Authentication API - Web APIs
a publickeycredential.rawid that is the globally unique credential id along with a response that is the authenticatorattestationresponse containing the authenticatorresponse.clientdatajson and authenticatorattestationresponse.attestationobject. the publickeycredential is sent back to the server using any desired formatting and protocol (note that the arraybuffer properties need to be be base64 encoded or similar). server validates and finalizes registration - finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. these include: verifying that the challenge is the same as the challenge that was sent ensuring that the origin was the origin expected validating that the signature over the clientdatahash and th...
... ...
... ...
...And 2 more matches
Window.openDialog() - Web APIs
Web › API › Window › openDialog
ndialog() treats the absence of the features parameter the same way window.open() does; that is, an empty string sets all features to off) except chrome and dialog, which default to on. if the features parameter is a zero-length string, or contains only one or more of the behavior features (chrome, dependent, dialog and modal) the chrome features are assumed "os' choice." that is, window creation code is not given specific instructions, but is instead allowed to select the chrome that best fits a dialog on that operating system. passing extra parameters to the dialog to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a pro...
...rs to the dialog to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property gets added to the newly opened dialog window. ...
... "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property gets added to the newly opened dialog window. to access these extra parameters from within dialog code, use the following scheme: var food = window.arguments[0]; var price = window.arguments[1]; note that you can access this property from within anywhere in the dialog code. (another example). returning values from the dialog since window.close() erases all properties associated with the dialog window (i.e. the variables specified in the javascript code which gets loaded from the dialog), it is not possible to pass return values back past the close operation using globals (or any other constructs). to be able to pass values back to the caller, you have to supply ...
...And 2 more matches
ARIA: figure role - Accessibility
<div role="figure" aria-labelledby="caption"> <img src="image.png" alt="full alternative image description"> <p id="caption">figure 1: the caption</p> </div> in the above example, we have a figure that consists of two separate content items — an image and a caption. ...
... a caption. this is wrapped by a <div> element that identifies the content as a figure using role="figure". instead of using aria to create a figure, consider using the native, semantic html <figure> element. along with the <figcaption> element. see best practices below. description any content that should be grouped together and consumed as a figure (which could include images, video, audio, code snippets, or other content) can be identified as a figure using role="figure". there are no hard and fast rules about how you should write your figure content. you should make sure that it is accessible just like any other content. for example, make sure it is perceivable by users of assistive technology, navigable by keyboard as well as mouse, and so on. you can add a caption or label to your ...
... if at all possible, you should use the appropriate semantic...
...And 2 more matches
Detecting CSS animation support - CSS: Cascading Style Sheets
css animations make it possible to do creative animations of content using nothing but css. however, there are likely to be times when this feature isn't available, and you may wish to handle that case by using javascript code to simulate a similar effect. this article, based on this blog post by chris heilmann, demonstrates a technique for doing this. ...
... css animations make it possible to do creative animations of content using nothing but css. however, there are likely to be times when this feature isn't available, and you may wish to handle that case by using javascript code to simulate a similar effect. this article, based on this blog post by chris heilmann, demonstrates a technique for doing this. ...
...lement specified by the variable elem is set. this means the browser supports css animation without any prefix, which, to date, none of them do. if the browser does not support non-prefixed animation and animation is still false, we iterate over all the possible prefixes, since all the major browsers are currently prefixing this property and changing its name to animationname instead. once this code is finished running, the value of animation will be false if css animation support isn't available, or it will be true. if it is true then both the animation property name and the keyframe prefix will be the right ones. so if you use a new firefox, the property will be mozanimation and the keyframe prefix -moz- and with chrome it'll be webkitanimation and -webkit-. notice browsers don't make it e...
...And 2 more matches
Border-image generator - CSS: Cascading Style Sheets
</div> <div class="property"> <div class="ui-input-slider" data-topic="preview-height" data-info="height" data-unit=" px" data-min="10" data-max="10000" data-sensivity="3"> </div> </div> </div> <div id="output" class="category"> <div class="title"> css code </div> <div class="css-property"> <span class="name"> border-image-slice: </span> <span id="out-border-slice" class="value"> </span> </div> <div class="css-property"> <span class="name"> border-image-width: </span> <span id="out-border-width" class="value"> </span> ...
...6px; background: url('https://mdn.mozillademos.org/files/6019/close.png') no-repeat center center; background-size: 75%; position: absolute; top: 4px; right: 4px; opacity: 0.5; } #unit-settings .close:hover { cursor: pointer; opacity: 1; } #unit-settings[data-active='true'] { opacity: 1; } #unit-settings[data-active='false'] { opacity: 0; top: -100px !important; } /* * css output code */ #output { padding: 10px; border: 2px dashed #888 !important; box-shadow: none !important; border-radius: 3px; overflow: hidden; -moz-user-select: text; -webkit-user-select: text; -ms-user-select: text; user-select: text; } @media (min-width: 880px) { #output { width: 63.33% !important; } } @media (max-width: 879px) { #output { width: 87% !important; } } #output .title ...
...order_slice = []; var border_width = []; var border_outset = []; var border_slice_values = []; var border_width_values = []; var border_outset_values = []; var border_slice_units = ['', '', '', '']; var border_width_units = ['px', 'px', 'px', 'px']; var border_outset_units = ['px', 'px', 'px', 'px']; var border_fill = false; var border_repeat = ['round', 'round']; var css_code = { 'source' : null, 'slice' : null, 'width' : null, 'outset' : null, 'repeat' : null }; var setborderslice = function setborderslice(positionid, value) { border_slice[positionid] = value + border_slice_units[positionid]; updateborderslice(); }; var updateborderslice = function updateborderslice() { var value = border_slice.join(' '); if (border_fill === true)...
...And 2 more matches
Mastering margin collapsing - CSS: Cascading Style Sheets
the sum of the largest positive margin and the smallest (most negative) negative margin. when all margins are negative, the size of the collapsed margin is the smallest (most negative) margin. this applies to both adjacent elements and nested elements. ...
...e largest positive margin and the smallest (most negative) negative margin. when all margins are negative, the size of the collapsed margin is the smallest (most negative) margin. this applies to both adjacent elements and nested elements. ...
...gative, the size of the collapsed margin is the smallest (most negative) margin. this applies to both adjacent elements and nested elements. ...
...And 2 more matches
overflow-y - CSS: Cascading Style Sheets
ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugi...
...ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. <...
...utside the box <div id="div1"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-y:scroll</code> — always adds a scrollbar <div id="div2"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat null...
...And 2 more matches
perspective - CSS: Cascading Style Sheets
syntax none | <length> examples setting perspective this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. ...
...examples setting perspective this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. ...
... this example shows a cube with the perspective set at different positions. how quick the cube shrinks is defined by the perspective property. the smaller its value is, the deeper the perspective is. html the html below creates four copies of the same box, with the perspective set at different values. ...
...And 2 more matches
Constraint validation - Developer guides
ltiple of the step. stepmismatch constraint violation month an integer number of months week an integer number of weeks datetime, datetime-local, time an integer number of seconds range, number an integer minlength text, search, url, tel, email, password; also on the <textarea> element an integer length the number of characters (code points) must not be less than the value of the attribute, if non-empty. all newlines are normalized to a single character (as opposed to crlf pairs) for <textarea>. tooshort constraint violation maxlength text, search, url, tel, email, password; also on the <textarea> element an integer length the number of characters (code points) must not exceed the value of the attribute. ...
...rigger javascript on some form field event (like onchange) to calculate whether the constraint is violated, and then to use the method field.setcustomvalidity() to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an error and this string is the error message to display to the user. constraint combining several fields: postal code validation the postal code format varies from one country to another. not only do most countries allow an optional prefix with the country code (like d- in germany, f- in france or switzerland), but some countries have postal codes with only a fixed number of digits; others, like the uk, have more complex structures, allowing letters at some specific positions. note: this is not a comprehensi...
...n the postal code format varies from one country to another. not only do most countries allow an optional prefix with the country code (like d- in germany, f- in france or switzerland), but some countries have postal codes with only a fixed number of digits; others, like the uk, have more complex structures, allowing letters at some specific positions. note: this is not a comprehensive postal code validation library, but rather a demonstration of the key concepts. as an example, we will add a script checking the constraint validation for this simple form: <form> <label for="zip">zip : </label> <input type="text" id="zip"> <label for="country">country : </label> <select id="country"> <option value="ch">switzerland</option> <option value="fr">france</option> ...
...And 2 more matches
Index - Developer guides
Web › Guide › Index
fullscreen apis. this follow-up article looks at how to style this custom player, including making it responsive. 14 web audio playbackrate explained apps, audio, media, video, playbackrate the playbackrate property of the <audio> and <video> elements allows us to change the speed, or rate, at which a piece of web audio or video is playing 15 writing web audio api code that works in every browser api you probably have already read the announcement on the web audio api coming to firefox, and are totally excited and ready to make your until-now-webkit-only sites work with firefox, which uses the unprefixed version of the spec. 16 audio and video manipulation audio, canvas, examples, guide, html5, media, video, web audio api, webgl, develo...
... when using orientation and motion events, it's important to understand what the values you're given by the browser mean. this article provides details about the coordinate systems at play and how you use them. 24 overview of events and handlers beginner, dom, example, javascript, needsbeginnerupdate, needsupdate, events this overview of events and event handling explains the code design pattern used to react to incidents occurring when a browser accesses a web page, and it summarizes the types of such incidents modern web browsers can handle. 25 touch events (mozilla experimental) dom the experimental touch events api described on this page was available from gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) to gecko/firefox 17. you should inste...
...t beginner, css, codingscripting, development, html, javascript, web whether you're just getting started with web development, or are just expanding your horizons into new realms of web awesomeness, the links here should help you get started. 31 localizations and character encodings character encodings, html, localization, needsmarkupwork browsers process text as unicode internally. however, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. the html specification recommends the use of the utf-8 encoding (which can represent all of unicode) and regardless of the encoding used requires web content to declare what encoding was used. 32 mobile web development intermedi...
...And 2 more matches
Localizations and character encodings - Developer guides
the <meta> element's charset attribute is used to specify the page's character encoding. it must be used within a <head> block. ...
... the <meta> element's charset attribute is used to specify the page's character encoding. it must be used within a <head> block. ...
...d by web content like the html specification requires, firefox will use that encoding for turning the bytes into the internal representation. unfortunately, using utf-8 and declaring that utf-8 was used was not always the prevalent way of offering web content. in the 1990s, it was common to leave the encoding undeclared and to use a region-specific encoding that wasn't able to represent all of unicode. firefox needs a fallback encoding that it uses for non-conforming legacy content that doesn't declare its encoding. for most locales, the fallback encoding is windows-1252 (often called iso-8859-1), which was the encoding emitted by most windows applications in the 1990s and a superset of the encoding emitted by most unix applications in the 1990s as a deployed in the america has and in western...
...And 2 more matches
<input type="date"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › date
is always formatted yyyy-mm-dd. you can get and set the date value in javascript with the input element's value and valueasnumber properties. for example: var datecontrol = document.queryselector('input[type="date"]'); datecontrol.value = '2017-06-01'; console.log(datecontrol.value); // prints "2017-06-01" console.log(datecontrol.valueasnumber); // prints 1496275200000, a unix timestamp this code finds the first <input> element whose type is date, and sets its value to 2017-06-01 (june 1st, 2017). it then reads that value back in string and number formats. additional attributes along with the attributes common to all <input> elements, date inputs have the following attributes: attribute description max the latest acceptable date min the earliest ...
... <option>july</option> <option>august</option> <option>september</option> <option>october</option> <option>november</option> <option>december</option> </select> </span> <span> <label for="year">year:</label> <select id="year" name="year"> </select> </span> </div> </form> the months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.) span { padding-left: 5px; } input:invalid + span::after { content: '✖'; } input:valid + span::after { content: '✓'; } javascript the oth...
...always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.) span { padding-left: 5px; } input:invalid + span::after { content: '✖'; } input:valid + span::after { content: '✓'; } javascript the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">. we create a new <input> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will return text, because the date type falls back to type text. if <input type="date"> isn't supported, we hide the native picker and show the fallbac...
...And 2 more matches
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. value a domstring representing the path to the selected file. ...
...less the multiple attribute is specified. multiple when the multiple boolean attribute is specified, the file input allows the user to select more than one file. non-standard attributes in addition to the attributes listed above, the following non-standard attributes are available on some browsers. you should try to avoid using them when possible, since doing so will limit the ability of your code to function in browsers that don't implement them. attribute description webkitdirectory a boolean indicating whether or not to only allow the user to choose a directory (or directories, if multiple is also present) webkitdirectory the boolean webkitdirectory attribute, if present, indicates that only directories should be available to be selected by the us...
... regardless of the user's device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file. including the multiple attribute, as shown above, specifies that multiple files can be chosen at once. the user can choose multiple files from the file picker in any way that their chosen platform allows (...
...And 2 more matches
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
s constraint validation. if a value is specified for min that isn't a valid year and month string, the input has no minimum value. this value must be a year-month pairing which is earlier than or equal to the one specified by the max attribute. readonly a boolean attribute which, if present, means this field cannot be edited by the user. its value can, however, still be changed from javascript code that directly sets the value of the htmlinputelement.value property. note: because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step the step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. only values which are equal to the...
...eft: 5px; } important: html form validation is not a substitute for scripts that ensure that the entered data is in the proper format. it's far too easy for someone to make adjustments to the html that allow them to bypass the validation, or to remove it entirely. it's also possible for someone to simply bypass your html entirely and submit the data directly to your server. if your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). handling browser support as mentioned above, the major problem with using date inputs at the time of writing is that many major browsers don't yet implement them all; only chrome/opera and edge support it on desktop, and most m...
...">year:</label> <select id="year" name="year"> </select> </span> </div> </div> </form> the <div> with the id nativedatepicker uses the month input type to request the month and year, while the <div> with the id fallbackdatepicker instead uses a pair of <select> elements. the first requests the month, and the second the year. the <select> for choosing the month is hardcoded with the names of the months, as they don't change (leaving localization out of things). the list of available year values is dynamically generated depending on the current year (see the code comments below for detailed explanations of how these functions work). div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px;...
...And 2 more matches
<input type="week"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › week
ue of the element is less than this, the element fails constraint validation. if a value is specified for min that isn't a valid week string, the input has no minimum value. this value must be less than or equal to the value of the max attribute. readonly a boolean attribute which, if present, means this field cannot be edited by the user. its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property. note: because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step the step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. only values which are equal to the basis for step...
...g browser: important: html form validation is not a substitute for scripts that ensure that the entered data is in the proper format. it's far too easy for someone to make adjustments to the html that allow them to bypass the validation, or to remove it entirely. it's also possible for someone to simply bypass your html entirely and submit the data directly to your server. if your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, of the wrong type, and so forth). handling browser support as mentioned above, the major problem with using week inputs right now is browser support: safari and firefox don't support it on desktop, and old versions of ie don't support it. mobile platforms such...
...</label> <select id="fallbackweek" name="week"> </select> </span> <span> <label for="year">year:</label> <select id="year" name="year"> <option value="2017" selected>2017</option> <option value="2018">2018</option> </select> </span> </div> </div> </form> the week values are dynamically generated by the javascript code below. div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the other part of the code that may be of interest is the feature detect...
...And 2 more matches
<table>: The Table element - HTML: Hypertext Markup Language
Web › HTML › Element › table
t: the table is displayed on the left side of the document; center: the table is displayed in the center of the document; right: the table is displayed on the right side of the document. set margin-left and margin-right to auto or margin to 0 auto to achieve an effect that is similar to the align attribute. bgcolor the background color of the table. it is a 6-digit hexadecimal rgb code, prefixed by a '#'. one of the predefined color kewords can also be used. to achieve a similar effect, use the css background-color property. border this integer attribute defines, in pixels, the size of the frame surrounding the table. if set to 0, the frame attribute is set to void. to achieve a similar effect, use the css border shorthand property. cellpadding this attribut...
...xperiences. in complex tables, scope can be specified so as to provide necessary information about the cells related to a header. ...
... complex tables, scope can be specified so as to provide necessary information about the cells related to a header. ...
...And 2 more matches
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › tt
of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer. the terms non-proportional, monotype, and monospace are used interchangeably and have the same general meaning: they describe a typeface whose characters are all the same number of pixels wide. this element is obsolete, however. you should use the more semantically helpful <code>, <kbd>, <samp>, or <var> elements for inline text that needs to be presented in monospace type, or the <pre> tag for content that should be presented as a separate block. if none of the semantic elements are appropriate for your use case (for example, if you simply need to show some content in a non-proportional font), you should consider using the <span> element, styling it as desired using cs...
...re mandatory. permitted parents any element that accepts phrasing content. permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes examples basic example this example uses <tt> to show text entered into, and output by, a terminal application. ...
... permitted parents any element that accepts phrasing content. permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes examples basic example this example uses <tt> to show text entered into, and output by, a terminal application. ...
...And 2 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
urce> elements, and the browser will then use the first one it understands. <video controls> <source src="myvideo.mp4" type="video/mp4"> <source src="myvideo.webm" type="video/webm"> <p>your browser doesn't support html5 video. here is a <a href="myvideo.mp4">link to the video</a> instead.</p> </video> we offer a substantive and thorough guide to media file types and the guide to the codecs supported for video. also available is a guide to audio codecs that can be used with them. other usage notes: if you don't specify the controls attribute, the video won't include the browser's default controls; you can create your own custom controls using javascript and the htmlmediaelement api. see creating a cross-browser video player for more details. to allow precise control over your...
...ement. htmlmediaelement.videotracks add an addtrack listener to this videotracklist object to be informed when video tracks are added to the element. htmlmediaelement.texttracks add an addtrack event listener to this texttracklist to be notified when new text tracks are added to the element. ...
... text tracks are added to the element. for example, to detect when audio tracks are added to or removed from a <video> element, you can use code like this: var elem = document.queryselector("video"); elem.audiotracklist.onaddtrack = function(event) { trackeditor.addtrack(event.track); }; elem.audiotracklist.onremovetrack = function(event) { trackeditor.removetrack(event.track); }; this code watches for audio tracks to be added to and removed from the element, and calls a hypothetical function on a track editor to register and remove the track from the editor's list of available tracks. you can also use addeventlistener() to listen for the addtrack and removetrack events. examples simple video example this example plays a video when activated, providing the user with the browser'...
...And 2 more matches
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
resent by is not specified or is invalid, no max value is applied. if the max attribute is valid and a non-empty value is greater than the maximum allowed by the max attribute, constraint validation will prevent form submission. 41 html attribute: maxlength attribute, attributes, constraint validation the maxlength attribute defines the maximum number of characters (as utf-16 code units) the user can enter into an <input> or <textarea>. this must be an integer value 0 or higher. 42 html attribute: min attribute, attributes, constraint validation, min the min attribute defines the minimum value that is acceptable and valid for the input containing the attribute. if the value of the element is less than this, the element fails constraint validation. this...
... is less than this, the element fails constraint validation. this value must be less than or equal to the value of the max attribute. if a value is specified for min that isn't a valid number, the input has no minimum value. 43 html attribute: minlength attribute, input, reference, minlength, textarea the minlength attribute defines the minimum number of characters (as utf-16 code units) the user can enter into an <input> or <textarea>. this must be an integer value 0 or higher. if no minlength is specified, or an invalid value is specified, the input has no minimum length. this value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria. 44 html attribute: multiple attribute,...
... or inline contents centered horizontally within its containing element. 79 <cite>: the citation element attribution, citation, citing references, citing works, element, html, html text-level semantics, quotations, reference, web the html citation element (<cite>) is used to describe a reference to a cited creative work, and must include the title of that work. 80 <code>: the inline code element code, element, html, html text-level semantics, inline code, reference, web the html <code> element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. 81 <col> element, html, html tabular data, reference, tables, web the html <col> element defines a column within a table and is...
...And 2 more matches
Data URLs - HTTP
if non-textual, and the data itself: data:[<mediatype>][;base64],<data> the mediatype is a mime type string, such as 'image/jpeg' for a jpeg image file. if omitted, defaults to text/plain;charset=us-ascii if the data is textual, you can simply embed the text (using the appropriate entities or escapes based on the enclosing document's type). otherwise, you can specify base64 to embed base64-encoded binary data. you can find more info on mime types here and here. a few examples: data:,hello%2c%20world! simple text/plain data. note the use of percent-encoding (url-encoding) for the quote and space characters. also, for csv data (mime type "text/csv"), percent-encoding is needed to preserve the line endings that delimit rows of the spreadsheet. data:text/plain;base64,sgvsbg8sifdvcmxkiq=...
...a. you can find more info on mime types here and here. a few examples: data:,hello%2c%20world! simple text/plain data. note the use of percent-encoding (url-encoding) for the quote and space characters. also, for csv data (mime type "text/csv"), percent-encoding is needed to preserve the line endings that delimit rows of the spreadsheet. data:text/plain;base64,sgvsbg8sifdvcmxkiq== base64-encoded version of the above data:text/html,%3ch1%3ehello%2c%20world!%3c%2fh1%3e an html document with <h1>hello, world!</h1> data:text/html,<script>alert('hi');</script> an html document that executes a javascript alert. note that the closing script tag is required. encoding data into base64 format base64 is a group of binary-to-text encoding schemes that represent binary data in an ascii string...
...ml document that executes a javascript alert. note that the closing script tag is required. encoding data into base64 format base64 is a group of binary-to-text encoding schemes that represent binary data in an ascii string format by translating it into a radix-64 representation. by consisting only in ascii characters, base64 strings are generally url-safe, and that's why they can be used to encode data in data urls. encoding in javascript the web apis have native methods to encode or decode to base64: base64 encoding and decoding. encoding on a unix system base64 encoding of a file or string on linux and mac os x systems can be achieved using the command-line base64 (or, as an alternative, the uuencode utility with -m argument). echo -n hello|base64 # outputs to console: agvsbg8= ech...
...And 2 more matches
Access-Control-Allow-Origin - HTTP
attempting to use the wildcard with credentials will result in an error. <origin> specifies an origin. only a single origin can be specified. ...
...attempting to use the wildcard with credentials will result in an error. <origin> specifies an origin. only a single origin can be specified. if the server supports clients from multiple origins, it must return the origin for the specific client making the request. null specifies the origin "null". ...
...ierarchical scheme (such as data: or file:) and sandboxed documents is defined to be "null". many user agents will grant such documents access to a response with an access-control-allow-origin: "null" header, and any origin can create a hostile document with a "null" origin. ...
...And 2 more matches
CSP: script-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples violation case given this csp header: content-security-policy: script-src https://example.com/ the following script is blocked and won't be loaded or executed: <script src="https://not-example.com/js/library.js"></script> note that inline event handlers are blocked as well: <button id="btn" onclick="dosomething()"> you should replace the...
...And 2 more matches
POST - HTTP
Web › HTTP › Methods › POST
successive identical post may have additional effects, like passing an order several times. a post request is typically sent via an html form and results in a change on the server. ...
...e additional effects, like passing an order several times. a post request is typically sent via an html form and results in a change on the server. ...
...this case, the content type is selected by putting the adequate string in the enctype attribute of the <form> element or the formenctype attribute of the <input> or <button> elements: application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead) multipart/form-data: each value is sent as a block of data ("body part"), with a user agent-defined delimiter ("boundary") separating each part. the keys are given in the content-disposition header of each part. text/plain when the post request is sent via a method other than an html f...
...And 2 more matches
Redirections in HTTP - HTTP
redirect, for this operation. redirects accomplish numerous goals: temporary redirects during site maintenance or downtime permanent redirects to preserve existing links/bookmarks after changing the site's urls, progress pages when uploading a file, etc. principle in http, redirection is triggered by a server sending a special redirect response to a request. redirect responses have status codes that start with 3, and a location header holding the url to redirect to. when browsers receive a redirect, they immediately load the new url provided in the location header. besides the small performance hit of an additional round-trip, users rarely notice the redirection. there are several types of redirects, sorted into three categories: permanent redirections temporary redirections s...
...veral types of redirects, sorted into three categories: permanent redirections temporary redirections special redirections permanent redirections these redirections are meant to last forever. they imply that the original url should no longer be used, and replaced with the new one.search engine robots, rss readers, and other crawlers will update the original url for the resource. code text method handling typical use case 301 moved permanently get methods unchanged. others may or may not be changed to get.[1] reorganization of a web site. 308 permanent redirect method and body not changed. reorganization of a web site, with non-get links/operations. [1] the specification did not intend to allow method changes, but the...
...orary redirections sometimes the requested resource can't be accessed from its canonical location, but it can be accessed from another place. in this case, a temporary redirect can be used. search engine robots and other crawlers don't memorize the new, temporary url. temporary redirections are also used when creating, updating, or deleting resources, to show temporary progress pages. code text method handling typical use case 302 found get methods unchanged. others may or may not be changed to get.[2] the web page is temporarily unavailable for unforeseen reasons. 303 see other get methods unchanged. others changed to get (body lost). used to redirect after a put or a post, so that refreshing the result page doesn't re-trigg...
...And 2 more matches
Details of the object model - JavaScript
ction. so, in this example, you could informally say that jane is an instance of engineer. similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in javascript; you can use them informally to refer to objects higher or lower in the prototype chain. creating objects with simple definitions object hierarchy the following hierarchy is created using the code on the right side. individual objects = jim, sally, mark, fred, jane, etc. "instances" created from constructor var jim = new employee; // parentheses can be omitted if the // constructor takes no arguments. // jim.name is '' // jim.dept is 'general' var sally = new manager; // sally.name is '' // sally.dept is 'general' // sally.reports is [] var mark = new workerbee; // mark.name is '' /...
... (string mach) { dept = "engineering"; machine = mach; } } these javascript definitions use a special idiom for setting default values: this.name = name || ''; the javascript logical or operator (||) evaluates its first argument. if that argument converts to true, the operator returns it. otherwise, the operator returns the value of the second argument. therefore, this line of code tests to see if name has a useful value for the name property. if it does, it sets this.name to that value. otherwise, it sets this.name to the empty string. this chapter uses this idiom for brevity; however, it can be puzzling at first glance. note: this may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string (""). in...
...nt to create a new engineer: var jane = new engineer('belau'); jane's properties are now: jane.name == ''; jane.dept == 'engineering'; jane.projects == []; jane.machine == 'belau'; notice that with these definitions, you cannot specify an initial value for an inherited property such as name. if you want to specify an initial value for inherited properties in javascript, you need to add more code to the constructor function. so far, the constructor function has created a generic object and then specified local properties and values for the new object. you can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. the following figure shows these new definitions. specifying properties in a constructor, take 2 ...
...And 2 more matches
constructor - JavaScript
to'); otto.introduce(); if you don't provide your own constructor, then a default constructor will be supplied for you. ...
...tializing the parent error from the argument it is given. however, if you provide your own constructor, and your class derives from some parent class, then you must explicitly call the parent class constructor using super. ...
...d your class derives from some parent class, then you must explicitly call the parent class constructor using super. ...
...And 2 more matches
Deprecated and obsolete features - JavaScript
this page lists features of javascript that are deprecated (that is, still available but planned for removal) and obsolete (that is, no longer usable). deprecated features these deprecated features can still be used, but should be used with caution because they are expected to be removed entirely sometime in the future. you should work to remove their use from your code. regexp properties the following properties are deprecated. this does not affect their use in replacement strings: property description $1-$9 parenthesized substring matches, if any. warning: using these properties can result in problems, since browser extensions can modify them. avoid them! $_ see input. $* see multiline. $& see lastmatch. ...
...precated. iterator is deprecated. object methods watch and unwatch are deprecated. use proxy instead. __iterator__ is deprecated. __nosuchmethod__ is deprecated. use proxy instead. date methods getyear and setyear are affected by the year-2000-problem and have been subsumed by getfullyear and setfullyear. you should use toisostring instead of the deprecated togmtstring method in new code. tolocaleformat is deprecated. functions expression closures are deprecated. use regular functions or arrow functions instead. proxy proxy.create and proxy.createfunction are deprecated. use proxy instead. the following traps are obsolete: hasown (bug 980565, firefox 33). getenumerablepropertykeys (bug 783829, firefox 37) getownpropertynames (bug 1007334, firefox 33) ke...
... obsolete: hasown (bug 980565, firefox 33). getenumerablepropertykeys (bug 783829, firefox 37) getownpropertynames (bug 1007334, firefox 33) keys (bug 1007334, firefox 33) escape sequences octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals. the escape and unescape functions are deprecated. use encodeuri, encodeuricomponent, decodeuri or decodeuricomponent to encode and decode escape sequences for special characters. string methods html wrapper methods like string.prototype.fontsize and string.prototype.big. string.prototype.quote is removed from firefox 37. non standard flags parameter in string.prototype.search, string.prototype.match, and string.prototype.replace are deprecated. str...
...And 2 more matches
Array.prototype.map() - JavaScript
before being visited are not visited. due to the algorithm defined in the specification, if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank. polyfill map was added to the ecma-262 standard in the 5th edition. therefore, it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object, typeerror, and array have their original values and that callback.call evaluates to the original value of function.prototype.call. // production steps of ecma-262, edition 5, 15.4.4.19 // reference: http:...
... // value: mappedvalue, // writable: true, // enumerable: true, // configurable: true // }); // for best browser support, use the following: a[k] = mappedvalue; } // d. increase k by 1. k++; } // 9. ...
...pping an array of numbers to an array of square roots the following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array. let numbers = [1, 4, 9] let roots = numbers.map(function(num) { return math.sqrt(num) }) // roots is now [1, 2, 3] // numbers is still [1, 4, 9] using map to reformat objects in an array the following code takes an array of objects and creates a new array containing the newly reformatted objects. let kvarray = [{key: 1, value: 10}, {key: 2, value: 20}, {key: 3, value: 30}] let reformattedarray = kvarray.map(obj => { let robj = {} robj[obj.key] = obj.value return robj }) // reformattedarray is now [{1: 10}, {2: 20}, {3: 30}], // kvarray is still: // [{key: 1...
...And 2 more matches
Function.prototype.bind() - JavaScript
sults in the execution of its wrapped function. a bound function has the following internal properties: [[boundtargetfunction]] the wrapped function object [[boundthis]] the value that is always passed as this value when calling the wrapped function. [[boundarguments]] a list of values whose elements are used as the first arguments to any call to the wrapped function. [[call]] executes code associated with this object. invoked via a function call expression. the arguments to the internal method are a this value and a list containing the arguments passed to the function by a call expression. when a bound function is called, it calls internal method [[call]] on [[boundtargetfunction]], with following arguments call(boundthis, ...args). where boundthis is [[boundthis]], args is [[bou...
...lyfills to make the browsing experience in outdated browsers slightly less horrible. thus, presented below are two options for function.prototype.bind() polyfills: the first one is much smaller and more performant, but does not work when using the new operator. the second one is bigger and less performant, but it permits some usage of the new operator on bound functions. generally, in most code it's very rare to see new used on a bound function, so it is generally best to go with the first option. // does not work with `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var slice = array.prototype.slice; function.prototype.bind = function() { var thatfunc = this, thatarg = arguments[0]; var args = slice.call(arguments, 1); if (typeof thatfunc !
... // yes, it does work with `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var arrayprototypeslice = array.prototype.slice; function.prototype.bind = function(otherthis) { if (typeof this !== 'function') { // closest ...
...And 2 more matches
Intl.Collator() constructor - JavaScript
you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new intl.collator([locales[, options]]) parameters locales optional. a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension keys are allowed: co variant collations for certain locales. possible values include: "big5han", "dict", "direct", "ducet", "gb2312", "phonebk", "phonetic", "pinyin", "reformed", "searchjl", "stroke", "trad", "unihan". the "standard" and "search" values are ignored; they are replaced by the options property usage (see below). kn whether numeric collation should be used, such ...
...", "ducet", "gb2312", "phonebk", "phonetic", "pinyin", "reformed", "searchjl", "stroke", "trad", "unihan". the "standard" and "search" values are ignored; they are replaced by the options property usage (see below). kn whether numeric collation should be used, such that "1" < "2" < "10". possible values are "true" and "false". this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence. kf whether upper case or lower case should sort first. possible values are "upper", "lower", or "false" (use the locale's default). this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence. options optional. an object wit...
... "variant" for usage "sort"; it's locale dependent for usage "search". ignorepunctuation whether punctuation should be ignored. possible values are true and false; the default is false. numeric whether numeric collation should be used, such that "1" < "2" < "10". possible values are true and false; the default is false. ...
...And 2 more matches
Object.create() - JavaScript
for example: a simple common debugging function: // display top-level property name:value pairs of given object function showproperties(obj){ for(var prop in obj){ console.log(prop + ": " + obj[prop] + "\n" ); } } not such simple results: (especiall...
...co; // create same compound object again, but create same properties in different order > showproperties( ob ) // display top-level properties - error: cannot convert object to primitive value note that neither property gets shown. note that such a different order may arise statically via disparate fixed codings such as here, but also dynamically via whatever the order any such property-adding code-branches actually get executed at runtime as depends on inputs and/or random-variables. then again, the actual iteration order is not guaranteed no matter what the order members are added. be aware of, also, that using object.entries() on an object created via object.create() will result in an empty array being returned. var obj = object.create({ a: 1, b: 2 }); > console.log(object.entries(obj...
...ons a good solution for the missing object-methods is not immediately apparent. ...
...And 2 more matches
String.prototype.charAt() - JavaScript
the string object's charat() method returns a new string consisting of the single utf-16 code unit located at the specified offset into the string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax let character = str.charat(index) parameters index an integer between 0 and str.length - 1. if the index cannot be converted to the integer or no index is provided, the default is 0, so the first character of str is returned. return value a string representing the character (exactly one utf-16 code unit) at the specified index. if index is out of range, charat() returns an empty string. description charact...
... z'; // we could also use a non-bmp character directly for (var i = 0, chr; i < str.length; i++) { if ((chr = getwholechar(str, i)) === false) { continue; } // adapt this line at the top of each loop, passing in the whole string and // the current iteration and returning a variable to represent the // individual character console.log(chr); } function getwholechar(str, i) { var code = str.charcodeat(i); if (number.isnan(code)) { return ''; // position not found } if (code < 0xd800 || code > 0xdfff) { return str.charat(i); } // high surrogate (could change last hex to 0xdb7f to treat high private // surrogates as single characters) if (0xd800 <= code && code <= 0xdbff) { if (str.length <= (i + 1)) { throw 'high surrogate without following low...
...code)) { return ''; // position not found } if (code < 0xd800 || code > 0xdfff) { return str.charat(i); } // high surrogate (could change last hex to 0xdb7f to treat high private // surrogates as single characters) if (0xd800 <= code && code <= 0xdbff) { if (str.length <= (i + 1)) { throw 'high surrogate without following low surrogate'; } var next = str.charcodeat(i + 1); if (0xdc00 > next || next > 0xdfff) { throw 'high surrogate without following low surrogate'; } return str.charat(i) + str.charat(i + 1); } // low surrogate (0xdc00 <= code && code <= 0xdfff) if (i === 0) { throw 'low surrogate without preceding high surrogate'; } var prev = str.charcodeat(i - 1); // (could change last hex to 0xdb7f to treat hi...
...And 2 more matches
import - JavaScript
/modules/my-module.js'; rename multiple exports during import import multiple exports from a module with convenient aliases. import { reallyreallylongmoduleexportname as shortname, anotherlongmodulename as short } from '/modules/my-module.js'; import a module for its side effects only import an entire module for side effects only, without importing anything. ...
... importing defaults it is possible to have a default export (whether it is an object, a function, a class, etc.). the import statement may then be used to import such defaults. ...
...c, named imports when importing a default export with dynamic imports, it works a bit differently. you need to destructure and rename the "default" key from the returned object. ...
...And 2 more matches
var - JavaScript
ithub.com/mdn/interactive-examples and send us a pull request. syntax var varname1 [= value1] [, varname2 [= value2] ... [, varnamen [= valuen]]]; varnamen variable name. it can be any legal identifier. valuen optional initial value of the variable. it can be any legal expression. default value is undefined. description var declarations, wherever they occur, are processed before any code is executed. this is called hoisting, and is discussed further below. the scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. duplicate variable declarations using var will not trigger an error, even in strict mode, and the var...
...r assignment is performed. 'use strict'; function foo() { var x = 1; function bar() { var y = 2; console.log(x); // 1 (function `bar` closes over `x`) console.log(y); // 2 (`y` is in scope) } bar(); console.log(x); // 1 (`x` is in scope) console.log(y); // referenceerror in strict mode, `y` is scoped to `bar` } foo(); variables declared using var are created before any code is executed in a process known as hoisting. their initial value is undefined. 'use strict'; console.log(x); // undefined (note: not referenceerror) console.log('still going...'); // still going... var x = 1; console.log(x); // 1 console.log('still going...'); // still going... in the global context, a variable declared using var is added as a non-configurable prope...
...mode will result in a referenceerror, to avoid the accidental creation of properties on the global object. note that the implication of the above, is that, contrary to popular misinformation, javascript does not have implicit or undeclared variables, it merely has a syntax that looks like it does. var hoisting because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. this also means that a variable can appear to be used before it's declared. this behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code. bla = 2; var bla; // ...is implicitly understood as: var bla; bla = 2; for that reason, i...
...And 2 more matches
Digital video concepts - Web media technologies
in this article, we explore important concepts that are useful to understand in order to fully grasp how to work with video on the web. encoding color representing the colors in an image or video requires several values for each pixel. what those values are depends on how you "split up" the color when converting it to numeric form. there are several color models, and video codec makes use of one or more of these to represent their pixels during the encoding process as well as after decoding the video frames. rgb most computer graphics models use the rgb color system, wherein some number of bits of data are used to represent each of the red, green, and blue components of the color of an individual pixel, and an image is comprised of a two-dimensional array of these pixels. there ...
... b' - y'. red-difference (v or cr) the red-difference component of the chroma of the color sample. computed by substracting luma from the gamma corrected red value: v = r' - y'. chroma subsampling chroma subsampling is the process of converting the color pixels into a greyscale image and a matrix of u and v values indicating the colors to map to those pixels. since the color data is being encoded at a lower resolution than the luma, when decoding the video to draw it to the screen each pixel's color is computed by calculating an appropriate color given the u and v values for the 4x2 block of 8 pixels in which the pixel resides. this decoding operation must mirror the method used during encoding, which is represented by three numbers separated by colons (":"). the first number specifie...
...decoding the video to draw it to the screen each pixel's color is computed by calculating an appropriate color given the u and v values for the 4x2 block of 8 pixels in which the pixel resides. this decoding operation must mirror the method used during encoding, which is represented by three numbers separated by colons (":"). the first number specifies the number of luminance samples per row encoded from the 4x2 pixel block. this value is essentially always 4, meaning "use all of the luminance samples." the second number specifies how many chroma samples are used to represent the colors of the pixels in the first row. the third number indicates how many chroma samples are used to represent the colors of the pixels in the second row. the table below shows examples of three chroma subsamp...
...And 2 more matches
Progressive loading - Progressive web apps (PWAs)
s problem can be solved with the new intersection observer api — using this we can ensure that images will be loaded only when they appear in the viewport. intersection observer this is a progressive enhancement to the previously working example — intersection observer will load target images only when the user scrolls down, causing them to display in the viewport. ...
...of it. the function passed as a parameter is handling the case when one or more items are intersecting with the observer (i.e. is appearing inside the viewport). we can iterate over each case and react accordingly — when an image is visible, we load the correct image and stop observing it as we no longer need to observe it. let's reiterate our earlier mention of progressive enhancement — the code is written so that the app will work whether intersection observer is supported or not. if it's not, we just load the images using the more basic approach covered earlier. improvements remember that there are many ways to optimize loading times, and this example is exploring only one of the approaches. you could try to make your apps more bulletproof by making them work without javascript — e...
...roof by making them work without javascript — either using <noscript> to show the image with final src already assigned, or by wrapping <img> tags with <a> elements pointing at the target images, so the user can click and access them when desired. we won't do that because the app itself is dependent on javascript — without it, the list of games wouldn't even be loaded, and the service worker code wouldn't be executed. we could rewrite the loading process to load not only the images, but the complete items consisting of full descriptions and links. it would work like an infinite scroll — loading the items on the list only when the user scrolls the page down. that way the initial html structure would be minimal, loading time even smaller, and we would have even greater performance benefi...
...And 2 more matches
Using shadow DOM - Web Components
the shadow dom api is a key part of this, providing a way to attach a hidden separated dom to an element. this article covers the basics of using the shadow dom. note: shadow dom is supported by default in firefox (63 and onwards), chrome, opera, and safari. the new chromium-based edge (75 and onwards) supports it too; the old edge didn't. ...
...he shadow dom ends, and the regular dom begins. shadow root: the root node of the shadow tree. you can affect the nodes in the shadow dom in exactly the same way as non-shadow nodes — for example appending children or setting attributes, styling individual nodes using element.style.foo, or adding style to the entire shadow dom tree inside a <style> element. the difference is that none of the code inside a shadow dom can affect anything outside it, allowing for handy encapsulation. note that the shadow dom is not a new thing by any means — browsers have used it for a long time to encapsulate the inner structure of an element. think for example of a <video> element, with the default browser controls exposed. all you see in the dom is the <video> element, but it contains a series of butto...
... for exam...
...And 2 more matches
Classes and Inheritance - Archive of obsolete content
es to inherit state and behavior from an existing classes, known as the base class. unlike languages like c++ and java, javascript does not have native support for classical inheritance. instead, it uses something called prototypal inheritance. as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. classes in javascript are defined using constructor functions. each constructor function has an associated object, known as its prototype, which is shared between all instances of that class. we will show how to define classes using constructors, and how to use prototypes to efficiently define member functions on each instance. classical inheritance can be implemented in javascript using constr...
...tor does not return a value, the result of the call defaults to the value of this. constructors are just ordinary functions, however, so it is perfectly legal to perform ordinary function calls on them. in fact, some people (including the add-on sdk team) prefer to use constructors this way. however, since the value of this is undefined for ordinary function calls, we need to add some boilerplate code to convert them to constructor calls: function shape(x, y) { if (!this) return new shape(x, y); this.x = x; this.y = y; } prototypes every object has an implicit property, known as its prototype. when javascript looks for a property, it first looks for it in the object itself. if it cannot find the property there, it looks for it in the object's prototype. if the property ...
... javascript looks for the method draw on an instance of circle, it first looks for it on the object itself. when it cannot find the property there, it looks for it on the prototype of circle. when it cannot find the property there either, it looks for it on shape, at which point the lookup succeeds. the resulting behavior is what we were aiming for. inheritance and instanceof the single line of code we added in the previous section solved the problem with prototypes, but introduced a new problem with the instanceof operator. consider the following: let circle = circle(2, 3, 5); circle instanceof shape; // => false since instances of circle inherit from shape, we definitely want the result of this expression to be true. to understand why it is not, we need to understand how instanceof work...
...e get: let shape = shape(2, 3); shape.draw(); // error: not yet implemented let circle = circle(2, 3, 5); circle.draw(); // typeerror: ctx is not defined which is the behavior we were aiming for. classes in the add-on sdk we have shown how to emulate classical inheritance in javascript using constructors and prototypes. however, as we have seen, this takes a significant amount of boilerplate code. the add-on sdk team consists of highly trained professionals, but they are also lazy: that is why the sdk contains a helper function that handles this boilerplate code for us. it is defined in the module “core/heritage”: const { class } = require('sdk/core/heritage'); the function class is a meta-constructor: it creates constructors that behave properly with respect to inheritance. it tak...
request - Archive of obsolete content
ion will be called when the request has received a response (or in terms of xhr, when readystate == 4). the function is passed a response object. headers object an unordered collection of name/value pairs representing headers to send with the request. content string,object the content to send to the server. if content is a string, it should be url-encoded (use encodeuricomponent). if content is an object, it should be a collection of name/value pairs. nested objects & arrays should encode safely. for get and head requests, the query string (content) will be appended to the url. for post and put requests, it will be sent as the body of the request. contenttype string the type of content to send to the server. this expl...
.../value pairs. nested objects & arrays should encode safely. for get and head requests, the query string (content) will be appended to the url. for post and put requests, it will be sent as the body of the request. contenttype string the type of content to send to the server. this explicitly sets the content-type header. the default value is application/x-www-form-urlencoded. overridemimetype string use this string to override the mime type returned by the server in the response's content-type header. you can use this to treat the content as a different mime type, or to force text to be interpreted using a specific character. ...
... the default value is application/x-www-form-urlencoded. overridemimetype string use this string to override the mime type returned by the server in the response's content-type header. you can use this to treat the content as a different mime type, or to force text to be interpreted using a specific character. for example, if you're retrieving text content which was encoded as iso-8859-1 (latin 1), it will be given a content type of "utf-8" and certain characters will not display correctly. to force the response to be interpreted as latin-1, use overridemimetype: var request = require("sdk/request").request; var quijote = request({ url: "http://www.latin1files.org/quijote.txt", overridemimetype: "text/plain; charset=latin1", oncomplete: function (respons...
...turned by the get(), head(), post(), put() or delete() method of a request object. all members of a response object are read-only. properties url the url of the response content. text the content of the response as plain text. json the content of the response as a javascript object. the value will be null if the document cannot be processed by json.parse. status the http response status code (e.g. 200). statustext the http response status line (e.g. ok). headers the http response headers represented as key/value pairs. to print all the headers you can do something like this: for (var headername in response.headers) { console.log(headername + " : " + response.headers[headername]); } anonymous boolean indicating if the request was anonymous. ...
loader/sandbox - Archive of obsolete content
ing, in which case the sandbox will get the same privileges as a script loaded from that url a dom window object, to inherit privileges from the window being passed. omitted or null: then the sandbox will have chrome privileges giving it access to all the xpcom components. optionally the sandbox function can be passed a second argument (see sandbox documentation on mdn for details). evaluate code module provides evaluate function that lets you execute code in the given sandbox: evaluate(scope, 'var a = 5;'); evaluate(scope, 'a + 2;'); //=> 7 more details about evaluated script may be passed via optional arguments that may improve exception reporting: // evaluate code as if it was loaded from 'http://foo.com/bar.js' and // start from 2nd line. evaluate(scope, 'a ++', 'http://foo.com/ba...
... that determines the privileges that will be given to the sandbox. this argument can be: a uri string, giving the sandbox the same privileges as a script loaded from that url a dom window object, giving the sandbox the same privileges as the dom window null, to give the sandbox chrome privileges. returns sandbox : a sandbox in which you can evaluate and load javascript. ...
... will be given to the sandbox. this argument can be: a uri string, giving the sandbox the same privileges as a script loaded from that url a dom window object, giving the sandbox the same privileges as the dom window null, to give the sandbox chrome privileges. returns sandbox : a sandbox in which you can evaluate and load javascript. evaluate(sandbox, code, uri, line, version) evaluate code in sandbox, and return the result. parameters sandbox : sandbox the sandbox to use. code : string the code to execute. uri : string evaluate the code as if it were being loaded from the given uri. optional. line : number evaluate the code starting at this line. optional, defaults to 1. version : string evaluate the code using this version of javascript. defaults to 1.8. returns resul...
... parameters sandbox : sandbox the sandbox to use. code : string the code to execute. uri : string evaluate the code as if it were being loaded from the given uri. optional. line : number evaluate the code starting at this line. optional, defaults to 1. version : string evaluate the code using this version of javascript. defaults to 1.8. returns result : returns whatever the evaluated code returns. load(sandbox, uri) evaluate code from uri in sandbox. parameters sandbox : sandbox the sandbox to use. uri : string the url pointing to the script to load. it must be a local chrome:, resource:, file: or data: url. returns result : returns whatever the evaluated code returns. ...
Display a Popup - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. to display a popup dialog, use the panel module. a panel's content is defined using html. you can run content scripts in the panel: although the script running in the panel can't directly access your main add-on code, you can exchange messages between the panel script and the add-on code. in this tutorial we'll create an add-on that adds an action button to the toolbar that displays a panel when clicked. ...
... running in the panel can't directly access your main add-on code, you can exchange messages between the panel script and the add-on code. in this tutorial we'll create an add-on that adds an action button to the toolbar that displays a panel when clicked. the panel just contains a <textarea> element: when the user presses the return key, the contents of the <textarea> is sent to the main add-on code. the main add-on code logs the message to the console. ...
...n add-on that adds an action button to the toolbar that displays a panel when clicked. the panel just contains a <textarea> element: when the user presses the return key, the contents of the <textarea> is sent to the main add-on code. the main add-on code logs the message to the console. ...
...rt.on("text-entered", function (text) { console.log(text); text_entry.hide(); }); the content script "get-text.js" looks like this: // when the user hits return, send the "text-entered" // message to main.js. // the message payload is the contents of the edit box. var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline. text = textarea.value.replace(/(\r\n|\n|\r)/gm,""); self.port.emit("text-entered", text); textarea.value = ''; } }, false); // listen for the "show" event being sent from the // main add-on code. it means that the panel's about // to be shown. // // set the focus to the text area so the user can // just start typing. self.port.on("show", function ...
Getting started (cfx) - Archive of obsolete content
you'll see some output like this: * lib directory created * data directory created * test directory created * doc directory created * readme.md written * package.json written * test/test-main.js written * lib/main.js written * doc/main.md written your sample add-on is now ready for testing: try "cfx test" and then "cfx run". ...
...d written * package.json written * test/test-main.js written * lib/main.js written * doc/main.md written your sample add-on is now ready for testing: try "cfx test" and then "cfx run". have fun!" implementing the add-on now you can write the add-on's code, which goes in the "main.js" file in your "lib" directory. this file was created for you in the previous step. open it and add the following code: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://www.mozilla.org/"); } save the file. next, save these th...
...it to initialize an empty add-on template cfx run to run a new instance of firefox with the add-on installed, so we can try it out cfx xpi to package the add-on into an xpi file for distribution these are the three main commands you'll use when developing sdk add-ons. there's comprehensive reference documentation covering all the commands you can use and all the options they take. the add-on code itself uses two sdk modules, action button and tabs. there's reference documentation for all the high-level and low-level apis in the sdk. what's next? to get a feel for some of the things you can do with the sdk apis, try working through some of the tutorials. advanced techniques overriding the built-in modules the sdk modules you use to implement your add-on are built into firefox. when yo...
...e the extension auto-installer add-on: this listens for new xpi files on a specified port and installs them automatically. that way you can test new changes without needing to restart the browser: make a change to your add-on run cfx xpi post the add-on to the port specified you could even automate this workflow with a simple script. for example: while true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run. this means that if you want to see output from console.log() messages, you'll have to tweak a setting. see the documentation on logging levels for the details on this. another example usi...
Downloading Files - Archive of obsolete content
rowserpersist;1", "nsiwebbrowserpersist"); var persist = webbrowserpersist(); // obtain the privacy context of the browser window that the url // we are downloading comes from. if, and only if, the url is not // related to a window, null should be used instead. ...
... "nsiwebbrowserpersist"); var persist = webbrowserpersist(); // obtain the privacy context of the browser window that the url // we are downloading comes from. if, and only if, the url is not // related to a window, null should be used instead. ...
... be used instead. ...
...rdcodedpassword = "foobar"; persist.progresslistener = { queryinterface: xpcomutils.generateqi(["nsiauthprompt"]), // implements nsiauthprompt prompt: function(dialogtitle, text, passwordrealm, savepassword, defaulttext, result) { result.value = hardcodedpassword; return true; }, promptpassword: function(dialogtitle, text, passwordrealm, savepassword, pwd) { pwd.value = hardcodedpassword; return true; }, promptusernameandpassword: function(dialogtitle, text, passwordrealm, savepassword, user, pwd) { user.value = hardcodedusername; pwd.value = hardcodedpassword; return true; } }; persist.saveuri(urltosave, null, null, null, "", nsfileinstance, privacy); the above is going to give you errors about missing nsidownloadprogresslistener methods, so you...
On page load - Archive of obsolete content
progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. progress listeners implement the nsiwebprogresslistener interface. ...
...ail if(messagepane){ messagepane.addeventlistener("load", function(event) { myextension.onpageload(event); }, true); } }, onpageload: function(aevent) { var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a location object (see below for a link). // you can use it to make your code executed on certain pages only. if(doc.location.href.search("forum") > -1) alert("a forum page is loaded"); // add event listener for page unload aevent.originaltarget.defaultview.addeventlistener("unload", function(event){ myextension.onpageunload(event); }, true); }, onpageunload: function(aevent) { // do something } }; current firefox trunk nightlies will fire t...
...ddeventlistener("unload", function(event){ myextension.onpageunload(event); }, true); }, onpageunload: function(aevent) { // do something } }; current firefox trunk nightlies will fire the onpageload function for not only documents, but xul:images (favicons in tabbrowser). if you only want to handle documents, ensure aevent.originaltarget.nodename == "#document" . ...
...event); }, true); }, onpageunload: function(aevent) { // do something } }; current firefox trunk nightlies will fire the onpageload function for not only documents, but xul:images (favicons in tabbrowser). if you only want to handle documents, ensure aevent.originaltarget.nodename == "#document" . if you are running code on a page load it is likely you would want to run some cleanup code on page unload. to attach to the unload event in above example you can use the "pagehide" event like this: appcontent.addeventlistener("pagehide", myextension.onpageunload, false); for appcontent and similarly for messagepane messagepane.addeventlistener("pagehide", myextension.onpageunload, false); and add your code to onpageunload method. basic onpageload for a browser window var mye...
Downloading JSON and JavaScript in extensions - Archive of obsolete content
a common practice found in many extensions is using xmlhttprequest (or some other mechanism) to download javascript or json (they are different) from a remote website. once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into javascript objects. this practice is dangerous and will not, in fact, pass an amo review. so the extension will not be allowed to move out of the amo sandbox. the practice is dangerous because the decoded javascript has full chrome privileges and could perform some nasty actions. how could the javascript an extension downloads perform nasty actions? fairly easy if the webserver where the javascript is hosted were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriou...
...d were to be hijacked or compromised. it happens to the best of us. amo takes the threat very seriously. the good news is there are several ways to workaround the problem. downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all. json is about state and does not allow functions to be decoded. the json decoding methods available to extension developers protect the extension from malicious json and javascript. downloading state from a remote webserver using json is becoming extremely popular. use the json decoders, not eval()! downloading javascript of course there are times when javascript code modules are downloaded and injected into the extension. this usually happens because the...
... extension developers protect the extension from malicious json and javascript. downloading state from a remote webserver using json is becoming extremely popular. use the json decoders, not eval()! ...
...lly happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change. in this case, javascript sandboxing should be used to isolate the downloaded javascript from the rest of the extension, and host application. sandboxing is done using components.utils.evalinsandbox(). the javascript code is added to the sandbox along with any "safe" objects the javascript needs to interact. sandboxing is not without its dangers and developers should read the sandboxing page carefully to make sure untrusted code is not leaked out of the sandbox. ...
Extension Etiquette - Archive of obsolete content
nsion lighter, while providing more consistency, especially for users using different themes. extension icons unique icons are usually worth their download weight. they allow for easy identification among other extensions in the extensions manager. coding practices namespace conflicts there are many namespaces which extensions often must share with other consumers, be they other add-ons, web code, or the browser itself. these often include areas such as: object prototypes, such as string.prototype, which are often extended to add methods to native objects. global variables, such as top-level declarations on scripts loaded into shared windows or web pages. expando properties of shared objects, such as document objects, or dom nodes. ids and class names in html and xul documents, when...
...to web pages or browser windows. chrome: or resource: packages, which are often defined in chrome.manifest files. about: page urls. xpcom contract ids, which are often registered in chrome.manifest files. while these are among the most common examples of namespaces in which conflicts can occur, there are many others. in general, care must be taken whenever defining a name anywhere that other code might do likewise. strategies to avoid such conflicts include: avoid shared namespaces where possible many naming conflicts are best avoided by simply not sharing namespaces. scripts can be loaded into their own globals, such as commonjs modules, javascript modules, or sandboxes, to avoid most global variable and prototype conflicts. expando properties are best avoided using tools such as wea...
...les might all be defined as properties of the coolbeans object. some namespaces have specific conflict prevention conventions, which should be followed as appropriate. xpcom contract ids, for instance, should always begin with an @, followed by a domain name that the author controls, e.g., "@example.com/foo/bar;1" it is important that the prefix that you use be unlikely to conflict with other code, and that it be indicative of the name of your add-on. generic prefixes such as myextension-, or short prefixes such as ffx-, are likely to be used elsewhere, and therefore unsuitable to the purpose. call .noconflict(true) where applicable many common libraries which create global variables provide a method called noconflict, or similar, which revert any global variables they've declared, a...
... variables provide a method called noconflict, or similar, which revert any global variables they've declared, and return the object itself. for instance, calling jquery.noconflict(true) will remove the window.jquery and window.$ variables, and return the jquery object itself, for future use by the caller. when available, these methods should always be used to prevent conflicts with third-party code. names and metadata naming be creative! don't be redundant and include "extension," "mozilla/firefox/thunderbird," or the version number in the name. be original! descriptions use something that is descriptive, but that would fit in the default add-on manager width. the mozilla extensions (inspector/reporter/talkback) believe starting with a verb is the best way. for example, "does an act...
Adding menus and submenus - Archive of obsolete content
r. the menubar element should be a child of a toolbox element because it is treated like another toolbar on systems other than mac os x. mac os x treats menus in a very different way than other systems. if your extension involves menus in any way, you should test it on mac os x to make sure everything works adequately. ...
...the separator is usually displayed as a horizontal line that creates a logical division between different types of menuitem elements, keeping everything more organized. a menubar can hold one or more menu elements. menus require a menupopup element as a contai...
...fill its contents. we'll look into some asynchronous techniques further ahead in the tutorial. adding elements to existing menus just as explained in the previous sections, the best place to overlay your extension menu is inside the tools menu. that is, unless there's a place inside the menu structure where your extension menus make more sense. if you're overlaying the tools menu, your overlay code should have something like this: <menupopup id="menu_toolspopup"> <menu id="xulschoolhello-hello-menu" label="&xulschoolhello.hello.label;" accesskey="&xulschoolhello.hellomenu.accesskey;" insertafter="javascriptconsole,devtoolsseparator"> <menupopup> <!-- your menuitem goes here. --> </menupopup> </menu> </menupopup> now let's look at some specialized types of menu i...
...l="&xulschoolhello.greet.medium.label;" /> <menuitem type="radio" name="xulschoolhello-greeting-radio" label="&xulschoolhello.greet.long.label;" /> </menupopup> this is a modified version of the 3 greeting menus. it is now implemented as a radio menu where you pick one of the 3 available choices. the first one is checked by default. the oncommand attribute is set on the menupopup to avoid code duplication, since now the 3 items call the same function. another example of a menu like this is the view > sidebars menu. only one sidebar is visible at any given moment, and you can pick from several. menus with images to add an icon to a menu or menuitem, set its class to "menu-iconic" or "menuitem-iconic" respectively, and set the image attribute or the list-style-image css property. menu...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
add-ons normally run code at startup, and as it is covered in the main tutorial, all you need is a load event handler and a little code. it is also common for an add-on to require to run a script only when it is installed for the first time, or every time it is updated. it can be used to write or copy necessary files to the profile folder, like the initial db the add-on will use for storage. a few others require cleanup code to be run after the add-on is uninstalled. this appendix covers these cases with simple code that should work for most add-ons. install scripts just like with a regular initialization function, we want a load event handler: // rest of overlay code goes here. window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); then all ...
...the best approach in this case is to use a preference, as explained in the handling preferences section. ...
...proach in this case is to use a preference, as explained in the handling preferences section. so, if we were to use fuel, we can do the following in the init function: init : function() { let firstrunpref = "extensions.xulschoolhello.firstrundone"; if (!application.prefs.getvalue(firstrunpref, false)) { application.prefs.setvalue(firstrunpref, true); // all the rest of the first run code goes here. } } in this case you would need to declare the first run preference in your default preferences file, with a default value of false. you should also change the preference value before you run any other first run code. keep in mind that the user could have set multiple firefox windows to open at startup, so there's a race condition on which window will run the first run code. if you...
... } } in this case you would need to declare the first run preference in your default preferences file, with a default value of false. you should also change the preference value before you run any other first run code. keep in mind that the user could have set multiple firefox windows to open at startup, so there's a race condition on which window will run the first run code. if you need to run code on every update, or some of them, the code would be very similar. instead of a boolean preference, it would be best to use a string preference with the last-installed add-on version. and then do a version comparison to decide which code to run. the current version number can be hard-coded in the first run function, or you can use the add-on manager to dynamically get it. this can get tricky with ...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
it is safe, though inefficient, to assign dynamic values to innerhtml if any dynamic content in the value is escaped with the following function: function escapehtml(str) { return str.replace(/[&"'<>]/g, (m) => ({ "&": "&amp;", '"': "&quot;", "'": "&#39;", "<": "&lt;", ">": "&gt;" })[m]); } or slightly more verbose, but slightly more efficient: function escapehtml(str) { return str.repl...
...>": "&gt;" }; note that quotation marks must be escaped in order to prevent fragments escaping attribute values. var href = "http://www.google.com/"; var text = "google"; document.getelementbyid("target-div").innerhtml = '<div>\ <a href="' + escapehtml(href) + '" target="_top">' + escapehtml(text) + '</a>\ </div>' it needs to be stressed that this method should not be used in new code and is only a temporary measure to shore up legacy code bases. safely generating event listeners and scripts it is occasionally necessary to generate event listeners and script fragments from dynamic content. great care must be taken in these situations. under no circumstances should code resembling 'callback("' + str + '")' appear anywhere in your add-on. closures by far the best way to crea...
...safely generating event listeners and scripts it is occasionally necessary to generate event listeners and script fragments from dynamic content. great care must be taken in these situations. under no circumstances should code resembling 'callback("' + str + '")' appear anywhere in your add-on. closures by far the best way to create dynamic event listeners is to use closures. the following two code fragments are roughly equivalent: function clickify(elem, address) { elem.addeventlistener("click", function (event) { openwindow(address) }, false); } function clickify(elem, address) { elem.onclick = function (event) { openwindow(address) }; } multiple attributes sometimes there is a need for event listeners to appear as attributes in the dom. in these cases, multiple attributes sh...
...on (event) { openwindow(address) }; } multiple attributes sometimes there is a need for event listeners to appear as attributes in the dom. in these cases, multiple attributes should be used, one for each variable: function clickify(elem, address) { elem.setattribute("href", address); elem.setattribute("onclick", "openwindow(this.getattribute('href'))"); } escaping functions when the code fragment in question is not an event handler attribute and there is no feasible way to pass the data through other means, they must be escaped with functions such as uneval, string.quote, json.stringify, or number. generating scripts in this matter is deprecated and should be avoided wherever possible, but is relatively safe and sometimes acceptable. function createscript(href, otherstuff) { ...
Mozilla Documentation Roadmap - Archive of obsolete content
t guidelines, accessibility, usability, best practices... the list goes on. it's incredibly comprehensive, and its underlying wiki technology makes it easy to expand and evolve with the help of the community. having said that, there are a few problems with it. first of all, the in-site search is not reliable, so we recommend using a search engine like google, with queries such as "mdc javascript code modules" or "javascript code modules site:developer.mozilla.org". secondly, there are several important articles that are very lacking in information, like the preferences system page. and finally, what we mentioned in our xpcom section: almost no documentation on xpcom components. the documentation on interfaces is very complete, but it isn't nearly as useful as the documentation that existed at...
...have them answered by experienced developers. it also includes discussions on add-on monetization, job postings and a long list of add-on ideas waiting to be developed. the mozilla source sometimes you need more than just a tutorial. there are various tricks that you can't learn anywhere, but you know that firefox implements them in some way. in these cases you should dive into mozilla's source code and try to locate the code you need. one way to do this is to look into your firefox installation directory, maybe unpack a few jars and see what's inside. but this is very awkward and limited. it would be much better to be able to search and navigate through the huge code base with some ease. luckily, mozilla provides exactly that in the mozilla cross-reference. the main index in this page give...
...he main index in this page gives you options to look into the different product branches in development at mozilla. make sure you pick the one that matches your target versions. all of these provide advanced search capabilities, including regular expression search and file path search. you'll be able to navigate the full source tree, inspect the change history for all files, and link to specific code lines. it takes a little getting used to, specially learning how to choose the best search queries, but it's an invaluable resource of information. mozilla blogs several mozilla community members maintain blogs that are updated frequently, often including information on api changes, bug fixes, useful tools and future release plans. many of the tips and tricks included in this tutorial were disc...
...comes in handy for reading and posting to the newsgroups. another advantage is that discussions are archived and searchable through google groups. other and finally, a couple resources you should also keep in mind: other extensions. there are thousands of extensions out there, and you may strike luck and find one that does exactly what you need. be sure to look at the license the extension's code is released with before thinking about copying large sections of it. also, remember to give credit when it's due. mozilla's bugzilla repository. pretty much every code change done in firefox and mozilla projects is documented in this huge tracking database. but this also means that finding exactly what you need can be time-consuming, and often fruitless. the advanced search is very useful in fil...
Session store API - Archive of obsolete content
red. you can determine which tab is being restored by looking at the event's originaltarget field. there's not really a way to determine when the last tab has been restored unless you determine how many tabs need to be restored then count the sstabrestored events. this section provides a few simple examples of how to make use of the session store api. saving a value with a tab the following code will attach a key/value pair to a tab, so that when the tab is restored, that pair is still associated with it. var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var datatoattach = "i want to attach this"; ss.settabvalue(currenttab, "key-name-here", datatoattach); this...
...will attach a key/value pair to a tab, so that when the tab is restored, that pair is still associated with it. ...
...enttab = gbrowser.selectedtab; var datatoattach = "i want to attach this"; ss.settabvalue(currenttab, "key-name-here", datatoattach); this code sets the value of the key "key-name-here" to datatoattach. you may use any javascript object as the data. fetching a saved value you can fetch a value associated with a tab at any time (whether the tab is in the process of being restored or not), using code similar to the following: var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var retrieveddata = ss.gettabvalue(currenttab, "key-name-here"); after this code executes, the variable retrieveddata contains the value saved for the key "key-name-here". retrieveddata is unde...
...ts.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var retrieveddata = ss.gettabvalue(currenttab, "key-name-here"); after this code executes, the variable retrieveddata contains the value saved for the key "key-name-here". retrieveddata is undefined if there is no value saved for that key name. deleting a value associated with a tab to delete a value from a tab, you can use code similar to the following: var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; ss.deletetabvalue(currenttab, "key-name-here"); remarks the window value save and restore functions work exactly like the tab-based functions by similar names. starting in firefox 3.5, notifi...
Updating addons broken by private browsing changes - Archive of obsolete content
after reading this document, contact josh matthews with further questions or clarifications, or file a bug if your extension has stopped working due to a change described here and you are having trouble updating it. ...
...d by these changes? ...
... idls nsitransferab...
...ke an optional boolean parameter to indicate whether the identity is classified as private. nsistricttransportsecurityservice: processstsheader, removestsstate, isstshost, and isstsuri now take a flags parameter that understands nsisocketprovider.no_permanent_storage or nothing. nsiprivatebrowsingservice: this service is deprecated, and as of firefox 20 it is now an empty interface. if your code depends on this interface, it will break. the global private browsing service is actively being removed, and may not even exist as of firefox 21. nsirecentbadcertsservice: this is no longer a global service, and has been renamed to nsirecentbadcerts. to obtain this, acquire the nsix509certdb service, and use the new getrecentbadcerts method, passing a boolean indicating whether the private bad c...
Using Dependent Libraries In Extension Components - Archive of obsolete content
ther shared libraries (for example, libraries provided by a third party). the firefox extension system does not provide automatic support for loading these dependent libraries, but it is possible to load these libraries explicitly using a component stub. the basic strategy of the stub is to dynamically load the dependent libraries, then load the component library and continue registration. sample code is below, and can be built by placing the two files in extensions/stub and configuring with --enable-extensions=stub extension file structure using the stub slightly changes how components are packaged in the extension directory structure. note that the "real" component is no longer in the components/ directory, it is in the libraries/ directory. extension-directory/install.rdf extension-director...
... dependant libraries on the mac must be loaded with a special system function nsaddimage() with the flag nsaddimage_option_match_filename_by_installname. the following are the necessary modifications you will need in order to write a stub loader for an os x extension. you will also need to make sure you are properly linking the xpcom glue libraries. se...
...n nsaddimage() with the flag nsaddimage_option_match_filename_by_installname. the following are the necessary modifications you will need in order to write a stub loader for an os x extension. you will also need to make sure you are properly linking the xpcom glue libraries. see xpcom glue for the proper flags on how to link to the glue libraries. /* * os x stubloader * original stubloader code by benjamin smedberg <benjamin@smedbergs.us> copyright (c) 2005 * adapted for os x by walter johnson <zinkyu@gmail.com>, sept. 2008 */ //include the stuff from mozilla glue that we need #include "nsilocalfile.h" #include "nsstringapi.h" #include "nscomptr.h" //include things from the mach-o libraries that we need for loading the libraries. #include <mach-o/loader.h> #include <mach-o/dyld.h> ...
...uelinkingosx.cpp . // deprecated api calls have been removed. static void* lookupsymbol(const mach_header* alib, const char* asymbolname) { nssymbol sym = nsnull; if (alib) { sym = nslookupsymbolinimage(alib, asymbolname, nslookupsymbolinimage_option_bind | nslookupsymbolinimage_option_return_on_error); } if (!sym) return nsnull; return nsaddressofsymbol(sym); } notes code samples are licensed under the mit license. this code only works on firefox 1.5 and later. as written it uses only frozen apis. os x code was built using the 10.4 universal sdk. ...
Search Extension Tutorial (Draft) - Archive of obsolete content
save the original values. var savedprefs = {} // change the default value of the preference *name* to *value*. // a default for this preference must exist, and it must be a // character preference. function setpref(name, value, localized) { // 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) == va...
...and 2) setting it as a default (and restoring the previous default when your extension is uninstalled). adding a new search engine search engines may be added either directly via an api call, or indirectly via an xml description file. while the former is the simpler method, it does not support complex descriptions containing suggestion urls or separate keyword search urls. note: example uninstall code is only provided for restartless extensions. a separate tutorial exists for running code at uninstall in non-restartless extensions. an example bootstrap.js file illustrating the simple method follows: const { classes: cc, interfaces: ci, utils: cu, results: cr } = components; // import the services module. cu.import("resource://gre/modules/services.jsm"); // the details of the engine to add co...
... } } function install() {} function uninstall() {} the complex method requires two files, an xml search description file and a javascript file to register the engine. in non-restartless extensions, the xml search description may instead simply be placed in the searchplugins/ directory in the root of your xpi, as em:unpack is specified in your install.rdf file. as above, install and uninstall code is only provided for restartless add-ons but can be adapted for traditional add-ons. search.xml <?xml version="1.0" encoding="utf-8"?> <searchplugin xmlns="http://www.mozilla.org/2006/browser/search/"> <shortname>example engine</shortname> <description>example search engine</description> <inputencoding>utf-8</inputencoding> <image width="16" height="16" type="image/png">data:image...
... ...
Add-ons - Archive of obsolete content
, html, and css, to create the add-ons. the sdk includes javascript apis, which you can use to create add-ons and tools for creating, running, testing, and packaging add-ons. bookmarks.export() exports bookmarks to an html bookmark file. bookmarks.import() imports bookmarks from an html bookmark file. bootstrapped extensions browser.bookmarks.export( function() {...} // optional function ) code snippets … creating custom firefox extensions with the mozilla build system there is a wealth of material on creating extensions for firefox. all of these documents currently assume, however, that you are developing your extension using xul and javascript only. for complex extensions, it may be necessary to create components in c++ that provide additional functionality. extension etiquette ...
...arting with seamonkey 2 alpha 1 seamonkey supports toolkit/-style extensions. these type of extensions have many advantages for both users and developers compared to the old xpinstall/-style extensions. firefox addons developer guide the original document is in japanese and distributed via the xuldev.org website. so there may be still some reference to the xuldev website (we want to host source code on mdc, not on xuldev), and to japanese things (like some specific locales, which have been translated to french since non-latin characters are not well supported). hotfix extension this document has been moved to the add-ons wiki. how to convert an overlay extension to restartless first off, what kind of add-on are we talking about here? well, xul overlays and windows, jsm files, chrome & re...
...ntifying the add-on, providing information about who created it, where more information can be found about it, which versions of what applications it is compatible with, how it should be updated, and so on. interaction between privileged and non-privileged pages an easy way to send data from a web page to an extension is by using custom dom events. in your extension's browser.xul overlay, write code which listens for a custom dom event. here we call the event myextensionevent. legacy add-ons this section contains links to documentation for legacy technology for add-on development, including: legacy extensions for firefox for android add-ons that work with desktop firefox do not automatically work in firefox for android: overlay extensions this page contains links to documentation for t...
...ot 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 you should be inserting your own code. techniques … ...
Install.js - Archive of obsolete content
different sample install.js template located at http://downloads.mozdev.org/xsidebar/mods/. this version has been developed as part of the effort to port firefox extensions to seamonkey from the xsidebar project. pros: this version consolidates all the changable information at the top of the file. and it also knows how to install packaged components, search engines and default preferences. cons: code is bloated since it has to cater for several different ways an extension author can package the .jar file contained in the .xpi file. xpi file structure you can use the code below (taken from pike's extensions ). it assumes the following structure of your xpi file: sampleext.xpi chrome\ sampleext.jar content\ sampleext\ locale\ (optional) en-us\ sa...
...cture you can use the code below (taken from pike's extensions ). it assumes the following structure of your xpi file: sampleext.xpi chrome\ sampleext.jar content\ sampleext\ locale\ (optional) en-us\ sampleext\ ... skin\ (optional) classic\ sampleext\ ... ...
...t assumes the following structure of your xpi file: sampleext.xpi chrome\ sampleext.jar content\ sampleext\ locale\ (optional) en-us\ sampleext\ ... skin\ (optional) classic\ sampleext\ ... install.js install.rdf (optional -- see above) code // install.js // xpiinstaller // by pike (heavily inspired by code from henrik gemal and stephen clavering) var xpiinstaller = { // --- editable items begin --- extfullname: 'sample extension', // the name displayed to the user (don't include the version) extshortname: 'sampleext', // the leafname of the jar file (without the .jar part) extversion: '1.0', extauthor: 'insert-your-name-here', extlocalenames: null, // e.g. ['en-us', 'en-gb'] extskinnames: n...
...tement instead var args = install.arguments; if (args == 'p=0') { this.profileinstall = false; this.silentinstall = true; } else if (args == 'p=1') { this.profileinstall = true; this.silentinstall = true; } }, handleerror: function(err) { if (!this.silentinstall) { install.alert('error: could not install ' + this.extfullname + ' ' + this.extversion + ' (error code: ' + err + ')'); } install.cancelinstall(err); } }; xpiinstaller.install(); ...
Monitoring WiFi access points - Archive of obsolete content
this capability was introduced primarily to allow wifi-based location services to be used by geolocation services. example this example simply displays a list of the available access points. ...
...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 itera...
...onents.interfaces.nsiwifimonitor); wifi_service.startwatching(listener); </script> </head> <body> <div id="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 refr...
...versalxpconnect 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 access points to start monitoring the access points, we instantiate the listener (on line 44), then get access to the wifi monitor interface on line 45. the monitoring is started up on line 47, by calling the wifi monitoring service's startwatching() method. ...
Enabling the behavior - updating the status periodically - Archive of obsolete content
function loadtinderboxstatus() { gxmlhttprequest = new xmlhttprequest(); gxmlhttprequest.onload = updatetinderboxstatus; gxmlhttprequest.open("get", "http://tinderbox.mozilla.org/seamonkey/panel.html"); gxmlhttprequest.send(null); window.settimeout(loadtinderboxstatus, 60000); } window.settimeout(loadtinderboxstatus, 1000); window.settimeout schedules functions to run at some future time. we use it inside the loadtinderboxstatus function to make that function run a second (1,000 milliseconds) after startup and a minute (60,000 milliseconds) after each invocation. ...
... window.settimeout schedules functions to run at some future time. we use it inside the loadtinderboxstatus function to make that function run a second (1,000 milliseconds) after startup and a minute (60,000 milliseconds) after each invocation. this allows users to get relatively frequent updates about tinderbox without overloading the tinderbox server or slowing down mozilla with requests. ...
... run a second (1,000 milliseconds) after startup and a minute (60,000 milliseconds) after each invocation. this allows users to get relatively frequent updates about tinderbox without overloading the tinderbox server or slowing down mozilla with requests. our code is now ready to run, but mozilla doesn't know about it yet. to enable its functionality, we have to add a reference to our javascript code into navigator.xul, just as we put a reference to our css code into that file back in specifying the appearance. put the javascript code into a file called tinderstatus.js in the same directory as navigator.xul and reference it in navigator.xul where other javascript scripts are referenced: ... <!-- navigator --> <script type="application/javascript" src="chrome://navigator/content/browse...
...to confirm this state, go to tinderbox and verify that the panel displays the current worst state of active tinderbox clients. « previousnext » ...
Making it into a static overlay - Archive of obsolete content
now that we have a working mozilla extension that shows tinderbox status, we need to make it distributable to other users. the two ways of doing that are to integrate it into the mozilla codebase (in which case it is no longer an extension but rather part of the default mozilla distribution) and to package it into an installer that users can run from within mozilla to add the extension to their mozilla installation. most extensions are distributed as installer packages, and that's how we'll distribute our extension. integrating extensions into the mozilla codebase is beyond the scope of this tutorial, but for more information see mozilla.org's hacking documentation. mozilla installer packages are called xpis (pronounced "zippies"), which stands for cross-platform installer. the package...
... a xul file via a reference at the top of the file (much like stylesheets and javascript scripts). dynamic overlays are added to a xul file via a reference in the chrome registry. ...
...a reference in the chrome registry. overlays provide a way to break up a large xul file into several different files (one that describes the overall structure of an application window and the others to implement specific portions of the window) to improve code readability, maintainability, and extensability. dynamic overlays also make it possible to modify a xul file without actually changing the code of the file itself, which is necessary when installing an extension like ours. ...
...dow) to improve code readability, maintainability, and extensability. dynamic overlays also make it possible to modify a xul file without actually changing the code of the file itself, which is necessary when installing an extension like ours. we'll first make the file into a static overlay, then we'll make it into a dynamic overlay. ...
Creating a Microsummary - Archive of obsolete content
displays the current firefox download count along with the label fx downloads; for example: 174475447 fx downloads. we'll build the xslt transform sheet that converts that page into its microsummary, learn how to specify that the generator applies to that page, and find out how to make the generator available for download and installation. in each step of revising the transform sheet and other code in this tutorial, new material added will be shown in boldface so you can follow along more easily. note: if you are a web site developer, and you want to create microsummaries for pages on your site, you can write generators to do so, but a simpler and more efficient approach is to create the microsummaries on the server-side using the same tools and languages you already use to generate pages.
...re easily. note: if you are a web site developer, and you want to create microsummaries for pages on your site, you can write generators to do so, but a simpler and more efficient approach is to create the microsummaries on the server-side using the same tools and languages you already use to generate pages. for example, if you use php scripts to generate pages on your site, you could write php code to output a microsummary when the view=microsummary url parameter is present. then just link to the microsummaries from within the pages themselves using a <link rel="microsummary"> element, f.e.: <head> <link rel="microsummary" href="index.php?view=microsummary"> </head> when firefox encounters a <link rel="microsummary"> element, it loads the url in the href attribute. if the url points to...
...then create a javascript link on some web page that calls firefox's window.sidebar.addmicrosummarygenerator() method to download and install the generator. ...
...utorial/sfx-generator.xml')">install the spread firefox home page microsummary!</button> clicking that button will generate a javascript error on browsers that don't support microsummaries, however, so to improve the experience for those users, we should check to see if the user is using a microsummaries-enabled browser and display an explanatory message if not. ...
In-Depth - Archive of obsolete content
do i know where everything is? well there is an easy way to find out - using the dom inspector. if you didn't install it when you first installed mozilla you may have to run the installer again. load mozilla and one browser window. then open the dom inspector (tools->web development->dom inspector). click file->inspect and select the browser window. what appears in a tree view below is the actual code for the interface. using this, we can figure out what objects are where, what classes/id's they have applied to them, and most importantly, which file the style is located in. click on the inspect icon and then click on the back button in the browser window. what this will do is find the code for the back button and display it in the dom inspector. selected in the tree view will be xul:toolbarbu...
...ed with some xbl hacking. place this xml file in \classic\skin\classic\communicator\toolbar\toolbarbindings.xml (you will need to create the sub directory). what this file does, is it takes the standard toolbar that is used in mozilla and adds an image to the one side of it. if you look at the modern skin, you'll notice that it adds the image to the other side of the toolbar. now that we have the code that will change the toolbar, it needs to be accessed. open up \classic\skin\classic\communicator\communicator.css and look for the .toolbar-primary section. there is a -moz-binding command there. point the url to the new location. change: -moz-binding: url("chrome://global/content/bindings/toolbar.xml#toolbar-primary"); to -moz-binding: url("chrome://communicator/skin/toolbar/toolbarbindings.xm...
...location. change: -moz-binding: url("chrome://global/content/bindings/toolbar.xml#toolbar-primary"); to -moz-binding: url("chrome://communicator/skin/toolbar/toolbarbindings.xml#toolbar-primary"); now every toolbar has a spot for an image on the right hand side and we can start adding images, but first we need to make sure we can see the images that we add. also in the communicator.css add this code: .toolbar-primary-icon { width: 100px; background-repeat: no-repeat; background-position: top; } open up \classic\skin\classic\navigator\navigator.css and scroll down to the bottom. to style that image, we first need to get a handle to the toolbar, then the box inside of it, and then to the image that we added with the xml. by hunting around with the dom inspector and looking at the naviga...
...e to the toolbar, then the box inside of it, and then to the image that we added with the xml. by hunting around with the dom inspector and looking at the navigation toolbar you can find this information. the id is "navigation-toolbar". then it contains a xul:hbox with the class .toolbar-holder. this .toolbar-holder class is also defined in the toolbarbindings.xml. this is where mozilla takes the code out of our xml file and puts the two together. inside of the xml file there is an image which has its class set to toolbar-primary-icon. note: in versions of firefox prior to firefox 3 beta 3, the navigation toolbar's id is "nav-bar". put these 3 together and you get: #navigation-toolbar > .toolbar-holder > .toolbar-primary-icon inside this section of the css is where you add an image. set the b...
Using Dehydra - Archive of obsolete content
as gcc compiles file, dehydra calls functions in the user analysis script with information about the code being compiled. for more information, see the function reference and the object reference. ...
... as gcc compiles file, dehydra calls functions in the user analysis script with information about the code being compiled. for more information, see the function reference and the object reference. ...
... */ function isfinal(c) { if (!c.attributes) return false; for each (let a in c.at...
... return false; } function process_type(t) { if (t.bases) for each (let base in t.bases) if (isfinal(base.type)) error("class " + t.name + " extends final class " + base.type.name, t.loc); } compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/final.js -o/dev/null -c final.cc it should print the following results and return with an error code: final.cc:8: error: class subclass extends final class myclass see documentation for: process_type, error, .bases property, .attributes property ...
Embedding FAQ - Archive of obsolete content
api from mozilla itself. you can get more detailed information on what interfaces are required and which are optional to impelement here. scroll down to "initalization and teardown. how to customize document retrieval one method is to implement your own protocol method. ...
...hat interfaces are required and which are optional to impelement here. scroll down to "initalization and teardown. how to customize document retrieval one method is to implement your own protocol method. you can find more information on adding new protocols here how to embedding mozilla inside of java there hasn't been any good code examples found. however, there is a stripped down, uncommented code with eclipse libraries in this thread. ...
...pelement here. scroll down to "initalization and teardown. how to customize document retrieval one method is to implement your own protocol method. you can find more information on adding new protocols here how to embedding mozilla inside of java there hasn't been any good code examples found. however, there is a stripped down, uncommented code with eclipse libraries in this thread. ...
...you can find a better quality answer repeated and with an example in this newsgroup thread. ...
Message Summary Database - Archive of obsolete content
. nsimsgdatabase the main access point to the summary information is nsimsgdatabase. nsimsgfolder has a method to get the database for a folder. nsimsgdatabase is an abstraction on top of mdb, which is a set of db interfaces. the mdb interfaces are implemented in mork. ...
... the summary information is nsimsgdatabase. nsimsgfolder has a method to get the database for a folder. nsimsgdatabase is an abstraction on top of mdb, which is a set of db interfaces. the mdb interfaces are implemented in mork. mdb is a schema-less db interface, so it's trivial to add new attributes without regenerating the db, and it's trivial for older code to read newer databases, because the code can ignore but maintain the attributes it doesn't know about. if we were to replace mork, we could do it at the mdb level (unlikely, because implementing the mdb interface on top of a different db would be very hard), the nsimsgdatabase level (probably the easiest), or we could invent a whole new database interface and change all the code that uses the nsimsgdatabase interface. message headers th...
...so the db knows which messages are in a thread, which message a message is in reply to, etc. ...
...er db. the bottom line is that we haven't been able to justify the very large cost of doing so because there won't be any benefit to the end-user, at least in the short term. here are some of the trade-offs: the mork file format is ascii text, but unreadable. if it were binary, there would be less complaints, and it would be smaller. the mdb interfaces are overly complex, and unfamiliar. the mork code uses a lot of terminology of its own invention, as near as i can tell (though i suspect most db code would be that way). it's difficult to fix bugs in mork. but, on the other hand, there are very few bugs in the mork code. mork loads the whole database in memory, and keeps it there. this makes it very fast to access our database objects, but it does increase memory usage. mork assumes the caller ...
LIR - Archive of obsolete content
in nanojit, lir is the source language for compilation to machine code. lir stands for low-level intermediate representation. it is a typed assembly language. the lir instruction set is best learnt by reading nanojit/liropcode.tbl. code for manipulating lir is in nanojit/lir.h. nanojit lir instruction cheat sheet.also in pdf format see attachment. category op code code name return type featured description miscellaneous 0 start void start of a fragment 1 regfence void a register fence causes no code to be generated, but it affects register allocation so that no registers are live when it is reached. 2 skip void links code chunks. 3 parami integer 32 bit load an int parameter (register or stack location). 4 paramq ...
...all subroutine that returns an int 35 callq quad 64 bit call subroutine that returns a quad 36 calld double call subroutine that returns a double branch 37 j void jump always 38 jt void jump if true 39 jf void jump if false 40 jtbl void jump to address in table 41 label void a jump target (no machine code is emitted for this) 42 not in use guards 43 x void exit always 44 xt void exit if true 45 xf void exit if false 46 xtbl void exit via indirect jump 47 xbarrier void a lir_xbarrier cause no code to be generated, but it acts like a never-taken guard in that it inhibits certain optimisations, such as dead stac...
... 105 cmovi integer conditional move int 106 cmovq quad 64 bit conditional move quad 107 cmovd double conditional move double conversions 108 i2q quad ...
...d 64 bit right shift unsigned quad; 2nd operand is an int 99 negd double negate double 100 addd double add double 101 subd double subtract double 102 muld double multiply double 103 divd double divide double 104 modd double modulo double lir_modd is just a place-holder opcode, ie. the back-ends cannot generate code for it.it's used in tracemonkey briefly but is always demoted to a lir_modl or converted to a function call before nanojit has to do anything serious with it. 105 cmovi integer conditional move int 106 cmovq quad 64 bit conditional move quad 107 cmovd double conditional move double conversions 108 i2q quad 64 bit sign-extend int to quad 10...
Table Cellmap - Archive of obsolete content
further it contains info whether this entry is a row- or colspan. ...
.../tbody> </table> now we have two different rowgroups and and the rowspans can not cross the borders between the different rowgroups. (ref xhtml-2.0). further the table header and footer will be repeated on every page when printed out. due to this behind the cellmap for the table we will find a cellmap for every rowgroup. in this low level cellmap the row count begins every time with 0. ...
...below follows the dump for the 2x2 table. ...
...ried place in the cellmap. this can produce enormous costs once the cellmap contains large holes that are not caused by zero spans, this is at least a o2(n) algorithm. the following routines seem to be hot spots performance wise: nscellmap::colhasspanningcells nscellmap::rowhasspanningcells nscellmap::rowisspannedinto users of nscellmap::getdataat outside nscellmap.cpp the border collapse code relies on the cellmap. the collapsing of rows and columns uses the cellmap. and finally the line iterator methods which are used for arrow navigation through a table. original document information author(s): bernd mielke last updated date: september 27, 2003 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under ...
Mac stub installer - Archive of obsolete content
run the installer from the opt "mozilla installer" folder. ...
... run the installer from the opt "mozilla installer" folder. ...
...older. alternative to steps 3 and 4 copy the "installer modules" folder from the "mozilla installer" folder into the "macbuild" folder that contains the build debug or non-debug installer binary next to miw.mcp. copy the license and readme from the "mozilla installer" folder" to the "macbuild" folder itself. now run the built installer from the "macbuild" itself or by running it from the miw.mcp codewarrior project. how we get setup to debug the xpinstall engine from the mac installer? once you have the mac installer built and ready to debug you may want to debug the xpinstall engine in the context of the installer rather than in the context of the browser. to do this, in addition to the above steps to set up the mac installer to debug you will need to do the following: create a file nam...
... how do i add an installer package to the mac installer? adding a package involves a few steps: add a section named for your <component> to the packages-mac manifest that describes which files from dist belong to which module. for example, see the...
Learn XPI Installer Scripting by Example - Archive of obsolete content
ugh it's possible to rearrange things arbitrarily upon installation--to create new directories, to install files in system folders and other areas. overview of the install script xpi install scripts are written in javascript using xpinstall engine syntax defined in the xpinstall api reference. ...
...xpinstall api reference. most installation scripts, including the one discussed here, take the following basic form (in pseudo-code and with links to the sections in which these installation steps are documented): initinstall(); if (verify_space()) { err = add_dirs_and_files; register_files; if (err==success) { performinstall() }; else { cancelinstall() }; } as you can see in the code listing, the verification process at the top is on lines 1 to 18; the file addition process, here part of the main installation block, is on lines 24 to 41; the registration part of the main installation block is on lines 42-58; and the execution at the end of the main block is on lines 59 to 71. if you choose not to register the installed software or do the verifications at the front end of the ...
...ace()) { err = add_dirs_and_files; register_files; if (err==success) { performinstall() }; else { cancelinstall() }; } in this arrangement, the actual execution of the installation is checked against the errors returned from the addition of files to the installation, which may itself have been conditioned on some verification of version and necessary disk space. ...
...) returned: " + err); } else { cancelinstall(err); logcomment("cancelinstall() due to error: " + err); } } else cancelinstall(insufficient_disk_space); performinstall is the function used to execute the install once it has been initialized and loaded, and it is the last step to installing the software. note that in the example above, the installation is cancelled if the error code from the file addition process returns success (0), and also cancelled outside the main block if the earlier verification process is not successful. note also the comments that indicate the success of various steps in the process--including the performinstall and cancelinstall steps--are written to the install log using the logcomment, described in the following section. installation logging l...
Reading from Files - Archive of obsolete content
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. reading data from a file involves getting a reference to a file and then creating an input stream to read from it. an input stream provides a means of reading bytes, strings or other values from the file. while there is only one method to create an input stream, it provides a n...
...of options to control exactly how reading is performed. for instance, there are options to read a file as if it were text or a binary file. using the former will cause characters in the stream to be interpreted with a particular character encoding. in addition, lines may be read by reading the file up until a linefeed character is detected. a binary stream would be used to read bytes or numbers encoded within the file. to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.newinputstream() to open a stream for reading from it. to learn more about file objects, see files and streams. var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); this example first retrieves a file object using nsiscriptableio.getfile(). in this c...
...n't been read and parsed yet, so the actual number of characters isn't known yet. fortunately as a character is always at least one byte long in the default utf-8 encoding, the number of characters will always be equal to or smaller than the number of bytes available. for normal file streams, the available method will return the total number of bytes left in the file to read. in effect, the above code ends up reading the entire contents of the file into a single string. the available method returns 0 if there is no more data to read, so you could use a loop to read a number of strings. this example keeps reading 10 character strings from a file until there is no more data to read. note that the last string read may be less than ten characters long. while(stream.available()) output += stream.
...file using the utf-16 encoding. var stream = io.newinputstream(file, "text", "utf-16"); this third argument is not needed if the file is stored in utf-8. for a list of supported character encodings, see supported character sets. the files can be read in the same manner using the readstring and readline methods. the difference is handled internally so you don't need to write any other part of the code differently. reading binary data in addition to text, binary values may be read from a file either as bytes, or interpreted as numbers. a number of methods are available which may be used for this. if you are expecting to read from a binary file instead of text, specify the 'binary' flag when creating the stream with nsiscriptableio.newinputstream(). var stream = io.newinputstream(file, "binary")...
MenuItems - Archive of obsolete content
lthough there isn't usually a need to do so, you can also set a custom label for the keyboard shortcut on the menu using the acceltext attribute. you might do this if the key associated with the item changes, for instance a list of open windows displayed on a window menu. <menuitem label="first window" acceltext="1"/> here the keyboard shortcut label will be '1', however you will need to write code to handle the key as well. adding icons to menu items an icon may be added to a menu item using the image attribute. the icon will appear to the left of the menuitem label. in addition to the image, a special class "menuitem-iconic" must be used on the menuitem to indicate that an icon is expected. <menuitem id="add-bookmark" class="menuitem-iconic" label="add bookmark" image="addbookmark.png"...
...<menuitem label="show status bar" accesskey="s" type="checkbox"/> </menupopup> </menu> both menuitems are of the checkbox type. the first menuitem is checked by default, as indicated by the checked attribute set to the value true. the second menuitem is not checked by default. when the user activates the menuitem, the command event gets fired. from within a command listener, you can execute code which will change the state of the toolbar or status bar or whatever it is that need changing. you do not need to update the checked attribute as the menuitem will update this automatically before the command event is fired. note that the checked state is updated before the command event fires, so if you use the menuitem's checked attribute within the command listener, it will already be in the ...
...nuitem is activated. this can be useful if there's a possibility that whatever action is carried out could fail. one possibility is to simply reverse the checkbox state again. as this can be more complicated, it is also possible to use the autocheck attribute to disable this behavior. when the autocheck attribute is set to false, the checkbox state is not updated automatically, and you must write code to adjust the state yourself. <script> function changetoolbarstate(event) { if (event.target.getattribute("checked") == "true") hidetoolbar(); event.target.removeattribute("checked"); } else { if (!showtoolbar()) return; event.target.setattribute("checked", "true"); } } </script> ... <menuitem label="show toolbar" accesskey="t" type="checkbox" autocheck="false" ...
...tattribute("checked", "true"); } } </script> ... <menuitem label="show toolbar" accesskey="t" type="checkbox" autocheck="false" oncommand="changetoolbarstate();"/> this version of the changetoolbarstate function changes the checked attribute itself. the autocheck attribute has been set to false on the menuitem so the 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...
Menus - Archive of obsolete content
ed the menu is opened, listing the commands that are available. the user may select a command to invoke it, or may cancel the operation by pressing escape or clicking outside the menu. xul provides a number of tags for creating menus. these tags can be used to create menus which sit on a menubar or are attached to buttons. submenus may be created by nesting one menu inside of another. no special code needs to be written to open or close a menu or submenu, and, in addition, the menus are placed on screen in the appropriate locations automatically. there are four elements that a menupopup can be attached to. in each case, the menupopup element is placed as a direct child of the element. the following is a brief summary of these elements, examples of each will be provided later. menu the me...
...ubar"> <menu id="file-menu" label="file"> ... </menu> <menu id="tools-menu" label="tools"> ... </menu> <menu id="help-menu" label="help"> ... </menu> </menubar> it's possible to place other elements on a menubar, but remember that they will not appear on a macintosh. so you should ensure that the functionality of these elements is avialable elsewhere. or, you could write code that handles multiple platforms in different ways. if you do place other elements on a menubar, you may wish to align them on the far side rather than next to the other menus. you can do this by adding a flexible spacer. <menubar id="sample-menubar"> <menu id="file-menu" label="file"> ... </menu> <spacer flex="1"/> <image src="logo.png"/> </menubar> in this example, a logo image is...
...and="cmd_open"/> the command attribute should be set to the id of a command element within the same document, in this case 'cmd_open'. the command event will be fired on the command element instead of the menuitem. this is useful when you wish to have several elements performing the same action, for example a menuitem on a menubar, a context menu, and a toolbar button, because you can place the code to execute only once on the command and hook each element up to the command. menuitems also support displaying shortcuts associated with the menuitem, as well as icons beside the label. for details about adding shortcut keys to menus, see adding shortcut keys to menu items. for details about adding icons to menus, see adding icons to menu items. for details about creating checkbox menu items or...
... however, this tends to become more difficult for the user to use, so you should avoid adding too many levels of submenus. sharing menus between windows if you wish to have several windows that share the same menu bar, a common technique is to place the menubar in an overlay and apply it to all of the windows. this allows the menu bar to be shared between each window without having to duplicate code. this technique may be used for individual menus or for an entire menu bar. for example, to have a tools menu that is shared between all windows, just create a menu in the overlay, and include it in each window with a single line: <menu id="menu-tools"/> the overlay should have a menu with the same id 'menu-tools' containing the complete definition of the menu. if you wish to have slight diff...
textbox (Toolkit autocomplete) - Archive of obsolete content
his can be used to display additional items that are not autocomplete results. nomatch type: boolean this attribute will be set to true if the last search resulted in no matches. overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the window object event object exampl...
... note: for firefox 12 and above, this event handler must be set as an initial attribute. onsearc...
...say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> oninput type: script code this event is sent when a user enters text in a textbox. this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchbegin type: script code this event handler is called when the autocomplete search begins. note: for firefox 12 and above, this event handler must be set as an initial attribute. onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the autocomplete search is finished and results are available. note: for firefox 12 and above, this event handler must be...
... event handler must be set as an initial attribute. onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the autocomplete search is finished and results are available. note: for firefox 12 and above, this event handler must be set as an initial attribute. ontextentered new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when a result is selected for the textbox. note: for firefox 12 and above, this event handler must be set as an initial attribute. ontextreverted new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the user presses escape to revert the textbox to its original uncompleted value. note: for firefox 12 and above, this...
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
ents, you can use a number of attributes similar to those for the key element to match a specific key and match only when certain modifer keys are pressed. the previous example could be extended so that the checked property of the check box is changed when the space bar is pressed. <handlers> <handler event="keypress" key=" " action="this.checked=!checked"/> </handlers> you can also use the keycode attribute to check for non-printable keys. the section on keyboard shortcuts provides more information. the modifier keys can be checked by adding a modifiers attribute. this should be set to one of the values set below: alt the user must press the alt key. control the user must press the control key. meta the user must press the meta key. s...
...ust press the meta key. shift the user must press the shift key. accel the user must press the special modifier key that is usually used for keyboard shortcuts on their platform. if set, the handler is only called when the modifier is pressed. you can require multiple modifier keys by separating them with spaces. ...
... special modifier key that is usually used for keyboard shortcuts on their platform. if set, the handler is only called when the modifier is pressed. you can require multiple modifier keys by separating them with spaces. ...
...ded, one for cut, one for copy and the other for paste. each has its own keystroke that invokes it. the first handler is the cut operation and is invoked when the control key is pressed along with the x key. the script within the action attribute is used to cut the text from the textbox and put it into the clipboard field. for simplicity, the entire text is cut and not just the selected text. the code works as follows: this.clipboard=document.getanonymousnodes(this)[0].value; the first element of the anonymous content array is retrieved which gives a reference to the textbox element, which happens to be 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 fiel...
Commands - Archive of obsolete content
ents the command element is used to create commands which can be used to carry out operations. you don't need to use commands, since you can just call a script to handle things. however, a command has the advantage that it can be disabled when needed and can be invoked without needing to know about the details of its implementation. commands provide a suitable way to abstract operations from the code. commands are especially useful for larger applications. for instance, in order to implement the clipboard menu commands, cut, copy and paste, you can use commands. if you did not use commands, you would need to figure out which field has the focus, then check to ensure that the operation is suitable for that element. in addition, the menu commands would need to be enabled and disabled depending...
...ead place it on a command element. the two are then linked using the command attribute, which has the value of the command's id. the result is that when the button is pressed, the command 'cmd_openhelp' is invoked. there are two advantages to using this approach. first, it moves all your operations onto commands which can all be grouped together in one section of the xul file. this means that code is all together and not scattered throughout the ui code. the other advantage is that several buttons or other ui elements can be hooked up to the same command. for instance, you might have a menu item, a toolbar button and a keyboard shortcut all for the same operation. rather than repeat the code three times, you can hook all three up to the same command. normally, you would only hook up eleme...
...if you return false, the command is not handled and command dispatcher will look for another controller. a single controller may support multiple commands. iscommandenabled (command) this method should return true if the command is enabled, or false if it is disabled. corresponding buttons will be disabled automatically. docommand (command) execute the command. this is where you would put the code to handle the command. onevent (event) this method handles an event. example: controller implementation let's assume that we want to implement a listbox that handles the delete command. when the user selects delete from the menu, the listbox deletes the selected row. in this case, you just need to attach a controller to a listbox which will perform the action in its docommand method. try op...
... there is no selection, false is returned. if you delete all the rows in the example, the delete command will become disabled. you may have to click the listbox to update the menu in this simple example. the docommand method will be called when the delete menu item is selected, and this will cause the selected row in the listbox to be deleted. nothing needs to happen for the onevent method, so no code is added for this method. override default controller we attach this controller to the listbox by calling the appendcontroller method of the listbox's controllers. nsicontrollers has a number of methods that may be used to manipulate the controllers. for instance, there is also an insertcontrollerat method which inserts a controller into an element before other ones. this might be useful to ove...
Localization - Archive of obsolete content
that translating the interface into a different language is as simple as possible. usually, a table of strings is created for each language. instead of hard-coding text directly into an application, each piece of text is only a reference into the string table. xml provides entities which can be used for a similar purpose. you should already be familiar with entities if you have written html. the codes &lt; and &gt; are examples of entities which can be used to place less than and greater than signs into the text. xml has a syntax which allows you to declare custom entities. you can use these so that the entity is replaced with its value, which can be a string of text. entities may be used whenever text occurs, including the values of attributes. the example below demonstrates the use of an en...
...ins. inside the archives, you would place the dtd files in which you declare entities. typically, you will have one dtd file for each xul file, usually with the same filename except with a .dtd extension. so, for the find files dialog, we will need a file called findfile.dtd. for non-installed chrome files, you can just put the dtd file in the same directory as the xul file. note: you should encode dtd files as utf-8 for non-ascii characters. that is, you should save them in utf-8 format (without bom). for more information, see mozilla language packs. once you have created a dtd file for your xul, you will need to add a line to the xul file which indicates that you want to use the dtd file. otherwise, errors will occur as it won't be able to find the entities. to do this, add a line of the...
...l;" accesskey="&copycmd.accesskey;"/> <menuitem label="&pastecmd.label;" accesskey="&pastecmd.accesskey;" disabled="true"/> </menupopup> </popupset> <keyset> <key id="cut_cmd" modifiers="accel" key="&cutcmd.commandkey;"/> <key id="copy_cmd" modifiers="accel" key="&copycmd.commandkey;"/> <key id="paste_cmd" modifiers="accel" key="&pastecmd.commandkey;"/> <key id="close_cmd" keycode="vk_escape" oncommand="window.close();"/> </keyset> <vbox flex="1"> <toolbox> <menubar id="findfiles-menubar"> <menu id="file-menu" label="&filemenu.label;" accesskey="&filemenu.accesskey;"> <menupopup id="file-popup"> <menuitem label="&opencmd.label;" accesskey="&opencmd.accesskey;"/> <menuitem label="&savecmd.label;" ac...
...xul file. each entity that was added should be declared in the dtd file. the window will not be displayed if an entity is found in the xul file that hasn't been declared. note that the name of the entity is not important. in the example above, words in entities have been separated with periods. you don't have to do this. the entity names here follow similar conventions as the rest of the mozilla code. you might notice that the text '2520 bytes' has been replaced by two entities. this is because the phrase structure may be different in another locale. for example, the number might need to appear before the equivalent of 'bytes' instead of after. of course, this might need to be more complicated in order to display kb or mb as needed. the access keys and keyboard shortcuts have also been tran...
Tree View Details - Archive of obsolete content
of 2. hasnextsibling: function(idx, after) { var thislevel = this.getlevel(idx); for (var t = after + 1; t < this.visibledata.length; t++) { var nextlevel = this.getlevel(t); if (nextlevel == thislevel) return true; if (nextlevel < thislevel) break; } return false; } the hasnextsibling function needs to return true if there is a row at the same level after a given row. the code above uses a brute force method which simply iterates over the rows looking for one, returning true if a row exists with the same level and false once it finds a row that has a lower level. in this simple example, this method is fine, but a tree with a larger set of data will want to use a more optimal method of determining whether a later sibling exists. opening or closing a row the final func...
...e(idx + i + 1, 0, [toinsert[i], false]); } this.treebox.rowcountchanged(idx + 1, toinsert.length); } this.treebox.invalidaterow(idx); } first we will need to check if the row is a container. if not, the function just returns since non-containers cannot be opened or closed. since the third element in the item array (with an index of 2) holds whether the row is open or not, we use two code paths, the first to close a row and the second to open a row. let's examine each block of code, but let's look at the second block for opening a row first. item[2] = true; var label = this.visibledata[idx][0]; var toinsert = this.childdata[label]; for (var i = 0; i < toinsert.length; i++) { this.visibledata.splice(idx + i + 1, 0, [toinsert[i], false]); } this.treebox.rowcountchanged(idx + 1, ...
...rlying data. the tree will then redraw the tree as needed and the result is that the child rows will appear inside the container. the various other functions implemented above such as getlevel and iscontainer are used by the tree to determine how to draw the tree. the rowcountchanged function takes two arguments, the index where the first row was inserted and the number of rows to insert. ...
...r of rows to insert. in the code above we indicate that the starting row is the value of 'idx' plus one, which will be the first child under the parent. the tree will use this information and add space for the appropriate number of rows and push the rows afterwards down. make sure to pass the right number or the tree might redraw incorrectly or try to draw more rows than necessary. the following code is used to delete rows when a row is closed. item[2] = false; var thislevel = this.getlevel(idx); var deletecount = 0; for (var t = idx + 1; t < this.visibledata.length; t++) { if (this.getlevel(t) > thislevel) deletecount++; else break; } if (deletecount) { this.visibledata.splice(idx + 1, deletecount); this.treebox.rowcountchanged(idx + 1, -deletecount); } first, the item is set clo...
XBL Example - Archive of obsolete content
talpages); return newidx; ]]> </body> </method> this function is called setpage and takes one parameter newidx. the body of the method has been enclosed inside <![cdata[ and ]]>. this is the general mechanism in all xml files that can be used to escape all of the text inside it. that way, you don't have to escape every less-than and greater-than sign inside it. let's break down the code piece by piece. var thedeck=document.getanonymousnodes(this)[0].childnodes[0]; get the first element of the anonymous content array, which will be the vertical box, then get its first child, which will be the deck element. var totalpages=this.childnodes.length; get the number of children that the bound box has. this will give the total number of pages that there are. if (newid...
...the second child of that label element (the horizontal box), and then the second element of that box. the value attribute is changed to read '1 of 3' or something similar. note that one is added to the index because indicies start at 0. constructor we will also need a constructor to initialize the label element so that it displays correctly when the slideshow is first displayed. we use similar code as to the method above to set the page number. the reference to 'this.page' will call the onget script of the page property, which in turn will retrieve the initial page from the selectedindex attribute. <constructor> var totalpages=this.childnodes.length; document.getanonymousnodes(this)[0].childnodes[1].childnodes[1] .setattribute("value",(this.page+1)+" of "+totalpages); </const...
...ed for the previous and next buttons, (say backspace and the enter key). first and last buttons could be added to go to the first and last pages. the label element could be changed to a field where the user could enter the page to go to, or a popup could be added to allow selection of the page from a menu. we could also add a border around the deck with css to make it look a bit nicer. ...
...ous and next buttons, (say backspace and the enter key). first and last buttons could be added to go to the first and last pages. the label element could be changed to a field where the user could enter the page to go to, or a popup could be added to allow selection of the page from a menu. we could also add a border around the deck with css to make it look a bit nicer. ...
MacFAQ - Archive of obsolete content
ton in the top right corner. this button is used to show/hide the toolbar. the toolkit will automatically enable this behavior if you add class="chromeclass-toolbar" to your <toolbar> element. commandline support commandline handlers work great on the mac if it's a cold start. here's how to implement command-line trapping when the app is already running, without getting into appleevents or c++ code. ...
...ur <toolbar> element. commandline support commandline handlers work great on the mac if it's a cold start. here's how to implement command-line trapping when the app is already running, without getting into appleevents or c++ code. this is implemented in a pseudo "hidden window" technique and parsing the window arguments instead of command-line handlers and some of the toolkit singleton window code. ...
... support commandline handlers work great on the mac if it's a cold start. here's how to implement command-line trapping when the app is already running, without getting into appleevents or c++ code. this is implemented in a pseudo "hidden window" technique and parsing the window arguments instead of command-line handlers and some of the toolkit singleton window code. ...
...dow code. ...
XULRunner tips - Archive of obsolete content
extension manager to be able to install any extensions, you first need to enable the extension manager in application.ini. xulrunner 1.8.0 does not load extensions from the application directory; only the xulrunner directory and the user profile directory are checked. however, it seems that with xulrunner 1.9 the xulrunner directory is ignored, while the profile and application directories are checked. ...
...there is a working stub. any better suggestion? venkman uses "chrome://communicator/skin/" as an alias for "chrome://global/skin/" and this alias was maintained in the xulrunner toolkit until xulrunner 1.9 was released. when using xulrunner 1.9 or greater, you can create your own alias in your chrome manifest...
... var windowds = components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"] .getservice(components.interfaces.nsiwindowdatasource)...
...without these settings password manager will not store login details. pref("signon.remembersignons", true)...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
ns that use xembed instead of using the old xt-based mainloop that most plugins have been using since the netscape 3.x days. the use of the xt mainloop has been a problem for modern plugin development because very few modern applications that want to take advantage of the capabilities of newer toolkits use xt. also, when included with builds of mozilla that are based on gtk 1.2 or gtk 2.x, the xt code that hosts the plugins is at best hacky and has been the source for many minor problems including inconsistent focus behavior as well as occasional crashes. it's recommended that you have a look at the gecko plugin api reference since this document will include information that assumes that you are already familiar with the way that plugins are currently hosted as well as the apis. key difference...
...key differences: in the npp_setwindow call, the window parameter will be the xid of the hosting xembed window. as an implementation note, this is really the xid of a gtksocket window. in your plugin instance npp_getvalue call you need to make sure that you support the new nppvpluginneedsxembed value. more information is included on this below. hosting using gtk2.x included below are a couple of code snippits that should help you get started as well as some hints on building a successful plugin. please use the following diagram as a reference: as you can see from the diagram above, it's pretty easy to set up a plugin using gtk2. the general idea is that you use the xid that was passed into your npp_setwindow() call and create a gtkplug to host inside of that socket. since the gtkplug is just...
...ialized. if you've built your plugin so that it will support either xt or xembed you can include a fallback for older style hosting. if you haven't you can return an error and the plugin will be ignored. it's good practice to do this in case people try to install your plugin for older versions of the browser that don't support xembed functionality. ...
...n't support xembed functionality. this is an incomplete example of what a piece of code might look like that tries to check for the proper mozilla version. this would be included in your np_initialize function. nperror np_initialize(npnetscapefuncs* nstable, nppluginfuncs* pluginfuncs) { nperror err = nperr_no_error; prbool supportsxembed = pr_false; npntoolkittype toolkit = 0; [ code that copies all of the function tables and does ] [ other standard checks ] /* * make sure that the browser supports functionality we care * about. */ err = callnpn_getvalueproc(gnetscapefuncs.getvalue, null, npnvsupportsxembedbool, (void *)&supportsxembed); if (err != np...
JavaArray - Archive of obsolete content
created by any java method which returns an array. in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript. javaarray is a wrapper for the instance; all references to the array instance are made through the javaarray. ...
...rray object, just as you do to access elements in an array in java. for example: var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); bytearray[0] // returns 72 bytearray[1] // returns 101 any java data brought into javascript is converted to javascript data types. when the javaarray is passed back to java, the array is unwrapped and can be used by java code. see the core javascript 1.5 guide for more information about data type conversions. in javascript 1.4 and later, the methods of java.lang.object are inherited by javaarray. backward compatibility javascript 1.3 and earlier the methods of java.lang.object are not inherited by javaarray. in addition, the tostring method is inherited from the object object and returns the following value: [obj...
...rray is created by the java.lang.string.getbytes method, which returns an array. ...
...ript with the newinstance method in javascript 1.4, you can use a javaclass object as the argument for the newinstance method which creates the array, as shown in the following code: var dogs = java.lang.reflect.array.newinstance(java.lang.string, 5); in javascript 1.1, use a class object returned by java.lang.class.forname as the argument for the newinstance method, as shown in the following code: var datatype = java.lang.class.forname("java.lang.string"); var dogs = java.lang.reflect.array.newinstance(datatype, 5); ...
Standards-Compliant Authoring Tools - Archive of obsolete content
html-kit is a full-featured, low priced editor designed to help html, xhtml and xml authors to edit, format, lookup help, validate, preview and publish web pages. validation is done with html tidy, so you can verify standards compliance. ...
... html-kit is a full-featured, low priced editor designed to help html, xhtml and xml authors to edit, format, lookup help, validate, preview and publish web pages. validation is done with html tidy, so you can verify standards compliance. ...
... html-kit is a full-featured, low priced editor designed to help html, xhtml and xml authors to edit, format, lookup help, validate, preview and publish web pages. ...
...editor designed to help html, xhtml and xml authors to edit, format, lookup help, validate, preview and publish web pages. validation is done with html tidy, so you can verify standards compliance. macromedia™ dreamweaver™ cs6 style master and layout master by western civilisation some caveats: it appears that tools currently available from namo generate ie-specific or netscape 4-specific code that may require extra debugging for compatibility with standards-based browsers. newer versions of microsoft frontpage™ have improved, however be sure not to rely on frontpage-specific extensions for critical website content or functionality. some versions of microsoft word create invalid html code that only works with internet explorer. always be sure to validate your web pages. original do...
forEach - Archive of obsolete content
i've removed the lengthy example, while still linking to it and provided a much simpler and leaner implementation. ...
...i've removed the lengthy example, while still linking to it and provided a much simpler and leaner implementation. ...
...i've removed the lengthy example, while still linking to it and provided a much simpler and leaner implementation. ...
...i've removed the lengthy example, while still linking to it and provided a much simpler and leaner implementation. dotnetcarpenter 30 june 2012 <hr> i have released the write access restriction, but i will be watching changes closely. ...
Unconventional controls - Game development
asy, because the events fired by the controller are emulating conventional keyboard keys. captain rogers had the keyboard controls implemented already: this.cursors = this.input.keyboard.createcursorkeys(); //... if(this.cursors.right.isdown) { // move player right } it works out of the box. the cursors are the four directional arrow keys on the keyboard, and these have exactly the same key codes as the arrow keys on the remote. how do you know the codes for the other remote keys? you can check them by printing the responses out in the console: window.addeventlistener("keydown", function(event) { console.log(event.keycode); }, this); every key pressed on the remote will show its key code in the console. you can also check this handy cheat sheet seen below if you're working with pan...
... } }, this); you can see it in action by watching this video. ...
...ollowing the steps at leapmotion.com/setup. when everything is installed and the controller is connected to your computer we can proceed with implementing support in our little demo. first, we add a <script> tag with the url pointing at this file, and add <div id="output"></div> just before the closing </body> tag for outputting diagnostic information. we will need a few helper variables for our code to work — one for the purpose of calculating the degrees from radians, two for holding the horizontal and vertical amount of degrees our hand is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. we next add these lines after all the event listeners for keyboard and mouse, but before the draw method: var todegrees = 1 / (math.pi /...
...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 > degreethres...
asm.js - Game development
et, what improvements it confers, where and how you can make use of it, and further resources and examples. what is asm.js, exactly? it is a very small, strict subset of javascript that only allows things like `while`, `if`, numbers, top-level named functions, and other simple constructs. it does not allow objects, strings, closures, and basically anything that requires heap allocation. asm.js code resembles c in many ways, but it's still completely valid javascript that will run in all current engines. it pushes js engines to optimize this kind of code, and gives compilers like emscripten a clear definition of what kind of code to 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 man...
...ode, 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 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 ge...
...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 chooses to specially recognize asm.js code, there even more optimizations that can be made. firefox is the only browser to do this ri...
...made. firefox is the only browser to do this right now. asm.js language summary asm.js is an intermediate programming language. asm.js has a very predictable perfomance rate because it is limited to an extremely restricted subset of javascript that provides only strictly-typed integers, floats, arithmetic, function calls, and heap accesses. the performance characteristics are closer to native code than that of standard javascript. using a subset of javascript asm.js is already supported by major web browsers. since asm.js runs in a browser it depends heavily on the browser and the hardware. ...
Game over - Game development
« previousnext » this is the 5th 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/lesson5.html. it's fun to watch the ball bouncing off the walls and be able to move the paddle around, but other than that the game does nothing and doesn't have any progression or end goal. it would be good from the gameplay point of view to be able to lose. the logic behind losing in breakout is simple. if you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over. implementing game over let's try to implement game over in our game. ...
...ut other than that the game does nothing and doesn't have any progression or end goal. it would be good from the gameplay point of view to be able to lose. the logic behind losing in breakout is simple. if you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over. implementing game over let's try to implement game over in our game. here's the piece of code from the third lesson where we made the ball bounce off the walls: if(x + dx > canvas.width-ballradius || x + dx < ballradius) { dx = -dx; } if(y + dy > canvas.height-ballradius || y + dy < ballradius) { dy = -dy; } instead of allowing the ball to bounce off all four walls, let's only allow three now — left, top and right. hitting the bottom wall will end the game. we'll edit the sec...
...erval(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. ...
...adius) { if(x > paddlex && x < paddlex + paddlewidth) { dy = -dy; } else { alert("game over"); document.location.reload(); clearinterval(interval); } } if the ball hits the bottom edge of the canvas we need to check whether it hits the paddle . if yes, then it bounces off just like you'd expect; if not then the game is over as before. compare your code here's the working code for you to compare yours against: exercise: make the ball move faster when it hits the paddle. next steps we're doing quite well so far and our game is starting to feel a lot more worth playing now you can lose! but it is still missing something. let's move on to the sixth chapter — build the brick field — and create some bricks for the ball to destroy. ...
Track the score and win - Game development
destroying the bricks is really cool, but to be even more awesome the game could award points for every brick a user hits, and keep count of the total score. counting the score if you can see your score throughout the game, eventually you can impress your friends. you need a variable to record the score. ...
...t("score: "+score, 8, 20); } drawing text on a canvas is similar to drawing a shape. the font definition looks exactly like the one in css — you can set the size and font type in the font() method. then use fillstyle() to set the color of the font and filltext() to set the actual text that will be placed on the canvas, and where it will be placed. ...
...irst parameter is the text itself — the code above shows the current number of points — and the last two parameters are the coordinates where the text will be placed on the canvas. to award a score each time a brick is hit, add a line to the collisiondetection() function to increment the value of the score variable each time a collision is detected. ...
... clearinterval(interval); // needed for chrome to end game } } } } } } thanks to this, your users can actually win the game when they destroy all the bricks, which is quite important when it comes to games. the document.location.reload() function reloads the page and starts the game again once the alert button is clicked. compare your code the latest code looks (and works) like this, in case you want to compare and contrast it with yours: exercise: add more points per brick hit, print out the number of collected points in the end game alert box. next steps the game looks pretty good at this point. in the next lesson you will broaden the game's appeal by adding mouse controls. « previousnext » ...
Buttons - Game development
instead of starting the game right away we can leave that decision to the player by adding a start button they can press. let's investigate how to do that. new variables we will need a variable to store a boolean value representing whether the game is currently being played or not, and another one to represent our button. ...
...he button a callback function that will be executed when the button is pressed a reference to this to specify the execution context the frames that will be used for the over, out and down events. note: the over event is the same as hover, out is when the pointer moves out of the button and down is when the button is pressed. now we need to define the startgame() function referenced in the code above: function startgame() { startbutton.destroy(); ball.body.velocity.set(150, -150); playing = true; } when the button is pressed, we remove the button, sets the ball's initial velocity and set the playing variable to true. finally for this section, go back into your create() function, find the ball.body.velocity.set(150, -150); line, and remove it. you only want the ball to mo...
... « previousnext » ...
...like so: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); if(playing) { paddle.x = game.input.x || game.world.width*0.5; } } that way the paddle is immovable after everything is loaded and prepared, but before the start of the actual game. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps the last thing we will do in this article series is make the gameplay even more interesting by adding some randomization to the way the ball bounces off the paddle. « previousnext » ...
Move the ball - Game development
« previousnext » this is the 4th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson04.html. we have our blue ball printed on screen, but it's doing nothing — it would be cool to make it move somehow. this article covers how to do just that. updating the ball's position on each frame remember the update() function and its definition? ...
...ev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson04.html. we have our blue ball printed on screen, but it's doing nothing — it would be cool to make it move somehow. this article covers how to do just that. updating the ball's position on each frame remember the update() function and its definition? the code inside it is executed on every frame, so it's a perfect place to put the code that will update the ball's position on screen. add the following new lines of the code inside update(), as shown: function update() { ball.x += 1; ball.y += 1; } the code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame. reload index.html and you shoul...
... place to put the code that will update the ball's position on screen. add the following new lines of the code inside update(), as shown: function update() { ball.x += 1; ball.y += 1; } the code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame. reload index.html and you should see the ball rolling across the screen. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps the next step is to add some basic collision detection, so our ball can bounce off the walls. ...
...oordinates on the canvas, on each frame. reload index.html and you should see the ball rolling across the screen. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps the next step is to add some basic collision detection, so our ball can bounce off the walls. this would take several lines of code — a significantly more complex step than we have seen so far, especially if we want to add paddle and brick collisions too — but fortunately phaser allows us to do this much more easily than if we wanted to use pure javascript. in any case, before we do all that we will first introduce phaser's physics engines, and do some setup work. « previousnext » ...
Physics - Game development
for proper collision detection between objects in our game we will need to have physics; this article introduces you to what's available in phaser, as well as demonstrating a typical simple setup. adding physics phaser is bundled with three different physics engines — arcade physics, p2 and ninja physics — with a fourth option, box2d, being available as a commercial plugin. for simple games like ours, we can use the arcade physics engine. ...
... on the screen, we can set velocity on its body. add the following line, again at the bottom of create(): ball.body.velocity.set(150, 150); removing our previous update instructions remember to remove our old method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine. ...
...set velocity on its body. add the following line, again at the bottom of create(): ball.body.velocity.set(150, 150); removing our previous update instructions remember to remove our old method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine. ...
...l. as a result it will be launched upwards, but then fall due to the effects of gravity pulling it down. this kind of functionality is just the tip of the iceberg — there are various functions and variables that can help you manipulate the physics objects. check out the official physics documentation and see the huge collection of examples using the arcade and p2 physics systems. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now we can move to the next lesson and see how to make the ball bounce off the walls. « previousnext » ...
Visual typescript game engine - Game development
luanch debugger configuration comes with this project. physics engine based on matter.js. multiplatform video chat (for all browsers) implemented. socketio used for session staff. multirtc2 used for data transfer also for video chat. multirtc3 alias 'broadcaster' used for video chat. ...
... is fully independent server size. i use one git repo but consider '/server' represent the standalone application. there's server package.json independently from the client part also config is not common. i just like it like that. ...
...ep state clear no. node.js is the best options. for email staff, i choose: npm i gmail-send. -run services database server (locally and leave it alive to develop process): npm run dataserver looks like this : mongod --dbpath ./server/database/data fix: "failed: address already in use" : netstat -ano | findstr :27017 taskkill /pid typeyourpidhere /f also important "run visual studio code as administrator". - a command for killing all node.js process for window users : taskkill /im node.exe /f networking multimedia communication: websocketserver running on node.js text-based protocol sip (session initiation protocol) used for signalling and controlling multimedia sessions. general networking config: config property defined in constructor from serverconfig class. this...
...k.config.js. restart 'npm run dev' best way to fully healthy build. html/css is not prior to this project. if you wanna insert some new html page just define it intro webpack.config.js : plugins : [ new htmlwebpackplugin({ filename: '/templates/mygamelobby.html', template: 'src/html-components/mygamelobby.html' }), ... see register and login example. ...
Gecko FAQ - Gecko Redirect 1
what is gecko? gecko is the open source browser engine designed to support open internet standards such as html 5, css 3, the w3c dom, xml, javascript, and others. gecko is used in multiple browsers, including mozilla firefox, seamonkey, and others. gecko is continuously under development at mozilla.org. gecko has been known previously by the code names "raptor" and "nglayout"; the new name was chosen following a trademark infringement dispute. for more information see the wikipedia article on gecko. what is a layout engine? basically, a layout engine takes content (such as html, xml, image files, applets, and so on) and formatting information (such as cascading style sheets, presentational html tags, etc.) and displays the formatted content on the screen. it paints the browser's ...
...or a future release. xml 1.0: full support, except for processing to manipulate default attributes rdf: full support, except for abouteach, abouteachprefix, and parsetype javascript 1.5, including ecma-262 edition 3 (ecmascript) compliance, except for date.todatestring and date.totimestring, which are not implemented transfer protocols: http 1.1 (including gzip compression), ftp ssl unicode oji (open java interface) image formats png gif jpeg, pjpeg does "full support" mean that gecko has zero bugs today or will have zero bugs at some point in the future? of course not. as robert o'callahan notes in bug 25707, "full html4/css1 compliance can't mean '100% bug free'. if it does, no-one will ever ship a fully compliant browser." because web pages can be arbitrari...
...fully compliant browser." because web pages can be arbitrarily long and complex and have arbitrarily deeply nested markup, it will always be possible to construct web pages that do not display in a given browser the way the specifications would recommend. so long as qa testing and test case development continues, there will always be known bugs at any given point in time in the open-source gecko codebase, and it follows that every commercial product that has ever shipped and ever will ship based on gecko will have known bugs at the time of its release. (the same principle of course applies to other browser engine development projects and products based upon them as well.) known bugs in the open-source gecko codebase are documented in bugzilla. here are some links to lists of reported bugs re...
...s platforms. additionally, on the windows platform, gecko's xpcom interfaces are wrapped in an activex control that vb developers can utilize (activex wrappers are not available on other platforms because activex is a windows-only technology). a javabean wrapper is not currently under development, but there is nothing in gecko's architecture that precludes such development in the future. source code and documentation for these interfaces are available through mozilla.org. for future embedding api plans, see wikimo:mozilla 2:embedding apis. which platforms does gecko run on? gecko runs today on win32 (windows xp service pack 2, windows vista, windows 7, windows 8, windows 8.1, windows 10), mac os x 10.5 and later, and linux. oems and contributors from the net participating in mozilla.org a...
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ascii string format by translating it into a radix-64 representation. the term base64 originates from a specific mime content transfer encoding. base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ascii. this is to ensure that the data remain intact without modification during transport. base64 is commonly used in a number of applications including email via mime, and storing complex data in xml. one common application of base64 encoding on the web is to encode binary data so it can be included in a data: url. in javascript there are two functions respectively for decoding and...
...intact without modification during transport. base64 is commonly used in a number of applications including email via mime, and storing complex data in xml. one common application of base64 encoding on the web is to encode binary data so it can be included in a data: url. in javascript there are two functions respectively for decoding and encoding base64 strings: btoa(): creates a base-64 encoded ascii string from a "string" of binary data ("btoa" should be read as "binary to ascii"). atob(): decodes a base64 encoded string("atob" should be read as "ascii to binary"). the algorithm used by atob() and btoa() is specified in rfc 4648, section 4. note that btoa() expects to be passed binary data, and will throw an exception if the given string contains any characters whose utf-16 repres...
...atob(): decodes a base64 encoded string("atob" should be read as "ascii to binary"). the algorithm used by atob() and btoa() is specified in rfc 4648, section 4. note that btoa() expects to be passed binary data, and will throw an exception if the given string contains any characters whose utf-16 representation occupies more than one byte. for more details, see the documentation for btoa(). encoded size increase each base64 digit represents exactly 6 bits of data. so, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit base64 digits (4×6 = 24 bits). this means that the base64 version of a string or file will be at most 133% the size of its source (a ~33% increase). the increase may be larger if the encoded data is small. for example,...
...ents exactly 6 bits of data. so, three 8-bits bytes of the input string/binary file (3×8 bits = 24 bits) can be represented by four 6-bit base64 digits (4×6 = 24 bits). this means that the base64 version of a string or file will be at most 133% the size of its source (a ~33% increase). the increase may be larger if the encoded data is small. for example, the string "a" with length === 1 gets encoded to "yq==" with length === 4 — a 300% increase. ...
Advanced styling effects - Learn web development
box-shadow allows you to apply one or more drop shadows to an element's box. like text shadows, box shadows are supported pretty well across browsers, including ie9+ and edge. users of older ie versions might just have to cope with no shadows, so just test your designs to make sure your content is legible without them. you can find the examples in this section at box-shadow.html (see the source code too). a simple box shadow let's look at a simple example to get things started. first, some html: <article class="simple"> <p><strong>warning</strong>: the thermostat on the cosmic transcender has reached a critical level.</p> </article> now the css: p { margin: 0; } article { max-width: 500px; padding: 10px; background-color: red; background-image: linear-gradient(to bottom, rg...
...ere are two properties that use blend modes in css: background-blend-mode, which blends together multiple background images and colors set on a single element. mix-blend-mode, which blends together the element it is set on with elements it is overlapping — both background and content. you can find a lot more examples than are available here in our blend-modes.html example page (see source code), and on the <blend-mode> reference page. note: blend modes are also very new, and slightly less well supported than filters. there is no support as yet in edge, and safari only supports some of the blend mode options. background-blend-mode again, let's look at some examples so we can understand this better. first, background-blend-mode — here we'll show a couple of simple <div>s, so you c...
...e, as if we had put a compass in the middle of the file and drawn a circle that fits inside the file. it is that circle that the text flows around. note: in firefox you can use the devtools shapes inspector to inspect shapes. the circle() function is just one of a few basic shapes that are defined, however there are a number of different ways to create shapes. for more information and example code for css shapes see the guides to css shapes on mdn. -webkit-background-clip: text another feature we thought we'd mention briefly is the text value for background-clip. when used along with the proprietary -webkit-text-fill-color: transparent; feature, this allows you to clip background images to the shape of the element's text, making for some nice effects. this is not an official standard, bu...
...g websites with -webkit- prefixes that it started to look like the other browsers were broken, whereas in actual fact they were following the standards. so they were forced to implement a few such features. this highlights the danger of using non-standard and/or prefixed css features in your work — not only do they cause browser compatibility issues, but they are also subject to change, so your code could break at any time. it is much better to stick to the standards. if you do want to use such features in your production work, make sure to test across browsers thoroughly and check that, where these features don't work, the site is still usable. note: for a full -webkit-background-clip: text code example, see background-clip-text.html (see also the source code). summary we hope this ar...
Test your skills: The Cascade - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...tch the image above. for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for cascade skill test 1". details of what you have already tried, and what you would like us to do,...
...e skill test 1". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want to be assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: tables - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task in the lesson we styled up a table in a rather garish manner. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task in the lesson we styled up a table in a rather garish manner. ...
...f the main table. for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for tables skill test". details of what you have already tried, and what you would like us to do, e.
...or tables skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
Test Your Skills: Fundamental layout comprehension - Learn web development
if you have worked through this module then you will have already covered the basics of what you need to know to do css layout today, and to work with older css as well. this task will test some of your knowledge by way of developing a simple webpage layout using a variety of techniques. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief you have been provided with some raw html, basic css, and images — now you need to create a layout for the design, which should look just like the image below. basic setup you c...
...into a directory on your computer, and add the images into a folder named images. opening the index.html file in a browser should give you a page with basic styling but no layout, which should look something like the image seen below. this starting point has all of the content of your layout as displayed by the browser in normal flow. if you don't want to work locally then using a tool such as codepen or jsfiddle will work as well. you will need to upload the images using their assets functionality and replace the value in the src attribute to point to the new image location. your tasks you now need to implement your layout. the tasks you need to achieve are: to display the navigation items in a row, with an equal amount of space between the items. the navigation bar should scroll ...
...tasks, and there often isn’t a single right or wrong way to do things. try a few different approaches and see which works best. make notes as you experiment. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for fundamental layout comprehension". details of what you have already tried, and what you would li...
...layout comprehension". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. in this module introduction to css layout normal flow flexbox grid floats positioning multiple-column layout responsive design beginner's guide to media queries legacy layout methods supporting older browsers fundamental layout comprehension assessment ...
Introduction to CSS layout - Learn web development
be in a good place to understand which is the best layout tool for each task. normal flow normal flow is how the browser lays out html pages by default when you do nothing to control page layout. let's look at a quick html example: <p>i love my cat.</p> <ul> <li>buy cat food</li> <li>exercise</li> <li>cheer up friend</li> </ul> <p>the end!</p> by default, the browser will display this code as follows: note here how the html is displayed in the exact order in which it appears in the source code, with elements stacked up on top of one another — the first paragraph, followed by the unordered list, followed by the second paragraph. the elements that appear one below the other are described as block elements, in contrast to inline elements, which appear one beside the other, like ...
...e our middle paragraph a position value of relative — this doesn't do anything on its own, so we also add top and left properties. these serve to move the affected element down and to the right — this might seem like the opposite of what you were expecting, but you need to think of it as the element being pushed on its left and top sides, which result in it moving right and down. ...
...nt from normal flow, and place it using offsets from the edges of a containing block. going back to our original non-positioned example, we could add the following css rule to implement absolute positioning: .positioned { position: absolute; top: 30px; left: 30px; } here we give our middle paragraph a position value of absolute, and the same top and left properties as before. ...
...while reading up and down columns is less useful in a web context as you don’t want to force users to scroll up and down, arranging content into columns can be a useful technique. to turn a block into a multicol container we use either the column-co...
What text editors are available? - Learn web development
extensible atom mit/bsd free windows, mac, linux forum online manual yes bluefish gpl 3 free windows, mac, linux mailing list, wiki online manual yes brackets mit/bsd free windows, mac, linux forum, irc github wiki yes coda closed source $99 mac twitter, forum, e-mail ebook yes codelobster closed source free windows, mac, linux forum, e-mail no end user doc yes emacs gpl 3 free windows, mac, linux faq, mailing list, news group online manual yes espresso closed source $75 mac faq, e-mail no end user doc, but plug-in doc yes gedit gpl free windows, mac, linux mailing list, irc o...
...your computer may already be installed with one of the editors suggested above (e.g. gedit if you use gnome desktop, kate if you use ...
...hen you're doing web development and writing in html, css, and javascript, you can produce some pretty large, complex files. make it easier on yourself by choosing a text editor that understands the technologies you're working with. many text editors help you out with features like: syntax highlighting. make your file more legible by color-coding keywords based on the technology you're using. code completion. save you time by auto-completing recurring structures (for example, automatically close html tags, or suggesting valid values for a given css property). code snippets. as you saw when starting a new html document, many technologies use the same document structure over and over. save yourself the hassle of retyping all this by using a code snippet to pre-fill your document. most tex...
... depends on your needs and plans. these functionalities are often helpful: search-and-replace, in one or multiple documents, based on regular expressions or other patterns as needed quickly jump to a given line view two parts of a large document separately view html as it will look in the browser select text in multiple places at once view your project's files and directories format your code automatically with code beautifier check spelling auto-indent code based on indentation settings do i want to add extra features to my text editor? an extensible editor comes with fewer built-in features, but can be extended based on your needs. if you aren't sure which features you want, or your favorite editor lacks those features out of the box, look for an extensible editor. the best ed...
What software do I need to build a website? - Learn web development
tensively while you're building the website. all desktop operating systems come with a basic text editor. these editors are all straightforward, but lack special features for webpage coding. if you want something a bit fancier, there are plenty of third-party tools available. ...
...hing a bit fancier, there are plenty of third-party tools available. third-party editors often come with extra features, including syntax coloring, auto-completion, collapsible sections, and code search. ...
...psible sections, and code search. ...
...visual studio code web storm brackets shiftedit sublime text mac os textedit textwrangler visual studio code brackets shiftedit sublime text linux vi (all unix) gedit (gnome) kate (kde) leafpad (xfce) emacs vim visual studio code brackets shiftedit sublime text chrome os shiftedit here is a screenshot of an advanced text editor: here is a screenshot of an online text editor: uploading files on the web when your website is ready for public viewing, you'll have to upload your webpages to your web server. you can buy space on a server from various pro...
Advanced form styling - Learn web development
tton"></p> </form> applying the following css to them removes system-level styling. input { -webkit-appearance: none; appearance: none; } note: it is a good idea to always include both declarations — prefixed and unprefixed — when using a prefixed property. prefixed usually means "work in progress", so in the future browser vendors may come to a consensus to drop the prefix. the above code is good for future-proofing against such an eventuality. the following live example shows you what they look like in your system — default on the left, and with the above css applied on the right (find it here also if you want to test it on other systems). in most cases, the effect is to remove the stylized border, which makes css styling a bit easier, but isn't really essential. in a coup...
... also bear in mind that we've added some javascript to the page that lists the files selected by the file picker, below the control itself. this is a simplified version of the example found on the <input type="file"> reference page. as you can see, we've done fairly well at getting these to look uniform across modern browsers. we've applied some global normalizing css to all the controls and...
...check out styling cross-browser compatible range inputs with css on css tricks for a detailed write up of what's needed. color input types input controls of type color are not too bad. in supporting browsers, they tend to just give you a block of solid color with a small border. you can remove the border, just leaving the bloc...
... meters and progress bars <meter> and <progress> are possibly the worst of the lot. as you saw in the earlier example, we can set them to a desired width relatively accurately. but beyond that, they are really difficult to style in any way. they don't handle height settings consistently between each other and between browsers, you can color the background, but not the foreground bar, and set...
Test your skills: Form structure - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...of structural elements around the label/field pairs to separate them out. download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice this example in the interactive editor above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for form structure 1 skill test". details of what you have already tried, and what you would like us...
...ructure 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Form validation - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. ...
...r is too short, provide the user with appropriate custom error messages. download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for form validation 1 skill test". details of what you have already tried, and what you would like u...
...idation 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: HTML5 controls - Learn web development
this aim of this skill test is to assess whether you've understood our the html5 input types article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html5 controls 1 first let's explore some of the new html5 input types. create appropriate inputs for a user to update their details for: email website phone number favourite color try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html5 controls 2 next, we wa...
...el. give it a minimum value of 1, maximum value of 30, and initial value of 10. create a corresponding output element to put the current value of the slider into. give it a class of invite-output, and semantically associate it with the input. if you do this correctly, the javascript included on the page will automatically update the output value when the slider is moved. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. y...
...e the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for html5 controls 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or ...
...ontrols 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
HTML basics - Learn web development
for example, content could be structured within a set of paragraphs, a list of bulleted points, or using images and data tables. as the title suggests, this article will give you a basic understanding of html and its functions. so what is html? html is not a programming language; it is a markup language that defines the structure of your content. html consists of a series of elements, which you use to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. ...
...r the previous attribute, if the element already has one or more attributes). the attribute name followed by an equal sign. the attribute value wrapped by opening and closing quotation marks. note: simple attribute values that don't contain ascii whitespace (or any of the characters " ' ` = < > ) can remain unquoted, but it is recommended that you quote all attribute values, as it makes the code more consistent and understandable. nesting elements you can put elements inside other elements too — this is called nesting. if we wanted to state that our cat is very grumpy, we could wrap the word "very" in a <strong> element, which means that the word is to be strongly emphasized: <p>my cat is <strong>very</strong> grumpy.</p> you do however need to make sure that your elements are pro...
...g </img> tag and no inner content. this is because an image element doesn't wrap content to affect it. its purpose is to embed an image in the html page in the place it appears. anatomy of an html document that wraps up the basics of individual html elements, but they aren't handy on their own. now we'll look at how individual elements are combined to form an entire html page. let's revisit the code we put into our index.html example (which we first met in the dealing with files article): <!doctype html> <html> <head> <meta charset="utf-8"> <title>my test page</title> </head> <body> <img src="images/firefox-icon.png" alt="my test image"> </body> </html> here, we have the following: <!doctype html> — the doctype. it is required preamble. in the mists of time, when h...
...t. if you are having trouble remembering it, remember that it stands for hypertext reference. add a link to your page now, if you haven't already done so. conclusion if you have followed all the instructions in this article, you should end up with a page that looks like the one below (you can also view it here): if you get stuck, you can always compare your work with our finished example code on github. here, we have only really scratched the surface of html. to find out more, go to our learning html topic. previous overview: getting started with the web next in this module installing basic software what will your website look like? dealing with files html basics css basics javascript basics publishing your website how the web works ...
Installing basic software - Learn web development
u what tools you need to do simple web development and how to install them properly. what tools do the professionals use? a computer. maybe that sounds obvious to some people, but some of you are reading this article on your phone or a library computer. for serious web development, it's better to invest in a desktop or laptop computer running windows, macos or linux. a text editor, to write code in. this could be a text editor (e.g. visual studio code, notepad++, sublime text, atom, gnu emacs, or vim), or a hybrid editor (e.g. dreamweaver or webstorm). office document editors are not suitable for this use, as they rely on hidden elements that interfere with the rendering engines used by web browsers. web browsers, to test code in. currently, the most-used browsers are firefox, chrome, o...
...rowsers your target audience may still be using (such as ie 8–10.) lynx, a text-based terminal web browser, is great for seeing how your site is experienced by visually-impaired users. a graphics editor, like gimp, figma, paint.net, photoshop, or xd, to make images or graphics for your web pages. a version control system, to manage files on servers, collaborate on a project with a team, share code and assets and avoid editing conflicts. right now, git is the most popular version control system along with the github or gitlab hosting service. an ftp program, used on older web hosting accounts to manage files on servers (git is increasingly replacing ftp for this purpose). there are loads of (s)ftp programs available including cyberduck, fetch and filezilla. an automation system, like webp...
...on control system along with the github or gitlab hosting service. an ftp program, used on older web hosting accounts to manage files on servers (git is increasingly replacing ftp for this purpose). there are loads of (s)ftp programs available including cyberduck, fetch and filezilla. an automation system, like webpack, grunt, or gulp to automatically perform repetitive tasks, such as minifying code and running tests. libraries, frameworks, etc., to speed up writing common functionality. a library tends to be an existing javascript or css file that provides ready-rolled functionality for you to make use of in your code. a framework tend to take this idea further, offering a complete system with some custom syntaxes for you to write a web app on top of. more tools besides! what tools do i...
...p with a bare minimum — a text editor and some modern web browsers. installing a text editor you probably already have a basic text editor on your computer. by default windows includes notepad and macos comes with textedit. linux distros vary; ubuntu comes with gedit by default. for web development, you can probably do better than notepad or textedit. we recommend starting with visual studio code, which is a free editor, that offers live previews and code hints. installing modern web browsers for now, we'll install a couple of desktop web browsers to test our code in. choose your operating system below and click the relevant links to download installers for your favorite browsers: linux: firefox, chrome, opera, brave. windows: firefox, chrome, opera, internet explorer, microsoft edg...
Test your skills: Advanced HTML text - Learn web development
the aim of this skill test is to assess whether you've understood our advanced text formatting article. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. advanced html text 1 in this task we want you to turn the provided animals and their definitions into a description list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. advanced html text 2 in this task we want you to add some semantics to the provided html as ...
...k-level quote, and semantically indicate that the quote is taken from accessibility. semantically mark up "html" and "css" as acronyms, providing expansions as tooltips. semantically associate machine-readable dates with the dates in the text. use subscript and superscript to provide correct semantics for the chemical formulae and dates, and make them display correctly. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. y...
...e the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for advanced html text 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help,...
...ml text 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
HTML table advanced features and accessibility - Learn web development
ted by the html5 spec, and can't be read by sighted users (it doesn't appear on the page.) active learning: adding a caption let's try this out, revisiting an example we first met in the previous article. open up your language teacher's school timetable from the end of html table basics, or make a local copy of 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...
...elow the table header (the browser will still render it at the bottom of the table). the <tbody> element needs to wrap the other parts of the table content that aren't in the table header or footer. it will appear below the table header or sometimes footer, depending on how you decided to structure it. note: <tbody> is always included in every table, implicitly if you don't specify it in your code. to check this, open up one of your previous examples that doesn't include <tbody> and look at the html code in your browser developer tools — you will see that the browser has added this tag for you. you might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling. active learning: adding table structure let...
...: adding table structure let's put these new elements into action. first of all, make a local copy of spending-record.html and minimal-table.css in a new folder. try opening it in a browser — you'll see that it looks ok, but it could stand to be improved. the "sum" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code. put the obvious headers row inside a <thead> element, the "sum" row inside a <tfoot> element, and the rest of the content inside a <tbody> element. save and refresh, and you'll see that adding the <tfoot> element has caused the "sum" row to go down to the bottom of the table. next, add a colspan attribute to make the "sum" cell span across the first four columns, so the actual number appears ...
..., add a colspan attribute to make the "sum" cell span across the first four columns, so the actual number appears at the bottom of the "cost" column. let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying css. inside the head of your html document, you'll see an empty <style> element. inside this element, add the following lines of css code: tbody { font-size: 95%; font-style: italic; } tfoot { font-weight: bold; } save and refresh, and have a look at the result. if the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling. note: we don't expect you to fully understand the css right now. you'll learn more about this when you go through our c...
Accessibility in React - Learn web development
kes a function as an argument; this function is executed after the component renders. let's see this in action; put the following useeffect() call just above the return statement in the body of todo(), and pass into it a function that logs the words "side effect" to your console: useeffect(() => { console.log("side effect"); }); to illustrate the difference between the main render process and code run inside useeffect(), add another log – put this one below the previous addition: console.log("main render"); now, open the app in your browser. you should see both messages in your console, with each one repeating three times. note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code. main render (3) ...
...n the last "edit" button. we need to refactor our approach so that focus changes only when isediting changes from one value to another. more robust focus management in order to meet our refined criteria, we need to know not just the value of isediting, but also when that value has changed. in order to do that, we need to be able to read the previous value of the isediting constant. using pseudocode, our logic should be something like this: if (wasnoteditingbefore && iseditingnow) { focusoneditfield() } if (waseditingbefore && isnoteditingnow) { focusoneditbutton() } the react team had discussed ways to get a component’s previous state, and has provided an example custom hook we can use for the job. paste the following code near the top of todo.js, above your todo() function. funct...
...(); useeffect(() => { ref.current = value; }); return ref.current; } now we'll define a wasediting constant beneath the hooks at the top of todo(). we want this constant to track the previous value of isediting, so we call useprevious with isediting as an argument: const wasediting = useprevious(isediting); with this constant, we can update our useeffect() hook to implement the pseudocode we discussed before — update it as follows: useeffect(() => { if (!wasediting && isediting) { editfieldref.current.focus(); } if (wasediting && !isediting) { editbuttonref.current.focus(); } }, [wasediting, isediting]); note that the logic of useeffect() now depends on wasediting, so we provide it in the array of dependencies. again try using the "edit" and "cancel" buttons ...
...ps. remember to always write the best html you can. useref() and useeffect() are somewhat advanced features, and you should be proud of yourself for using them! look out for opportunities to practice them more, because doing so will allow you to create inclusive experiences for users. remember: our app would have been inaccessible to keyboard users without them! note: if you need to check your code against our version, you can find a finished version of the sample react app code in our todo-react repository. for a running live version, see https://mdn.github.io/todo-react-build/. in the very last article we'll present you with a list of react resources that you can use to go further in your learning. previous overview: client-side javascript frameworks next in this module int...
React interactivity: Events and state - Learn web development
hello!"); } clicking on the "add" button in your browser will prove that the addtask() callback function works, but it'd be nice if we could get the alert to show us what we're typing in our input field! this is what we'll do next. note: we decided to name our callback prop addtask to make it easy to understand what the prop will do. another common convention you may well come across in react code is to prefix callback prop names with the word on, followed by the name of the event that will cause them to be run. for instance, we could have given our form a prop of onsubmit with the value of addtask. state and the usestate hook so far, we've used props to pass data through our components and this has served us just fine. now that we're dealing with user input and data updates, however, w...
...t state. it returns two things: the state, and a function that can be used to update the state later. this is a lot to take in at once, so let's try it out. we're going to make ourselves a name state, and a function for updating the name state. write the following above your handlesubmit() function, inside form(): const [name, setname] = usestate('use hooks!'); what's going on in this line of code? we are setting the initial name value as "use hooks!". we are defining a function whose job is to modify name, called setname(). usestate() returns these two things, so we are using array destructuring to capture them both in separate variables. reading state you can see the name state in action right away. add a value attribute to the form’s input, and set its value to name. your brow...
...an fix this by counting the length of tasklist and changing the text of our heading accordingly. add this inside your app() definition, before the return statement: const headingtext = `${tasklist.length} tasks remaining`; hrm. this is almost right, except that if our list ever contains a single task, the heading will still use the word “tasks”. we can make this a variable, too. update the code you just added as follows: const tasksnoun = tasklist.length !== 1 ? 'tasks' : 'task'; const headingtext = `${tasklist.length} ${tasksnoun} remaining`; now you can replace the list heading's text content with the headingtext variable. update your <h2> like so: <h2 id="list-heading">{headingtext}</h2> completing a task you might notice that, when you click on a checkbox, it checks and uncheck...
...t notice that, when you click on a checkbox, it checks and unchecks appropriately. as a feature of html, the browser knows how to remember which checkbox inputs are checked or unchecked without our help. this feature hides a problem, however: toggling a checkbox doesn't change the state in our react application. this means that the browser and our app are now out-of-sync. we have to write our own code to put the browser back in sync with our app. proving the bug before we fix the problem, let's observe it happening. we'll start by writing a toggletaskcompleted() function in our app() component. this function will have an id parameter, but we're not going to use it yet. for now, we'll log the first task in the array to the console – we're going to inspect what happens when we check or unch...
Beginning our React todo list - Learn web development
ked with creating a proof-of-concept in react – an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. this article will walk you through putting the basic app component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. note: if you need to check your code against our version, you can find a finished version of the sample react app code in our todo-react repository. for a running live version, see https://mdn.github.io/todo-react-build/. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to introduce our todo list case study, and get the...
...ur project cd src # delete a few files rm -- app.test.js app.css logo.svg serviceworker.js setuptests.js # move back up to the root of the project cd .. notes: two of the files we’re deleting are for testing the application. we will not cover testing here. if you stopped your server to do the terminal tasks mentioned above, you’ll have to start it again using npm start. project starter code as a starting point for this project, we're going to provide two things: an app() function to replace the one you have now, and some css to style your app. the jsx copy the following snippet to your clipboard, then paste it into app.js so that it replaces the existing app() function: function app(props) { return ( <div classname="todoapp stack-large"> <h1>todomatic</h1> <for...
...for as an attribute in jsx because for is a reserved word, so react uses htmlfor instead. notes: to use boolean values (true and false) in jsx attributes, you must enclose them in curly braces. if you write defaultchecked="true", the value of defaultchecked will be "true" — a string literal. ...
...you must enclose them in curly braces. if you write defaultchecked="true", the value of defaultchecked will be "true" — a string literal. remember — this is actually javascript, not html! the aria-pressed attribute used in our earlier code snippet has a value of true because aria-pressed is not a true boolean attribute in the way checked is. ...
Vue conditional rendering: editing existing todos - Learn web development
vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn how to do conditional rendering in vue. creating an editing component we can start by creating a separate component to handle the editing functionality. in your components directory, create a new file called todoitemeditform.vue. ...
...we create a form with an <input> field for editing the name of our to-do. there is a "save" button and a "cancel" button: when the "save" button is clicke...
...we create a form with an <input> field for editing the name of our to-do. ...
... sibling of a v-if/v-else-if block, otherwise vue will not recognize them. you can also attach v-if to a <template> tag if you need to conditionally render an entire template. lastly, you can use a v-if + v-else at the root of your component to display only one block or another, since vue will only render one of these blocks at a time. we'll do this in our app, as it will allow us to replace the code that displays our to-do item with the edit form. first of all add v-if="!isediting" to the root <div> in your todoitem component, <div class="stack-small" v-if="!isediting"> next, below that <div>'s closing tag add the following line: <to-do-item-edit-form v-else :id="id" :label="label"></to-do-item-edit-form> we also need to import and register the todoitemeditform component, so we can use ...
Tools and testing - Learn web development
d of tools, from javascript frameworks, to testing and automation tools, and more besides. as your web projects become larger and more complex, you'll want to start taking advantage of some of these tools, working out a reliable toolchain to give your development process superpowers. on top of that, we still need to keep cross-browser support in the forefront of our minds, and make sure that our code follows best practices that allow our projects to work across different browsers and devices that our users are using to browse the web, and be usable by people with disabilities. working out what tools you should be using can be a difficult process, so we have written this set of articles to inform you of what types of tool are available, what they can do for you, and how to make use of the cur...
...ave put together a course that includes all the essential information you need to work towards your goal. get started prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use many the tools detailed here. for example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of javascript frameworks, or writing tests and running them against your code using test runners. in addition, you should start with the first module in this topic, which gives a useful overview of the general area. modules understanding client-side web development tools client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose...
... how client-side frameworks work and how they fit into your toolset, before moving on to tutorial series covering some of today's most popular ones. git and github all developers will use some kind of version control system (vcs), a tool to allow them to collaborate with other developers on a project without danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. the most popular vcs (at least among web developers) is git, along with github, a site that provides hosting for your repositories and several tools for working with them. this module aims to teach you what you need to know about both of them. cross browser testing this module looks specifically at the area of testing web projects across different brows...
...hem. this module aims to teach you what you need to know about both of them. cross browser testing this module looks specifically at the area of testing web projects across different browsers. here we look at identifying your target audience (e.g. what users, browsers and devices do you most need to worry about?), how to go about testing, the main issues that you'll face with different types of code and how to fix/mitigate those, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing. ...
Accessibility Features in Firefox
to utilizing their ideas and hard work. contributions come in many forms. the mozilla firefox community welcomes bug reports, ideas, documentation, answering questions in the support forums -- and nearly any kind of community involvement resulting in a browser built for a broader audience of users and developers. here are a couple of success stories from businesses who contributed accessibility code because they needed an accessible web browser which supported their software: contributes accessible web applications (dhtml and ajax) ibm realized it needed a way to enable accessibility for ever more powerful web applications, beyond what you see on typical web pages today. rather than go and write their own new web browser, ibm decided to trust in the openness of the mozilla community, whic...
...essible web applications (dhtml and ajax) ibm realized it needed a way to enable accessibility for ever more powerful web applications, beyond what you see on typical web pages today. rather than go and write their own new web browser, ibm decided to trust in the openness of the mozilla community, which accepted ibm's significant contributions. for example, ibm has delivered over 50,000 lines of code to enable accessibility in firefox on windows and especially for this new powerful world of "web applications". a web application may be an easier-to-use online tax assistant, a web calendar or a live sports statistics page, which is familiar in that it acts much like a desktop application. whether the current buzzword for this technology is "dhtml", "ajax" or "web 2.0" doesn't really matter. thi...
...nly browser to support the newly evolving standards for making these web applications accessible. companies such as yahoo! have announced they are already working with the technology their new richer interfaces accessible with this new technology. developers, please see our dhtml accessibility documentation and get involved in writing tools and websites using this new technology. sun contributes code to improve accessibility on unix a similar story occurred at sun microsystems. sun needed an accessible web browser for unix, specifically for solaris. again, rather than develop a brand new web browser, it made more sense to contribute fixes that make firefox accessible on unix. thanks to sun's efforts we already have excellent support for the gnome onscreen keyboard (gok). meanwhile, ibm has j...
...the gnome onscreen keyboard (gok). meanwhile, ibm has joined sun's effort to make firefox as screen reader accessible on unix as it is on windows, because the same core accessibility work applies to linux. the two companies anticipate that in 2007, firefox will support topnotch screen reader accessibility on unix and linux. that's the great thing about the open firefox community model and source code license -- anyone can contribute, and everyone benefits. downloads, support and more information firefox information and downloads general online support and community forums accessibility newsgroup for users. can also be accessed as a mailing list. accessibility compliance statement (section 508): http://www.mozilla.com/firefox/vpat.html ...
CSUN Firefox Materials
n to utilizing their ideas and hard work. contributions come in many forms. the mozilla firefox community welcomes bug reports, ideas, documentation, answering questions in the support forums -- and nearly any kind of community involvement resulting in a browser built for a broader audience of users and developers. here are a couple of success stories from businesses who contributed accessibility code because they needed an accessible web browser which supported their software: ibm contributes accessible web applications (dhtml and ajax) ibm realized it needed a way to enable accessibility for ever more powerful web applications, beyond what you see on typical web pages today. rather than go and write their own new web browser, ibm decided to trust in the openness of the mozilla community, whi...
...cessible web applications (dhtml and ajax) ibm realized it needed a way to enable accessibility for ever more powerful web applications, beyond what you see on typical web pages today. rather than go and write their own new web browser, ibm decided to trust in the openness of the mozilla community, which accepted ibm's significant contributions. for example, ibm has delivered over 50,000 lines of code to enable accessibility in firefox on windows and especially for this new powerful world of "web applications". a web application may be an easier-to-use online tax assistant, a web calendar or a live sports statistics page, which is familiar in that it acts much like a desktop application. whether the current buzzword for this technology is "dhtml", "ajax" or "web 2.0" doesn't really matter. thi...
...er. this fact remains: the web is changing to become more interactive and less like a bunch of plain documents. firefox is currently the only browser to support the new evolving standards for making these web applications accessible. companies such as yahoo! have announced they are already working with the technology their new richer interfaces accessible with this new technology. sun contributes code to improve accessibility on unix a similar story occurred at sun microsystems. sun needed an accessible web browser for unix, specifically for solaris. again, rather than develop a brand new web browser, it made more sense to contribute fixes that make firefox accessible on unix. thanks to sun's efforts we already have excellent support for the gok onscreen keyboard. meanwhile, ibm has joined sun...
...port for the gok onscreen keyboard. meanwhile, ibm has joined sun's effort to make firefox as screen reader accessible on unix as it is on windows, because the same core accessibility work applies to linux. the two companies anticipate that in 2007, firefox will support topnotch screen reader accessibility on unix and linux. that's the great thing about the open firefox community model and source code license -- anyone can contribute, and everyone benefits. for more information general information: http://www.mozilla.com/firefox/ online support and community forums are located: http://forums.mozillazine.org/ accessibility compliance statement (section 508): http://www.mozilla.com/firefox/vpat.html ...
Benchmarking
slower. any performance metrics gathered by such builds are largely unrelated to what would be found in a release browser. rust optimization level local optimized builds are compiled with rust optimization level 1 by default, unlike nightly builds, which use rust optimization level 2. this setting reduces build times significantly but comes with a serious hit to runtime performance for any rust code (for example stylo and webrender). add the following to your mozconfig in order to build with level 2: ac_add_options rustc_opt_level=2 gc poisoning many firefox builds have a diagnostic tool that causes crashes to happen sooner and produce much more actionable information, but also slow down regular usage substantially. in particular, "gc poisoning" is used in all debug builds, and in optimiz...
...lead to severe performance problems even if things look ok visually. normally you would want to leave acceleration enabled while profiling, but on linux you may wish to disable accelerated graphics (preferences -> advanced -> general -> use hardware acceleration when available). flash plugin if you are profiling real websites, you should disable the adobe flash plugin so you are testing firefox code and not flash jank problems. in about:addons > plugins, set shockwave flash to "never activate". timer precision firefox reduces the precision of the performance apis and other clock and timer apis accessible to web content. they are currently reduce to a multiple of 2ms; which is controlled by the privacy.reducetimerprecision about:config flag. the exact value of the precision is controlled b...
...trolled by the privacy.reducetimerprecision about:config flag. the exact value of the precision is controlled by the privacy.resistfingerprinting.reducetimerprecision.microseconds about:config flag. profiling tools currently the gecko profiler has limitations in the ui for inverted call stack top function analysis which is very useful for finding heavy functions that call into a whole bunch of code. ...
...nding heavy functions that call into a whole bunch of code. currently such functions may be easy to miss looking at a profile, so feel free to also use your favorite native profiler. it also lacks features such as instruction level profiling which can be helpful in low level profiling, or finding the hot loop inside a large function, etc. some example tools include instruments on osx (part of xcode), rotateright zoom on linux (uses perf underneath), and intel vtune on windows or linux. ...
Testopia
se a fix for testopia immediately, because it's currently under heavy work to make testopia a fully self-contained extension, which means that all tr_*.cgi scripts which are currently in the bugzilla/ root directory are being moved into extensions/testopia/lib/. this is not an trivial task, it takes time (it started in august 2014), and we decided that it was not a good idea to release half-baked code which still needs testing to make sure we didn't regress anything. the good news is that the current code in the git repository already works with bugzilla 5.0, and so if you upgraded to 5.0 already, and if you don't mind having a work-in-progress extension on your machine, you can decide to pull the code from the git repository. this would also let us get some early feedback in case you find re...
...do not ask when we plan to release 3.0, because we really don't know. "as soon as possible" is our best answer. ...
...tar the tarball in your bugzilla root directory and run checksetup. thanks go to lpsolit from the bugzilla team for his work in making this possible. testopia 2.4 this version supports bugzilla 3.6. important notice: if you are upgrading on a case sensitive filesystem you must remove the existing testopia folder in the extensions directory. if you have made modifications to the testopia source code, you will need to merge them into the new testopia folder (capital t). if you are on windows or another case insensitive file system you should first rename the folder (testopia-old for example) and then unzip the tarball. you can then merge your changes before deleting the old version. api users take note: positional parameters are now deprecated. all params should now be sent in a hash (struct...
...o one tool and uses bugzilla group permissions to limit access to modifying test objects. testopia allows users to attach bugs to test case run results for centralized management of the software engineering process. requirements as our development has moved forward, we have decided to try to keep abreast of the latest stable release from bugzilla (currently 5.0). this gives us a stable code base to work from. developing plugins or extensions for any software is like trying to hit a moving target. this decision allows us to focus our time more on releasing new features often and early rather than back porting. however, this means that most major feature will not be back ported to earlier versions unless and until we have time to do so. anyone wishing to help in this effort is more th...
Creating a spell check dictionary add-on
x add-on, or how to update your existing add-on, so that it can be installed, uninstalled and updated without a restart. parts needed to create a dictionary add-on, you first need two things: a spell check dictionary in hunspell or myspell format, with a license which allows you to use it. such a dictionary consists of two files, one with a .dic and one with an .aff file extension. a locale code to describe the language of the dictionary. for example en-us, de-de or da. it is important to choose the right locale code, or the spell checker will not be able to match the language of your dictionary against the language of a web page in order to select the right dictionary to use. if you are creating a new dictionary, as opposed to updating an existing one, please make sure that there is n...
...y is one, try contacting the author to get it updated, or contact amo editors if the author does not respond. packaging a firefox add-on is a zip file renamed to use an .xpi file extension instead of the normal .zip file extension. to create a dictionary add-on, simply create a zip file which contains the following files and folders: my-dictionary.xpi install.rdf dictionaries/ locale-code.dic locale-code.aff the .dic and .aff files must be placed in a subfolder named dictionaries within the zip file. both files must have the locale code as their file name. you also have to add a file named install.rdf to the root of the zip file. this file contains information about your add-on such as name and version number (see below). in addition to these required files, you may add ...
...ple to give your add-on an icon or to describe the license of the dictionary. here is an example of the install.rdf file. you can create and edit it with a plain text editor such as notepad. ...
...if you update an existing dictionary add-on, you must keep the existing em:id, or your users will not be updated to the latest version. the em:versio...
Gecko Logging
it is enabled for all builds, thread-safe, and the preferred alternative to nspr logging. some other mostly-useless information on logging can be found on the nspr logging page. logging framework declaring a log module lazylogmodule defers the creation the backing logmodule in a thread-safe manner and is the preferred method to declare a log module. multiple lazylogmodules with the same name can be declared, all will share the same backing logmodule. this makes it much simpler to share a log module across multiple translation units. ...
...closed in parentheses. moz_log_test(module, level) checks if the module has the given level enabled. module - the log module to use. level - the output level of the message. log level numeric value purpose mozilla logging levels disabled 0 indicates logging is disabled. this should not be used directly in code. error 1 an error occurred, generally something you would consider asserting in a debug build. warning 2 a warning often indicates an unexpected state. info 3 an informational message, often indicates the current program state. debug 4 a debug message, useful for debugging but too verbose to be turned on normally. verbose 5 ...
... a warning often indicates an unexpected state. info 3 an informational message, often indicates the current program state. debug 4 a debug message, useful for debugging but too verbose to be turned on normally. verbose 5 a message that will be printed a lot, useful for debugging program flow and will probably impact performance. ...
..." the rotate and append options described above only apply when logging to a file. the special pref logging.config.log_file can be set at runtime to change the log file being output to. e10s note when a content process is in sandbox, it cannot write to stderr or any file. you may need to set preference security.sandbox.content.level to 0 to see the log. rust we're gradually adding more rust code to gecko, and rust crates typically use a different approach to logging. many rust libraries use the log crate to log messages, which works together with env_logger at the application level to control what's actually printed via rust_log. you can set an overall logging level, though it could be quite verbose: set rust_log="debug" you can also target individual modules by path: set rust_log="s...
Displaying Places information using views
tree = document.getelementbyid("mytree"); // your tree element var showrootnodeintree = true; var view = new placestreeview(showrootnodeintree); // here's the bridge! result.addobserver(view.queryinterface(components.interfaces.nsinavhistoryresultobserver)); tree.view = view.queryinterface(components.interfaces.nsitreeview); in fact this is how the built-in tree view works. it runs code similar to the above when you set its place property or call its load method. while you are free to set up your tree view in this manner, it's not recommended if you are using the built-in view. doing so circumvents updating the view's place attribute, causing it to fall out of sync with the view's query result. use the view's load method or place property instead and let it do the work for you.
...re free to set up your tree view in this manner, it's not recommended if you are using the built-in view. doing so circumvents updating the view's place attribute, causing it to fall out of sync with the view's query result. use the view's load method or place property instead and let it do the work for you. if, on the other hand, you are writing a custom tree view, you will need to write similar code at some point. menu view you can display places information in a popup menu. in firefox 3.6 and earlier requires gecko 1.9.2(firefox 3.6 / thunderbird 3.1 / fennec 1.0) create a built-in menu view by setting the type attribute to "places" on an empty menupopup element (which would be a child of some parent menu element): <menu> <menupopup type="places" /> </menu> the place attr...
...rvice(components.interfaces.nsinavhistoryservice); var opts = histserv.getnewqueryoptions(); var query = histserv.getnewquery(); query.setfolders([bmserv.placesroot], 1); var result = histserv.executequery(query, opts); // here myview is your view, and myview.viewer is some object implementing nsinavhistoryresultobserver. result.addobserver(myview.viewer); more practically, a variation of the code above might be internal to a method on your view. a caller would pass in a result or a query, and you would execute the query and add your view as an observing client using addobserver(). (that's how the load method of the built-in tree view works.) when you let your view observe the result, the result will in turn set the result property on the given nsinavhistoryresultobserver. you should not ...
...eecols> <treecol id="title" label="title" flex="1" primary="true" /> <splitter class="tree-splitter" /> <treecol anonid="fulluri" label="fulluri" flex="1" /> <splitter class="tree-splitter" /> <treecol id="indexinparent" label="indexinparent" /> <splitter class="tree-splitter" /> <treecol id="parity" label="parity" /> </treecols> <treechildren /> </tree> the full code listing is available in the files section of the page below. note that the tree element above does not have the special type attribute common to the built-in views. it's just a regular tree element that you've hooked up to a places query, with none of the convenience properties or methods of the built-in places tree view. if your custom view is used only once in your application, code similar to...
Communicating with frame scripts
chrome code and frame scripts communicate back and forth using a messaging api which can include json-serializable objects as arguments. the api is mostly symmetrical, with one major exception: frame scripts can send asynchronous or synchronous messages to chrome, but chrome can only send asynchronous messages to content. this is an intentional design decision made to prevent content code from making chrome code unresponsive. where absolutely necessary, frame scripts can pass wrappers called cross process object wrappers (also known as cpows) to chrome, and chrome can use these wrappers to get synchronous access to content objects. content to chrome the frame script can choose to send synchronous or asynchronous messages to chrome code. asynchronous messaging to send an asynchr...
...if you're using the message manager in an add-on, a good way to do that is to prefix messages with your add-on's id. after the name, you can pass detailed data as a string or a json-serializable object, and after that you can pass any objects it wants to pass to content as cpows. ...
...message.data); console.log(message.target); console.log(message.objects); } so combining this message listener with the message above will give console output somewhat like this, when the user clicks a <div>: "my-addon@me.org:my-e10s-extension-message" false object { details: "they clicked", tag: "div" } <xul:browser anonid="initialbrowser" ... > { target: <div#searchcontainer> } if your code requires access to a window (for example to run window.opendialog), and your message listener is run from somewhere without access to a window (e.g. an xpcom component), you can access the window of the browser that sent the message with message.target.ownerdocument.defaultview. synchronous messaging to send a synchronous message, the frame script uses the global sendsyncmessage() function: //...
...syncmessage("my-addon@me.org:message-from-chrome"); if you have a window or a global message manager, you need to use the broadcastasyncmessage method: // chrome script window.messagemanager.broadcastasyncmessage("my-addon@me.org:message-from-chrome"); these methods takes one mandatory parameter, which is the message name. all messages share the same namespace, so to avoid conflicts with other code, you'll need to ensure that the names you use are unique. if you're using the message manager in an add-on, a good way to do that is to prefix messages with your add-on's id. after the message name, you can pass detailed data as a string or a json-serializable object: // chrome script messagemanager.sendasyncmessage("my-addon@me.org:message-from-chrome", { details : "some more details" }); t...
Performance
cripts registered during addon startup get executed during session restore. the more expensive they are to execute the longer it will take for the browser to become responsive after startup. frame scripts also get executed on non-restored tabs. all their overhead is thus not just incurred by active tabs but by the total number of tabs in a session. the following examples omit some boilerplate code for the sake of brevity the "better" examples also omit some best practices and only demonstrate how to fix the problem described in their respective subtopics. performance best practices declaring stateless functions once per process bad: // addon.js services.mm.loadframescript("framescript.js", true) // framescript.js const precomputedconstants = // ... function helper(window, action)...
... better: instead of only keeping the state in the parent...
...ation, source: origin}) // <=== sync message! if(resultlist.every((r) => r == true)) return ci.nsicontentpolicy.accept; return ci.nsicontentpolicy.reject_request; } }); // more boilerplate code here this example is a (somewhat condensed) content policy which gets triggered for every network request in a child process to either allow or deny the request. since the code calls to the parent process to check whether a specific request can be allowed it would slow down all page loads, as web pages generally issue dozens of requests. better: instead of only keeping the state in the parent an addon can employ a master-slave architecture where the parent has the authoritative state and replicates it to the child processes in advance so they can act based on their lo...
...t based on their local copy. see the previous chapter on how to efficiently replicate addon state to each process. clean up on addon unload bad: all the previous examples, *even the "better" ones* if your addon is restartless or uses the sdk then updates or the user turning it off and on will load to unload/reload events. not handling those properly can lead to duplicate or conflicting code execution, especially when messages are sent. it can also lead to conflicts between the old and new code. under some circumstances it may even cause exceptions when attempting to register something twice under the same id. better: // addon.js function onunload() { services.mm.removedelayedframescript("resources://my-addon/framescript.js"); services.ppmm.removedelayedprocessscript("resources...
Firefox
firefox is mozilla's popular web browser, available for multiple platforms including windows, macos, and linux on the desktop and all android and ios mobile devices. with broad compatibility, the latest in web technologies, and powerful development tools, firefox is a great choice for both web developers and end users. firefox is an open source project; much of the code is contributed by our huge community of volunteers. here you can learn about how to contribute to the firefox project and you will also find links to information about the construction of firefox add-ons, using the developer tools in firefox, and other topics. learn how to create add-ons for firefox, how to develop and build firefox itself, and how the internals of firefox and its subprojects work. project documentation...
... information about the construction of firefox add-ons, using the developer tools in firefox, and other topics. learn how to create add-ons for firefox, how to develop and build firefox itself, and how the internals of firefox and its subprojects work. project documentation get detailed information about the internals of firefox and its build system, so you can find your way around in the code. developer guide our developer guide provides details on how to get and compile the firefox source code, how to find your way around, and how to contribute to the project. contents experimental features in firefoxthis page lists features that are in nightly versions of firefox along with information on how to activate them, if necessary.firefox and the "about" protocolthere is a lo...
...r to build firefox.multiple firefox profilesa profile in firefox is the collection of settings, customizations, add-ons, and other personalizations that a user has made or installed into their copy of firefox. you can find details about profiles on mozilla's end-user support site.performance best practices for firefox front-end engineersthis guide will help firefox developers working on front-end code produce code which is as performant as possible—not just on its own, but in terms of its impact on other parts of firefox. always keep in mind the side effects your changes may have, from blocking other tasks, to interfering with other user interface elements.privacythis document lists privacy-related documentation.security best practices for firefox front-end engineersthis article will help fi...
...ts of firefox. always keep in mind the side effects your changes may have, from blocking other tasks, to interfering with other user interface elements.privacythis document lists privacy-related documentation.security best practices for firefox front-end engineersthis article will help firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for firefox.site identity buttonthe site identity button is a feature in firefox that gives users more information about the sites they visit. firefox profiles if you find yourself using multiple firefox channels—or just multiple configurations—on a regular basis, you should read how to use multiple firefox profiles by turning firefox's profile manager and other profile management tool...
ChromeWorker
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary if you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object. it works exactly like a standard worker, except that it has access to js-ctypes via a global ctypes object available in the global scope of the worker. examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below. to use a postmessage with...
...ithub and are linked to from the see also section below. to use a postmessage with callback version of chromeworker that features promises, see promiseworker. addons must use absolute urls to load their workers, and those urls have to be using a chrome:// or resource:// protocol (file:// is not accepted). ...
...must first register a resource replacement path, using code like this: var fileuri = services.io.newfileuri(file); services.io.getprotocolhandler('resource'). queryinterface(ci.nsiresprotocolhandler). setsubstitution('my-cool-addon', fileuri); var worker = new worker('resource://my-cool-addon/worker.js'); more references: you can use chromeworker from javascript code modules. see using workers in javascript code modules for details. you can use chromeworker modules in chromeworkers. see using web workers for examples and details. ...
...ubstitution('my-cool-addon', fileuri); var worker = new worker('resource://my-cool-addon/worker.js'); more references: you can use chromeworker from javascript code modules. see using workers in javascript code modules for details. you can use chromeworker modules in chromeworkers. see using web workers for examples and details. see also using web workers using workers in javascript code modules worker sharedworker web workers specification workerglobalscope github :: chromeworker - a fully working demo addon using js-ctypes from a chrome worker. uses winapi example. promiseworker github :: promiseworker - shows how to uses promises as an twist on postmessage feature of chromeworker ...
Interfacing with the Add-on Repository
the add-on repository javascript code module makes it easy for your extension to interface with the amo repository. you an use the code module to get lists of add-ons and even install new add-ons. this article provides some sample code that queries the recommended add-ons list on amo and lets the user click a button to install an add-on from the list. importing the repository code module before you can use the add-on repository api, you need to import the code module: components.utils.import("resource://gre/modules/addonrepository.jsm"); having done this, you can then access the api through the resulting addonrepository object. enabling the recommendation feature in current builds of firefox 4, the recommendation api doesn't work because the preference for the url to query to get recom...
...ules/addonrepository.jsm"); having done this, you can then access the api through the resulting addonrepository object. enabling the recommendation feature in current builds of firefox 4, the recommendation api doesn't work because the preference for the url to query to get recommended add-ons is not included by default; see bug 628785. ...
...ch of the repository, you can use either of the following methods: searchaddons() queries the add-on repository for add-ons matching given search criteria. retrieverecommendedaddons() retrieves a list of recommended add-ons, as determined by the amo site administrators. this example will use the latter, in order to randomly select a recommended add-on and offer to install it. however, the code to perform a search term based query would be very similar. when the user clicks a toolbar button to initiate the query, the following code gets run to start the request: addonrepository.retrieverecommendedaddons(10, this); this asks the repository to fetch up to 10 add-ons, using the object this as the target for callbacks. the callback object needs to implement the searchcallback interface,...
... the pop-up callback function that gets called when the user clicks the button looks to see if there's a non-null addoninstall object reference; if it's null, then the pop-up is displaying an error notification, so ...
PerfMeasurement.jsm
note: at present, perfmeasurement.jsm is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. ...
...note: at present, perfmeasurement.jsm is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. ...
...access to the recorded data. any measurable event that was not being recorded has a value of -1 (that is, 0xffffffffffffffff). note: these values are all zeroed (or set to -1, for events not being measured) when you initialize the perfmeasurement object, then they are not zeroed again unless you explicitly call the reset() method. this lets you accumulate measurements over multiple passes through code that you want to analyze. variable type description cpu_cycles uint64 the number of cpu cycles elapsed. instructions uint64 the number of instructions executed. cache_references uint64 the number of memory accesses that occurred. cache_misses uint64 the number of times memory accesses missed the cache. branch_instructions uint64 the number of branch instructions executed. ...
...ask of all of the event types you want to record; see event mask constants for a list of values. or together all the event types you want to record, and pass that value here. pass perfmeasurement.all to record all event types. return value a new perfmeasurement object configured to record the specified event types. methods canmeasuresomething() indicates whether or not the platform on which your code is running supports this code module. static bool canmeasuresomething(); parameters none. return value if even one of the event types can be recorded, this will return true. otherwise, it returns false. reset() resets all the enabled counters to zero. void reset(); parameters none. start() starts measuring the performance indicators that were specified when the perfmeasurement object was create...
Promise
om being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in exception handling. note: you should always handle, forward, or report errors (rejection reasons). if you see the message "a promise chain failed to handle a rejection", there is likely something to be fixed in the code. see handling errors and common pitfalls below. documentation conventions in documentation, the type of the fulfillment value is usually specified between angular brackets. for example, the os.file.exists function returns a promise that will eventually fulfill with a boolean: promise<boolean> exists(string path); the rejection reason may be specified separately in the function's documentati...
...onfulfill ).catch( onreject ), exceptions thrown in onfulfill will be caught and passed to onreject, which is not the case when just passing onreject to then(). ...
...ject ); the following calls are therefore identical: p.then(undefined, logerror); p.catch(logerror); debugging by design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the then() method. to help with debugging, only when inspecting a promise object manually, you can see more information as special properties that are inaccessible from code (this, at present, is implemented by randomizing the property name, for the lack of more sophisticated language or debugger support). these code-inaccessible, inspectable properties are: {{private:status}}: 0 for pending, 1 for fulfilled, or 2 for rejected. {{private:value}}: fulfillment value or rejection reason, for fulfilled or rejected promises only. {{private:handlers}}: array of objec...
...rivate:value}}: fulfillment value or rejection reason, for fulfilled or rejected promises only. {{private:handlers}}: array of objects holding references to functions registered by the then() method, for pending promises only. examples see the examples page. handling errors and common pitfalls you should report unhandled errors, unless you're handing off the promise to a caller or another code path that will handle the error. // ###### wrong: silently drops any rejection notified by "os.file.exists". os.file.exists(path).then(exists => { if (exists) myread(path); }); // ###### wrong: silently drops any exception raised by "myread". os.file.exists(path).then(exists => { if (exists) myread(path); }, components.utils.reporterror); // correct (for example, might report the exception "my...
PromiseWorker.jsm
or js-ctypes but it is not limited to that. there is no xpcom access, similar to chromeworker. this answers the question "when should i use a promiseworker?", and the answer is, whenever you would normally use a chromeworker, but want postmessage to return promises. the promiseworker object is used to deliver all of the os.file functionality to the main thread. here is the test case from firefox codebase: mozilla dxr :: test_promise.js. promiseworker module consists of two javascript files, promiseworker.jsm and promiseworker.js. promiseworker.jsm path: resource://gre/modules/promiseworker.jsm a javascript code module used by the main thread to create a worker thread and communicate with it. promiseworker.jsm provides basepromiseworker. promiseworker.js path: resource://gre/modules/work...
...tions tell you which content to use in your worker and main thread files, in order to use promiseworker objects. worker file there is some standard templating that must be dropped into the worker file by the developer. the require.js file must be imported with workerglobalscope/importscripts(). next, the promiseworker.js file should be brought in with the require() method. finally, the template code should be added in. the code below is what should be copied and pasted: importscripts('resource://gre/modules/workers/require.js'); let promiseworker = require('resource://gre/modules/workers/promiseworker.js'); // instantiate abstractworker (see below). let worker = new promiseworker.abstractworker() worker.dispatch = function(method, args = []) { // dispatch a call to method `method` with ...
...ransfer data. the first is with atransferlist argument and other with basepromiseworker.meta. both are done by the post function described above. atransferlist to transfer an arraybuffer object, pass an array containing it as atransferlist argument. myworker.post('func', [buffer], null, [buffer]); this is simpler if the you know what to transfer at the callsite. basepromiseworker.meta above code can also be done with the meta object. each special data argument that you want to transfer, you can wrap in a basepromiseworker.meta object. the above example can be rewritten like this: myworker.post('func', [new basepromiseworker.meta(buffer, {transfers: [buffer]})]); this is convenient if the function's arguments are generated by some other functions or passed from somewhere else. post cal...
... = myworker.post('resolvetest', [false]); promise_domyfuncfalse.then( function(aval) { console.log('fullfilled - promise_domyfuncfalse - ', aval); }, function(areason) { console.error('rejected - promise_domyfuncfalse - ', areason); } ).catch( function(acaught) { console.error('caught - promise_domyfuncfalse - ', acaught); } ); result running the code above will log the following information to the console: "fullfilled - promise_domyfunctrue - " "you sent to promiseworker argument of: `true`" bootstrap.js line 8 "rejected - promise_domyfuncfalse - " "you passed in a non-true value for shouldresolve argument and therefore this will reject the main thread promise" bootstrap...
Sqlite.jsm
all operations are asynchronous. use of synchronous storage apis is discouraged because they block the main thread. all the functionality in sqlite.jsm is asynchronous. easier memory management. ...
...a promise-based wrapper around the storage/sqlite interface. sqlite.jsm offers some compelling advantages over the low-level storage xpcom interfaces: automatic statement management. sqlite.jsm will create, manage, and destroy statement instances for you. you don't need to worry about caching created statement instances, destroying them when you are done, etc. this translates to fewer lines of code to talk to sqlite. all operations are asynchronous. use of synchronous storage apis is discouraged because they block the main thread. all the functionality in sqlite.jsm is asynchronous. easier memory management. since sqlite.jsm manages statements for you, it can perform intelligent actions like purging all cached statements not in use, freeing memory in the process. there is even a shrinkmem...
...cess. there is even a shrinkmemory api that will minimize memory usage of the connection automatically. simpler transactions. sqlite.jsm exposes a transaction api built on top of task.jsm that allows transactions to be written as procedural javascript functions (as opposed to a series of callback driven operations). if the function throws, the transaction is automatically rolled back. this makes code easy to write and read. javascript-y api. sqlite.jsm feels like a pure javascript module. the complexities of xpcom are mostly hidden from view. javascript programmers should feel right at home using sqlite.jsm. note: the sqlite.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on. before you can use this module, you need to impor...
...ssing of subsequent rows occurs as if nothing happened. the promise is still resolved (not rejected). the return promise will be rejected with an error instance if the statement did not finish execution fully. the error may have an errors property. if defined, it will be an array of objects describing individual errors. each object has the properties result and message. result is a numeric error code and message is a string description of the problem. if onrow is specified, the returned promise will be resolved with a boolean indicating whether the onrow handler was called. else, the resolved value will be an array of mozistoragerow. executetransaction(func, type) this function is used to execute a database transaction. a transaction is a series of related statements treated as one functio...
Bootstrapping a new locale
ozilla repository. installing mercurial depending on your operating system, you will need to install the correct version of hg on your machine. this document will give you the basic information on how to do that. install the compare-locales utility the next step is to install compare-locales. $ sudo easy_install compare-locales this will download and install the utility. clone the source code the next step is to download a copy of the source code to your local system, using mercurial. you will need to "hg clone" the existing release branch for mozilla so you have all the files locally for you to begin localization. make sure to have the directory where you intend to work as the current path on your terminal. (you should "cd" to the directory before beginning.) in the terminal, ...
...ommand: $ hg clone http://hg.mozilla.org/releases/mozilla-x.x.x/ where "x.x.x" is the existing release branch version. for instance, for firefox 3.6, we use mozilla-1.9.2. refer to l10n:branches for the list of all branches. if you are interested in localizing thunderbird 3, seamonkey 2 or other mozilla projects based on gecko 1.9.1 you'll need to follow the instructions on getting the source-code of the comm-central repository. create a bare-bones localization next, create a base localization. this is done by cloning the en-us (united states english) files into your localization. first, you should specify your locale's language identifier in ab-cd format, where "ab" is the iso 639 language code, and cd is the iso 3166 country code. the "-cd" part is only necessary to differentiate be...
...e the repository remotely. it will be just like working on hg with mozilla, yet you will use the bit bucket platform to start. after your new bit bucket repository is created by the l10n-drivers, please visit the url for your repo. you can do this by entering the following url into your browser: $ https://bitbucket.org/mozillal10n/ab-cd/overview/ (where ab-cd will be replaced by your locale code) at that main page of your newly created bit bucket repo, you'll see the hg commands, $ hg clone http://bitbucket.org/mozillal10n/ab-cd/ ... $ hg pull -u # to pull changes and update $ hg push # to push changes to this repo import existing data? $ cd /path/to/existing/hg/repo/ $ hg push http://bitbucket.org/mozillal10n/ab-cd/ prefer ssh? $ hg clone ssh://hg@bitbucket.org/mozillal10n/ab-cd/...
... ...
Localization and Plurals
you're likely here because you're localizing a .properties file and it had a link to this page. this page is to help explain how to localize these strings so that the correct plural form is 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 ...
...oncatenating strings assuming a particular grammatical structure. the following would be better: components.utils.import("resource://gre/modules/pluralform.jsm"); let downloads = "you have one download.;you have #1 downloads."; let num = 10; // for english, this would display "you have 10 downloads." print(pluralform.get(num, downloads).replace("#1", num); notice in the above example that the code can be written to support placeholders or not use placeholders in some forms of the string. additionally, the localizer has control over where the placeholder is, in relation to the rest of the text. of course, the strings to be localized will be placed in a separate file, such as yourextension.properties, instead of being hardcoded in the javascript code file. the following 3 file snippets sho...
...so for your extension, specify a pluralrule value in the .properties, and call pluralform.makegetter(pluralrulefromproperties), making sure to save the 2 returned functions. (you can use destructured assignment in javascript 1.7 to keep things clean.) the returned functions act just like pluralform.get() and pluralform.numforms(), exc...
...fy a pluralrule value in the .properties, and call pluralform.makegetter(pluralrulefromproperties), making sure to save the 2 returned functions. (you can use destructured assignment in javascript 1.7 to keep things clean.) the returned functions act just like pluralform.get() and pluralform.numforms(), except for the specified plural rule instead of the default plural rule. credits plural form code first implemented for bug 394516 - figure out a remaining-time rounding scheme for minutes -> hours/days plural rules and families derived from gnu gettext documentation. ...
Localizing without a specialized tool
with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation. ...
...the command line should be enough: $ sudo easy_install -u compare-locales to start, be sure to open your command line interface and change your directory to where you are keeping your localization files, the en-us sources $ cd /path/to/your/working/directory now, you will need run compare locales. to do this, enter the following commands, keeping sure to change "x-testing" to the actual locale code of your locale. $ compare-locales mozilla-1.9.2/browser/locales/l10n.ini l10n-mozilla-1.9.2 x-testing for convenience, try saving the output of this command to a text file on your desktop so you can review it as you go. run: $ compare-locales mozilla-1.9.2/browser/locales/l10n.ini l10n-mozilla-1.9.2 x-testing > ~/desktop/x-testing.compare open the x-testing.compare file that is on your desktop. ...
...-right corner of your browser. at the bottom of the list of search engines that appears, you'll see, "manage search engines...". to start, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing and then, type the command mkdir /browser/chrome/browser now, step back out to the broader directory that contains both your l10n base (l10n-mozilla-1.9.2) and the en-us source code (mozilla-1.9.2). you can do this by typing: cd ../../ where each ".." represents the prior sub directory before the main directory where you want to be. you can always check the path by typing pwd once you are in the root working directory with both en-us source and the l10n base, copy the searchbar.dtd file by typing cp mozilla-1.9.2/browser/locales/chrome/browser/searchbar.dtd l10n-mozill...
...n the upper-right corner of your browser. at the second to bottom of the list of search engines that appears, you'll see, "add %s", where %s is replaced by the name of the site. again, to start, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing now, step back out to the broader directory that contains both your l10n base (l10n-mozilla-1.9.2) and the en-us source code (mozilla-1.9.2). you can do this by typing: cd ../../ where each ".." represents the prior sub directory before the main directory where you want to be. you can always check the path by typing pwd once you are in the root working directory with both en-us source and the l10n base, copy the searchbar.dtd file by typing cp mozilla-1.9.2/browser/locales/chrome/browser/search.properties l10n-mo...
Initial setup
you also need to determine if a localization effort already exists for your locale. here we'll go over the accounts you need as well as the tools and their configurations you need to set up before contributing. new or existing before anything else, you need to know if you will be creating a new localization or joining an existing one. this will determine what information is most applicable to you throughout the rest of this guide. ...
..., send an email to the new-locales newsgroup for additional guidance. accounts there are a handful of accounts that you need to be aware of as you begin. they're not required for you to begin contributing, but will be required when you are preparing to produce an official release. for now, simply be aware that these will become important as your efforts progress. these accounts will store your code, contributions, and help you produce an official localization. hg (mercurial) mercurial is the revision control environment that houses the main mozilla source code as well as localized code for each official mozilla localization. you will need this for localizing mozilla applications. hg commit access is not necessary to begin localizing. after you have some experience with hg, you may want ...
...ocale's bugzilla component to the new locales newsgroup. local environment tools similar to accounts, there is a number of environment tools that you should install on your personal computer. these tools will help you to store your contributions, build mozilla applications and language packs, and test your work. hg (mercurial) as noted above, we use mercurial for maintaining mozilla source code and localized code. not only will you need a localization repository to store your localizations, but you need to have it installed and configured on your personal computer as well. you can find everything you need to know about installing and configuring mercurial for your localization work here. compare-locales compare-locales is a python script that helps you check your work without needi...
...are written. you can find the source files and install instructions here. locale switcher or quick locale switcher both locale switcher and quick locale switcher are add-ons for mozilla applications. either one is necessary to enable you to see your work within a mozilla application. you can install either by searching for them in firefox's add-ons manager or following these links. a solid, unicode-based, text editor here are some suggestions: windows: notepad++ or notepad2 gnu/linux: vim, gedit or kate mac os x: textwrangler gnu make make is a tool which controls the generation of executables. you can find version 3.79.1 or higher here. unfortunately, other varieties of make won't do. end of initial setup now that you've finished your initial setup, it's time for the best...
gettext
t keyword for regular messages is gettext() and _(). for messages with plural support, the default keyword is ngettext(). a definition of a string with plurals takes three arguments: the singular form of the english string, the plural form of the english string, and the number basing on which the function will return the correct (singular or plural) form of the string. consider the following code snippet: <?php $num = 1; printf(ngettext("%d user likes this.", "%d users like this.", $num), $num); ?> depending on the value of the $num variable, this code will either use the singular ("user likes) or the plural ("users like") form of the string. notice that you need to pass the $num variable twice. first in the ngettext() call, where it will be used to determine which form of the string...
...in the above example, $num equals 1, so the string returned (for english) will be %d user likes this. the second time the $num variable is passed in the printf() call, which at this point of interpretation looks something like printf("%d user likes this.", $num);. the %d in the first argument (which is the string returned by gettext) will be replaced with the value of $num. for english, the above code will produce the following output: 1 user likes this. the string definition in the messages.po file will look like this: #: file.php:3 #, php-format msgid "%d user likes this." msgid_plural "%d users like this." msgstr[0] "" msgstr[1] "" depending on the localizer's target language and its rules for creating plural forms, there might be another field for translation, e.g. msgstr[2]. gettext will...
...ges.po file will look like this: #: file.php:3 #, php-format msgid "%d user likes this." msgid_plural "%d users like this." msgstr[0] "" msgstr[1] "" depending on the localizer's target language and its rules for creating plural forms, there might be another field for translation, e.g. msgstr[2]. gettext will return one of the msgstrs, depending on the number passed to the gettext function in the code ($num in the above example). to determine which form to return, gettext uses a plural rule, which should be declared in the po file header. for example, for english, the plural rule is of the following form: plural-forms: nplurals=2; plural=n != 1; the first part defines the number of different plural forms (2). the second part is evaluated and the result of the evaluation is used to choose the ...
...$num = 1; // l10n: this is another block comment that will be extracted by xgettext. printf(n___("%d user likes this.", "%d users like this.", $num), $num); // l10n: this block comment will not be extracted by xgettext because it's two lines above the gettext function call. $num = 4; printf(n___("%d user likes this.", "%d users like this.", $num, 'another unique context string'), $num); ?> this code produces the following output: a simple string. a string with context. 1 user likes this. 4 users like this. to extract the strings from the php file, use xgettext. you can specify the function calls to look for with the --keyword option. for example, --keyword=n___:1,2,4c tells xgettext to look for n___() calls, and extract the first argument as the singular string, the second argument as the p...
Mozilla Style System Documentation
ument in the order defined by the css cascade and finds the style rules (interface nsistylerule) thatmatch the content node or content node + pseudo-element pair. (the "non-element" style contexts are defined never to match any rules.) these interfaces nsistylesheet and nsistylerule correspond to the css concepts of style sheets and style rules, except they are more general, and are used by other code that needs to add style information to the document. for the css stylesheets, this process corresponds to css selector matching. the output of css selector matching as defined by the css specification is an ordered list of rules, where the order determines which declarations override other declarations. (in css,declarations are the property-value pairs within style rules. in mozilla, nscssdeclara...
...the depth of a node in the tree corresponds to the number of rules matched. therefore, inherited structs are cached on the style context (but only the top style contexts pointing to them actually "owns" them), but structs that are shared between rule nodes are stored only on the highest rule node to which they apply and then retrieved from that most upper rule node every time they are needed. the code that does this sharing work is mostly in nsstylecontext::getstyledata, nsrulenode::getstyledata, and nsrulenode::walkruletree. when nsrulenode::walkruletree computes a struct, it walks the rules, starting with the style context's rule node, towards the root of the rule tree. it uses the appropriate declaration struct and has each rule fill in any properties specified by that rule that are not fi...
... of the rule tree is reached. then the style struct is computed from the declaration and stored at the appropriate location in the rule tree or on the style context. problems: dynamic style changes often destroy too much data. css stylesheet backend css stylesheet loading [this section needs to be written. i'm reluctant to write it both since i don't know much about it.] problems:a bunch the code needs to be rewritten to prevent stylesheets from blocking the parser and to reduce string copying (although that partly goes with parsing).] parsing stylesheet representation problems: the stylesheet representation uses way too much memory. other nsistylesheet implementations problems: some of the html style information is implemented in the content node classes. it should be consolidated s...
...o prevent stylesheets from blocking the parser and to reduce string copying (although that partly goes with parsing).] parsing stylesheet representation problems: the stylesheet representation uses way too much memory. other nsistylesheet implementations problems: some of the html style information is implemented in the content node classes. it should be consolidated so that the style system code can be moved back within the layout dll and nsistylecontext can be de-com-ified. original document information author(s): l. david baron last updated date: june 6, 2003 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Memory reporting
this is most obviously used in about:memory and telemetry. this document describes things that you should know when writing a memory reporter. memory reporters a memory reporter makes one or more memory measurements (a.k.a. reports). ...
...e've had multiple bugs in the past with counter-based reporters. the cost of reporting isn't incurred unless the memory reporter is queried. they provide more information to dmd, which is a tool that helps keep about:memory's "heap-unclassified" number low. see below for more details. sometimes counter-based reporters are unavoidable, particularly when writing memory reporters for third-party code that cannot be modified. a simple example imagine a simple string class with the following data fields: class mystring { private: char *mbuffer; // heap-allocated size_t mlen; // ... methods ... } here are what the measurement functions (yes, functions) should look like for this class. size_t mystring::sizeofexcludingthis(mozilla::mallocsizeof amallocsizeof) const { return ...
... // no sometimes memory reporters are stand-alone objects, like the mystringreporter example above. but often you'll have a singleton object that needs measuring, in which case it is usually better not to have a separate reporter object, but instead for the singleton object to implement nsimemoryreporter, and thus measure and report its own memory consumption. ...
...this helps drive about:memory's heap-unclassified number down. it detects certain defects in existing heap memory reporters: if non-heap memory is reported, or if a heap block is partially reported or double-reported. ...
Emscripten
emscripten is an llvm to javascript compiler. it takes llvm bytecode (e.g. generated from c/c++ using clang, or from another language) and compiles that into javascript, which can be run on the web. important: this page provides a very brief introduction to what emscripten is. to get started with emscripten, go to the official emscripten wiki. using emscripten, you can compile c and c++ code into javascript compile any other code that can be translated into llvm bytecode into javascript. ...
...n be run on the web. important: this page provides a very brief introduction to what emscripten is. to get started with emscripten, go to the official emscripten wiki. using emscripten, you can compile c and c++ code into javascript compile any other code that can be translated into llvm bytecode into javascript. ...
... with emscripten, go to the official emscripten wiki. using emscripten, you can compile c and c++ code into javascript compile any other code that can be translated into llvm bytecode into javascript. compile the c/c++ runtimes of other languages into javascript, and then run code in those other languages in an indirect way (this has been done for python and lua)! emscripten makes native code immediately available on the web: a platform that is standards-based, has numerous independent compatible implementations, and runs everywhere from pcs to ipads. with emscripten, c/c++ developers don’t have the high cost of porting code manually to javascript — or having to learn javascript at all. web developers also benefit, as they can use the many thousands of pre-existing native utiliti...
...d, has numerous independent compatible implementations, and runs everywhere from pcs to ipads. with emscripten, c/c++ developers don’t have the high cost of porting code manually to javascript — or having to learn javascript at all. web developers also benefit, as they can use the many thousands of pre-existing native utilities and libraries in their sites. practically any portable c or c++ codebase can be compiled into javascript using emscripten, ranging from high performance games that need to render graphics, play sounds, and load and process files, through to application frameworks like qt. emscripten generates fast code — its default output format is asm.js , a highly optimizable subset of javascript that can execute at close to native speed in many cases. note: sound interest...
L20n Javascript API
selector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); ctx.registerlocales(defaultlocale: string?, availablelocales: array<string>?) register the default locale of the context instance, as well as all other locales available to the context instance before the language negotiation. locales are referenced by their bcp 47 language codes. ctx.registerlocales('en-us', ['ar', 'es-ar', 'es-es', 'en-us', 'fr', 'pl']); defaultlocale is the original language of the context instance and will be used as the last fallback locale if other locales are registered. if it is undefined, or if registerlocales hasn't been called at all, the context instance will create a special locale called i-default to be used as the default. availablel...
...synchronously by the negotiator registered by registerlocalenegotiator. ctx.requestlocales('pl'); ctx.requestlocales('fr-ca', 'fr'); if requestedlocales argument list is empty or undefined, the default locale from registerlocales will be used. ctx.requestlocales('pl'); if registerlocales hasn't been called, the special i-default locale is used, which means that the following minimal code is valid and will result in a fully operational context instance. var ctx = l20n.getcontext(); ctx.addresource('<hello "hello, world!">'); ctx.requestlocales(); requestlocales can be called multiple times after the context instance emitted the ready event, in order to change the current language fallback chain, for instance if requested by the user. ctx.supportedlocales a read-only propert...
...ntified by a url to the context instance. the resource is added to all registered locales. ctx.linkresource('../locale/strings.l20n'); ctx.linkresource(template: function) add a resource identified by a url to the context instance. the url is constructed dynamically when you call requestlocales. the function passed to linkresource (called a template function) takes one argument which is the code of the current locale, which needs to be first registered with registerlocales. ctx.linkresource(function(locale) { return '../locales/' + locale + '/strings.l20n'; }); the resource is added to all registered locales. if there are no registered locales (see registerlocales), the default i-default locale is used. in this case, addresource(string) and linkresource(string) might be better sui...
...tity called id. if passed, ctxdata is a simple hash object with a list of variables that extend the context data available for the evaluation of this entity. returns an object with the following properties: value: the string value of the entity, attributes: an object of evaluated attributes of the entity, globals: a list of global variables used while evaluating the entity, locale: locale code of the language the entity is in; it can be different than the first locale in the current fallback chain if the entity couldn't be evaluated and a fallback translation had to be used. ctx.localize(ids: array<string>, callback: function) registers a callback which fires when all entities listed in ids have been retrieved. ctx.localize(['hello', 'about'], function(l10n) { var node = documen...
AsyncTestUtils extended framework
the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird. see mailnews automated testing for a description of the other testing mechanisms. ...
...o call async_driver. if you have the following types of listeners you can use the following pre-defined helpers: nsiurllistener: asyncurllistener (predefined). if you need to wrap an existing url listener or need a callback or fancy promise, create an instance of asyncurllistener. copy listener: asynccopylistener. bringing messages into the picture synthetic set definitions most of the code involved in creating synthetic messages takes an object that defines how to generate the set. the following is a list of frequently used attributes where the default value is listed after the attribute name. there are more attributes you can specify; consult the documentation for more information. (see the bottom of this page for links to the source files.) count: 10 the number of messages th...
...cify two recipients. cc: (none) a list of recipients like 'to', but in this case the default is zero recipients. from: (automatically generated) a list whose first element is a (display) name and second element is an email address. for example, {count: 4, from: ["john doe", "john_doe@example.com"]} would result in four messages from john doe to random recipients. synthetic message sets the code that creates synthetic message sets returns instances of the syntheticmessageset class. this class not only holds references to the syntheticmessage instances, but it also tracks what folders they were injected into as well as what folders you move them to. this allows you to get at the nsimsgdbhdr instances directly. keep in mind that the class is not magic and will lose track of the message hea...
...logged to the error console (like you see if you go to the "tools | error console" menu). messagegenerator.js: provides the syntheticmessage abstraction and messagegenerator class that can generate one or more syntheticmessages at a time. the messagescenariofactory produces specific pre-configured message threading configurations using fresh messages (important in avoiding duplicate messages for code that cares, like gloda). messagemodifier.js: slightly misnamed, this provides the syntheticmessageset abstraction that is a set abstraction for syntheticmessages that also tracks what folders they got injected into and provides code to directly manipulate or aid other code that wants to directly manipulate them. messageinjection.js: all the logic for injecting messages into folders via local / ...
NSPR Contributor Guide
ting public api item in nspr cannot change. should you need to have a similar api, with some slightly different behavior or different function prototype, then suggest a new api with a different name. c language api the nspr api is a c language api. please do not contribute java, c or other language wrappers. coding style nspr does not have a documented coding style guide. look at the extant code. make yours look like that. some guidelines concerning naming conventions can be found in nspr naming conventions in the nspr reference. see also: xxx ownership of your contribution when you contribute something to nspr, you must have intellectual property rights to that contribution. this means that you cannot give us something you snatched from somewhere else;. it must be your own invention,...
...r public typedefs, enums, macros and functions. see: prshm.h as an example of how your header file(s) should be documented. source file descriptions. provide descriptive documentation in your source (*.c) files. alas, we have no source files documented as we think they should be. the following are some general guidelines to use when implementing new features: don't export global variables your code must be thread safe you must provide test cases that test all apis you are adding. see: [#testcases test cases] new libraries all the guidelines applicable to [#newfeatures new features] applies to new libraries. for purposes of this paper, a "new library" is defined as a libary under the mozilla/nsprpub/lib directory tree and built as a separate library. these libraries exist, for the most p...
...afe you must provide test cases that test all apis you are adding. see: [#testcases test cases] new libraries all the guidelines applicable to [#newfeatures new features] applies to new libraries. for purposes of this paper, a "new library" is defined as a libary under the mozilla/nsprpub/lib directory tree and built as a separate library. these libraries exist, for the most part, as "legacy" code from nspr 1.0. [note that the current nspr module owners do not now nor never have been involved with nspr 1.0.]. such is life. that said: there are some libraries that implement functions intended for use with applications using nspr, such as ...nsprpub/lib/libc/plgetopt.*. generally useful platform abstractions you agree to sustain, bug fix may rely on the nspr api may not rely on any oth...
...es that implement functions intended for use with applications using nspr, such as ...nsprpub/lib/libc/plgetopt.*. generally useful platform abstractions you agree to sustain, bug fix may rely on the nspr api may not rely on any other library api new platform ports all nspr api items must be implemented platform specific headers in pr/include/md/_platformname.[h!cfg] platform specific code in pr/src/md/platform/*.c make rules in config/_platform.mk documentation the files for nspr's documentation are maintained using a proprietary word processing system [don't ask]. document your work as described in [#newfeatures new features]. use the style of other nspr documentation. we will see that your documentation is transcribed into the appropriate word processor and the derived html ...
Cryptography functions
the public functions listed here perform cryptographic operations based on the pkcs #11 interface. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. ...
...nction listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
... sec_dersigndata mxr 3.2 and later sec_destroycrl mxr 3.2 and later sec_findcrlbydercert mxr 3.2 and later sec_findcrlbyname mxr 3.2 and later sec_lookupcrls mxr 3.2 and later sec_newcrl mxr 3.2 and later sec_quickderdecodeitem mxr 3.6 and later seckey_cachestaticflags mxr 3.10 and later seckey_converttopublickey mxr 3.2 and later seckey_copyprivatekey mxr 3.2 and later seckey_copypublickey mxr 3.6 and later seckey_copysubjectpublickeyinfo mxr 3.4 and later ...
...later seckey_copypublickey mxr 3.6 and later seckey_copysubjectpublickeyinfo mxr 3.4 and later seckey_createdhprivatekey mxr 3.3 and later seckey_createecprivatekey mxr 3.8 and later seckey_createsubjectpublickeyinfo mxr 3.2 and later seckey_decodedersubjectpublickeyinfo mxr 3.4 and later seckey_destroyprivatekey mxr 3.2 and later seckey_ecparamstobasepointorderlen mxr 3.12 and later seckey_ecparamstokeysize mxr 3.12 and later seckey_destroypublickeylist mxr 3.4 and later seckey_destroysubjectpublickeyi...
Encrypt Decrypt MAC Keys As Session Objects
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
... strcpy(header, mac_header); strcpy(trailer, mac_trailer); break; case pad: strcpy(header, pad_header); strcpy(trailer, pad_trailer); break; } pr_fprintf(outfile, "%s\n", header); printashex(outfile, buf, len); pr_fprintf(outfile, "%s\n\n", trailer); return secsuccess; } /* * initialize for encryption or decryption - common code */ pk11context * cryptinit(pk11symkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); ...
...ypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop returned %d\n", rv); goto cleanup; } cleanup: if (rv != secs...
Encrypt and decrypt MAC using token
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
... strcpy(header, mac_header); strcpy(trailer, mac_trailer); break; case pad: strcpy(header, pad_header); strcpy(trailer, pad_trailer); break; } pr_fprintf(outfile, "%s\n", header); printashex(outfile, buf, len); pr_fprintf(outfile, "%s\n\n", trailer); return secsuccess; } /* * initialize for encryption or decryption - common code */ pk11context * cryptinit(pk11symkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); ...
...ypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop returned %d\n", rv); goto cleanup; } cleanup: if (rv != secs...
NSS 3.14 release notes
support for certificate signatures using the md5 hash algorithm is now disabled by default. the nss license has changed to mpl 2.0. previous releases were released under a mpl 1.1/gpl 2.0/lgpl 2.1 tri-license. for more information about mpl 2.0, please see http://www.mozilla.org/mpl/2.0/faq.html. for an additional explantation on gpl/lgpl compatibility, see security/nss/copying in the source code. export and des cipher suites are disabled by default. non-ecc aes and triple des cipher suites are enabled by default. nss 3.14 source tarballs can be downloaded from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_rtm/src/. the cvs tag is nss_3_14_rtm. new in nss 3.14 the sections that follow discuss specific changes in nss 3.14 in more detail. support for tls 1.1 (...
...//bugzilla.mozilla.org/show_bug.cgi?id=774547) the choice of client_version sent during renegotiations has changed. see the "changes" section below. experimental support for dtls (rfc 4347) and dtls-srtp (rfc 5764) dtls client and server support has been added in nss 3.14. because the test coverage and interoperability testing is not yet at the same level as other nss code, this feature should be considered "experimental" and may contain bugs. the following functions have been added to the libssl library included in nss 3.14: dtls_importfd (in ssl.h) dtls_gethandshaketimeout (in ssl.h) ssl_getsrtpcipher (in ssl.h) ssl_setrtpciphers (in ssl.h) support for aes-gcm support for aes-gcm has been added to the nss pkcs...
...cific security policies, allowing libpkix to continue discovering certificate paths until it can find a chain that satisfies the policies. ...
...these changes have the observed effect of doubling rsa performance. bug 792681 - new default cipher suites the default cipher suites in nss 3.14 have been changed to better reflect the current security landscape. the defaults now better match the set that most major web browsers enable by default. bug 783448 - when performing an ssl renegotiation, the cli...
NSS 3.18 release notes
the tstclnt test utility program has new command-line options -c, -d, -b and -r. use -c one, two or three times to print information about the certificates received from a server, and information about the locally found and trusted issuer certificates, to diagnose server side configuration issues. it is possible to run tstclnt without providing a database (-d). a pkcs#11 l...
...roviding a database (-d). a pkcs#11 library that contains root ca certificates can be loaded by tstclnt, which may either be the nssckbi library provided by nss (-b) or another compatible library (-r). new functions in certdb.h sec_checkcrltimes - check the validity of a crl at the given time. sec_getcrltimes - extract the validity times from a crl. in p12.h sec_pkcs12decoderrenamecertnicknames - call an application provided callback for each certificate found in a sec_pkcs12decodercontext. in pk11pub.h __pk11_setcertificatenickname - this is an internal symbol for nss use only, as with all exported nss symbols that have a leading underscore '_'. applications that use or depend on these symbols can and will break in future nss releases. new types ...
... in pk11pub.h __pk11_setcertificatenickname - this is an internal symbol for nss use only, as with all exported nss symbols that have a leading underscore '_'. applications that use or depend on these symbols can and will break in future nss releases. new types in p12.h sec_pkcs12nicknamerenamecallback - a function pointer definition. an application that uses sec_pkcs12decoderrenamecertnicknames must implement a callback function that implements this function interface. notable changes in nss 3.18 the highest tls protocol version enabled by default has been increased from tls 1.0 to tls 1.2. similarly, the highest dtls protocol version enabled by default has been increased from dtls 1.0 to dtls 1.2. the default key size used by certutil when creating an rsa...
...tocol version enabled by default has been increased from dtls 1.0 to dtls 1.2. the default key size used by certutil when creating an rsa key pair has been increased from 1024 bits to 2048 bits. on mac os x, by default the softokn shared library will link with the sqlite library installed by the operating system, if it is version 3.5 or newer. ...
Encrypt Decrypt_MAC_Using Token
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
... strcpy(header, mac_header); strcpy(trailer, mac_trailer); break; case pad: strcpy(header, pad_header); strcpy(trailer, pad_trailer); break; } pr_fprintf(outfile, "%s\n", header); printashex(outfile, buf, len); pr_fprintf(outfile, "%s\n\n", trailer); return secsuccess; } /* * initialize for encryption or decryption - common code. */ pk11context * cryptinit(pk11symkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); ...
...ypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code. */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop returned %d\n", rv); goto cleanup; } cleanup: if (rv != sec...
EncDecMAC using token object - sample 3
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...: strcpy(header, iv_header); strcpy(trailer, iv_trailer); break; case mac: strcpy(header, mac_header); strcpy(trailer, mac_trailer); break; case pad: strcpy(header, pad_header); strcpy(trailer, pad_trailer); break; } pr_fprintf(outfile, "%s\n", header); printashex(outfile, buf, len); pr_fprintf(outfile, "%s\n\n", trailer); return secsuccess; } /* * initialize for encryption or decryption - common code */ pk11context * cryptinit(pk11symkey *key, unsigned char *iv, unsigned int ivlen, ck_mechanism_type type, ck_attribute_type operation) { secitem ivitem = { sibuffer, iv, ivlen }; pk11context *ctx = null; secitem *secparam = pk11_paramfromiv(ckm_aes_cbc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_a...
...bc, &ivitem); if (secparam == null) { pr_fprintf(pr_stderr, "crypt failed : secparam null\n"); return null; } ctx = pk11_createcontextbysymkey(ckm_aes_cbc, operation, key, secparam); if (ctx == null) { pr_fprintf(pr_stderr, "crypt failed : can't create a context\n"); goto cleanup; } cleanup: if (secparam) { secitem_freeitem(secparam, pr_true); } return ctx; } /* * common encryption and decryption code */ secstatus crypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) { secstatus rv; rv = pk11_cipherop(ctx, out, outlen, maxout, in, inlen); if (rv != secsuccess) { pr_fprintf(pr_stderr, "crypt failed : pk11_cipherop returned %d\n", rv); goto cleanup; } cleanup: if (rv != secsuccess) { return rv; } return secsuccess; } /* * de...
NSS sources building testing
find the directory that contains the highest version number. because nss depends on the base library nspr, you should download the archive that combines both nss and nspr. if you are a software developer and intend to contribute enhancements to nss, you should obtain the latest development snapshot of nss using mercurial/hg (a distributed source control management tool). in order to get started, anonymous read-only access is sufficient. ...
...read-only access is sufficient. create a new directory on your computer that you will use as your local work area, and run the following commands. hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss after the above commands complete, you should have two local directories, named nspr and nss, next to each other. (historical information: nspr and nss source code have recently been re-organized into a new directory structure. in past versions, all files were located in a directory hierarchy that started with the "mozilla" prefix. the nspr base library was located in directory mozilla/nsprpub. the subdirectories dbm, security/dbm, security/coreconf, security/nss were part of the nss sources.) the nss directory contains the following important subdirectori...
...in a directory hierarchy that started with the "mozilla" prefix. the nspr base library was located in directory mozilla/nsprpub. the subdirectories dbm, security/dbm, security/coreconf, security/nss were part of the nss sources.) the nss directory contains the following important subdirectories: nss/coreconf contains knowledge for cross platform building. nss/lib contains all the library code that is used to create the runtime libraries used by applications. nss/cmd contains a set of various tool programs that are built using nss. several tools are general purpose and can be used to inspect and manipulate the storage files that software using the nss library creates and modifies. other tools are only used for testing purposes. however, all these tools are good examples of how to wr...
...pect and manipulate the storage files that software using the nss library creates and modifies. other tools are only used for testing purposes. however, all these tools are good examples of how to write software that makes use of the nss library. nss/test this directory contains the nss test suite, which is routinely used to ensure that changes to nss don't introduce regressions. nss/gtests code for nss unit tests running in googletest. it is important to mention the difference between internal nss code and exported interfaces. software that would like to use the nss library must use only the exported interfaces. these can be found by looking at the files with the .def file extension, inside the nss/lib directory hierarchy. any c function that isn't contained in .def files is strictly ...
PKCS 7 functions
the public functions listed here perform pkcs #7 operations required by mail and news applications and by some of the nss tools. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
...ctions listed here perform pkcs #7 operations required by mail and news applications and by some of the nss tools. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
...3.4 and later sec_pkcs7createcertsonly mxr 3.3 and later sec_pkcs7createdata mxr 3.2 and later sec_pkcs7createencrypteddata mxr 3.2 and later sec_pkcs7createenvelopeddata mxr 3.2 and later sec_pkcs7createsigneddata mxr 3.2 and later sec_pkcs7decodeitem mxr 3.2 and later sec_pkcs7decoderabort mxr 3.9 and later sec_pkcs7decoderfinish mxr 3.2 and later sec_pkcs7decoderstart mxr 3.2 and later sec_pkcs7decoderupdate mxr 3.2 and later sec_pkcs7decryptcontents mxr 3.2 and later sec_...
...r 3.9 and later sec_pkcs7decoderfinish mxr 3.2 and later sec_pkcs7decoderstart mxr 3.2 and later sec_pkcs7decoderupdate mxr 3.2 and later sec_pkcs7decryptcontents mxr 3.2 and later sec_pkcs7destroycontentinfo mxr 3.2 and later sec_pkcs7encode mxr 3.3 and later sec_pkcs7encodeitem mxr 3.9.3 and later sec_pkcs7encoderabort mxr 3.9 and later sec_pkcs7encoderfinish mxr 3.2 and later sec_pkcs7encoderstart mxr 3.2 and later sec_pkcs7encoderupdate mxr 3.2 and later sec_pkcs7ge...
NSS tools : cmsutil
n and arguments are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options options specify an action. option arguments modify an action. the options and arguments for the cmsutil command are defined as follows: -d decode a message. -c encrypt a message. -e envelope a message. -o create a certificates-only message. -s sign a message. arguments option arguments modify an action and are lowercase. -c content use this detached content (decode only). -d dbdir specify the key/certificate database directory (default is ".") -e envfile specify a file containing an enveloped message for a set of recipients to which you wo...
...specify a file containing an enveloped message for a set of recipients to which you would like to send an encrypted message. if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only). -g include a signing time attribute (sign only). -h num generate email headers with info about cms message (decode only). -i infile use infile as a source of data (default is stdin). -n nickname specify nickname of certificate to sign with (sign only). -n suppress output of contents (decode only). -o outfile use outfile as a destination of data (default is stdout). -p include an s/mime capabilities attribute. -p password use password as key database password. -r recipient1,recipient2, ... specify list of reci...
...ed or enveloped message. for certificates-only message, list of certificates to send. -t suppress content in cms message (sign only). -u certusage set type of cert usage (default is certusageemailsigner). -y ekprefnick specify an encryption key preference by nickname. usage encrypt example cmsutil -c [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, . . ." -e envfile decode example cmsutil -d [-i infile] [-o outfile] [-d dbdir] [-p password] [-c content] [-n] [-h num] envelope example cmsutil -e [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, ..." certificate-only example cmsutil -o [-i infile] [-o outfile] [-d dbdir] [-p password] -r "cert1,cert2, . . ." sign message example cmsutil -s [-i infile] [-o outfile] [-d dbdir] [-p password...
...lso additional resources nss is maintained in conjunction with pki and security-related projects through mozilla dn fedora. the most closely-related project is dogtag pki, with a project wiki at [1]http://pki.fedoraproject.org/wiki/. for information specifically about nss, the nss project wiki is located at [2]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: pki-devel@redhat.com and pki-users@redhat.com irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape and now with red hat. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license version 2. references visible link...
NSS tools : ssltab
client to the server is in blue; the server's reply is in red. when used with looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. ...
...oping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same ...
...} length = 160 (0xa0) < encrypted > } ] <-- [ sslrecord { 0: 17 03 00 00 df |....ß type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted > } sslrecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted > } ] server socket closed. example 2 the -s option turns on ssl parsing. because the -x option is not used in this example, undecoded values are output as raw data. the output is routed to a text file. $ ssltap -s -p 444 interzone.mcom.com:443 > s.txt output connected to interzone.mcom.com:443 --> [ alloclen = 63 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 36 (0x24) sid-length = 0 (0x00) challenge-length = 16 (0x10) cipher-suites = { (0x010080) ssl2/rsa/rc4-128/md5 (0x020080) ssl2/rsa/rc4-40/md5 (...
...s/. additional resources nss is maintained in conjunction with pki and security-related projects through mozilla dn fedora. the most closely-related project is dogtag pki, with a project wiki at [2]http://pki.fedoraproject.org/wiki/. for information specifically about nss, the nss project wiki is located at [3]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: pki-devel@redhat.com and pki-users@redhat.com irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape and now with red hat and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license version 2. references visi...
NSS tools : ssltap
client to the server is in blue; the server's reply is in red. when used with looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. ...
...oping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the same ...
...} length = 160 (0xa0) < encrypted > } ] <-- [ sslrecord { 0: 17 03 00 00 df |....ß type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted > } sslrecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted > } ] server socket closed. example 2 the -s option turns on ssl parsing. because the -x option is not used in this example, undecoded values are output as raw data. the output is routed to a text file. $ ssltap -s -p 444 interzone.mcom.com:443 > s.txt output connected to interzone.mcom.com:443 --> [ alloclen = 63 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 36 (0x24) sid-length = 0 (0x00) challenge-length = 16 (0x10) cipher-suites = { (0x010080) ssl2/rsa/rc4-128/md5 (0x020080) ssl2/rsa/rc4-40/md5 (...
...s/. additional resources nss is maintained in conjunction with pki and security-related projects through mozilla dn fedora. the most closely-related project is dogtag pki, with a project wiki at [2]http://pki.fedoraproject.org/wiki/. for information specifically about nss, the nss project wiki is located at [3]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: pki-devel@redhat.com and pki-users@redhat.com irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape and now with red hat and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license version 2. references visi...
ssltyp.html
nctions also use types defined by nspr and described in the nspr reference. <a name="> many of the structures presented here (certcertdbhandle, certcertificate, pk11slotinfo, and seckeyprivatekey) are opaque--that is, they are types defined as structures (for example, certcertdbhandlestr) that may change in future releases of network security services. as long as you use the form shown here, your code will not need revision. certcertdbhandle an opaque handle structure for open certificate databases. syntax #include <certt.h> typedef struct certcertdbhandlestr certcertdbhandle; certcertificate an opaque x.509 certificate object. syntax #include <certt.h> typedef struct certcertificatestr certcertificate; description certificate structures are shared objects. when an applicati...
...pk11slotinfo an opaque structure representing a physical or logical pkcs #11 slot. syntax #include <pk11expt.h> typedef struct pk11slotinfostr pk11slotinfo; secitem a structure that points to other structures. syntax #include <seccomon.h> #include <prtypes.h> #include <secport.h> typedef enum { sibuffer, sicleardatabuffer, sicipherdatabuffer, sidercertbuffer, siencodedcertbuffer, sidernamebuffer, siencodednamebuffer, siasciinamestring, siasciistring, sideroid } secitemtype; typedef struct secitemstr secitem; struct secitemstr { secitemtype type; unsigned char *data; unsigned int len; }; description a secitem structure can be used to associate your own data with an ssl socket. to free a structure pointed to by a secitem, and...
... pointer to a secitem structure. freeitem when pr_false, free only the structure pointed to. otherwise, free both the structure pointed to and the secitem structure itself. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description this function frees the memory associated with the structure to which the specified item points, when that structure is no longer used. when freeitem is not pr_false, also frees the item structure itself. secitem_zfreeitem zeroes and frees the memory associated with a secitem structure. syntax #include <prtypes.h> secstatus secitem_zfreeitem ( secitem *item, prboo...
... pointer to a secitem structure. freeitem when pr_false, free only the structure pointed to. otherwise, free both the structure pointed to and the secitem structure itself. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description this function is similar to secitem_freeitem, except that it overwrites the structures to be freed with zeroes before it frees them. zeros and frees the memory associated with the structure to which the specified item points, when that structure is no longer used. when freeitem is not pr_false, also zeroes and frees the item structure itself. ...
NSS Tools ssltap
lient to the server is in blue; the server's reply is in red. when used with looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. ...
...ng mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the parsed ssl output. -x turn on hex/ascii printing of undecoded data inside parsed ssl records. used only with the -s option. this option uses the sa...
...r. this is because, by default, the tool closes down after the first connection is complete, so the browser is not able to load images. to make the tool continue to accept connections, switch on looping mode with the -l option. the following examples show the output from commonly used combinations of options. example 1 the s and x options in this example turn on ssl parsing and show undecoded values in hex/ascii format. the output is routed to a text file. command ssltap.exe -sx -p 444 interzone.mcom.com:443 > sx.txt output output connected to interzone.mcom.com:443--> [alloclen = 66 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 39 (0x27) sid-length = 0 (0x00) challenge-length = 16 (0x10) ...
...type = 23 (application_data) version = { 3,0 } length = 223 (0xdf) < encrypted >}sslrecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted >}]server socket closed. example 2 the -s option turns on ssl parsing. because the -x option is not used in this example, undecoded values are output as raw data. the output is routed to a text file. command ssltap.exe -s -p 444 interzone.mcom.com:443 > s.txt output connected to interzone.mcom.com:443--> [alloclen = 63 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 36 (0x24) sid-length = 0 (0x00) challenge-length = 16 (0x10) ciphe...
NSS tools : cmsutil
Mozilla › Projects › NSS › tools › cmsutil
he options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options options specify an action. option arguments modify an action. the options and arguments for the cmsutil command are defined as follows: -d decode a message. -c encrypt a message. -e envelope a message. -o create a certificates-only message. -s sign a message. arguments option arguments modify an action and are lowercase. -c content use this detached content (decode only). -d dbdir specify the key/certificate database directory (default i...
...ients to which you would like to send an encrypted message. if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only). -g include a signing time attribute (sign only). -h num generate email headers with info about cms message (decode only). -i infile use infile as a source of data (default is stdin). -n nickname specify nickname of certificate to sign with (sign only). -n suppress output of contents (decode only). -o outfile use outfile as a destination of data (default is stdout). -p include an s/mime capabilities attribute. -p password ...
... certificates to send. -t suppress content in cms message (sign only). -u certusage set type of cert usage (default is certusageemailsigner). -y ekprefnick specify an encryption key preference by nickname. usage encrypt example cmsutil -c [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, . . ." -e envfile decode example cmsutil -d [-i infile] [-o outfile] [-d dbdir] [-p password] [-c content] [-n] [-h num] envelope example cmsutil -e [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, ..." certificate-only example cmsutil -o [-i infile] [-o outfile] [-d dbdir] [-p password] -r "cert1,cert2, . . ." sign message example cmsutil -s [-i infile] [-o outfile] [-d...
...rces nss is maintained in conjunction with pki and security-related projects through mozilla dn fedora. the most closely-related project is dogtag pki, with a project wiki at [1]http://pki.fedoraproject.org/wiki/. for information specifically about nss, the nss project wiki is located at [2]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: pki-devel@redhat.com and pki-users@redhat.com irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape and now with red hat. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license versio...
NSS tools : signtool
written signature. once you have signed a file, it is difficult to claim later that you didn't sign it. in some situations, a digital signature may be considered as legally binding as a handwritten signature. therefore, you should take great care to ensure that you can stand behind any file you sign and distribute. for example, if you are a software developer, you should test your code to make sure it is virus-free before signing it. similarly, if you are a network administrator, you should make sure, before signing any code, that it comes from a reliable source and will run correctly with the software installed on the machines to which you are distributing it. before you can use netscape signing tool to sign files, you must have an object-signing certificate...
...e installing the keys and certificate in the communicator databases, you must exit communicator before using this option; otherwise, you risk corrupting the databases. in all cases, the certificate is also output to a file named x509.cacert, which has the mime-type application/x-x509-ca-cert. unlike certificates normally used to sign finished code to be distributed over a network, a test certificate created with -g is not signed by a recognized certificate authority. instead, it is self-signed. in addition, a single test signing certificate functions as both an object-signing certificate and a ca. when you are using it to sign objects, it behaves like an object-signing certificate. whe...
...y database password only once. the -j option is available only in netscape signing tool 1.0 and later versions. the -j option cannot be used at the same time as the -z option. if 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 objec...
...he new database design and how to configure applications to use it. o https://wiki.mozilla.org/nss_shared_db_howto o https://wiki.mozilla.org/nss_shared_db additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape, red hat, and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license vers...
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
ed. when used with looping mode, the different connections are separated with horizontal lines. you can use this option to upload the output into a browser. -s turn on ssl parsing and decoding. the tool does not automatically detect ssl sessions. if you are intercepting an ssl connection, use this option so that the tool can detect and decode ssl structures. if the tool detects a certificate chain, it saves the der-encoded certificates into files in the current directory. the files are named cert.0x, where x is the sequence number of the certificate. if the -s option is used with -h, two separate parts are printed for each record: the plain hex/ascii output, and the p...
...used only with the -s option. this option uses the same output format as the -h option. -l prefix turn on looping; that is, continue to accept connections rather than stopping after the first connection is complete. -p port change the default rendezvous port (1924) to another port. ...
... version = { 3,0 } length = 223 (0xdf) < encrypted > } sslrecord { 0: 15 03 00 00 12 |..... type = 21 (alert) version = { 3,0 } length = 18 (0x12) < encrypted > } ] server socket closed. example 2 the -s option turns on ssl parsing. because the -x option is not used in this example, undecoded values are output as raw data. the output is routed to a text file. $ ssltap -s -p 444 interzone.mcom.com:443 > s.txt output connected to interzone.mcom.com:443 --> [ alloclen = 63 bytes [ssl2] clienthellov2 { version = {0x03, 0x00} cipher-specs-length = 36 (0x24) sid-length = 0 (0x00) challenge-length = 16 (0x10) ...
...rces nss is maintained in conjunction with pki and security-related projects through mozilla dn fedora. the most closely-related project is dogtag pki, with a project wiki at [2]http://pki.fedoraproject.org/wiki/. for information specifically about nss, the nss project wiki is located at [3]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: pki-devel@redhat.com and pki-users@redhat.com irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape and now with red hat and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public licens...
Performance Hints
var statements use var statements when possible. not only is it good programming practice, it can speed up your code by allowing the compiler to generate special code to access the variables. for example, you could rewrite function sum(a) { result = 0; for (i=0; i < a.length; i++) result += a[i]; return result; } as function sum(a) { var result = 0; for (var i=0; i < a.length; i++) result += a[i]; return result; } this is not equivalent code because the second version does not modify global variables result and i. however, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a loop like the one in sum!). arrays use the forms...
...cause the second version does not modify global variables result and i. however, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a loop like the one in sum!). arrays use the forms of the array constructor that specify a size or take a list of initial elements. for example, the code var a = new array(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to new array(n). a constructor call like that indicates to the runtime that a javascript array should be used for the first n entries of the array. similarly, new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the j...
...c"] will cause a 3-element array to be allocated to hold the contents of the javascript array. eval and new function avoid calling eval when possible. calls to eval are slow because the script being executed must be compiled. constructing a new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. for example, the code function myobject(a) { this.s = a; this.tostring = new function("return this.s"); } could be written more efficiently as function myobject(a) { this.s = a; this.tostring = function () { return this.s } } beginning with rhino 1.4 release 2, code passed to eval and new function will be interpreted rather than compiled to class files. with using the with statement prevents th...
...you're probably better off explicitly accessing any properties of the object. ...
Scripting Java
earning about what a library or api can do by writing quick programs that use it. as we will see, scripting makes this process easier. note that the ecma standard doesn't cover communication with java (or with any external object system for that matter). all the functionality covered in this chapter should thus be considered an extension. accessing java packages and classes every piece of java code is part of a class. every java class is part of a package. in javascript, however, scripts exist outside of any package hierarchy. how then, do we access classes in java packages? rhino defines a top-level variable named packages. the properties of the packages variable are all the top-level java packages, such as java and com. for example, we can access the value of the java package: js> packa...
...ted inheritance hierarchies since you can see all the methods that are available for that object. rhino provides another convenience by allowing properties of javabeans to be accessed directly by their property names. a javabean property foo is defined by the methods getfoo and setfoo. additionally, a boolean property of the same name can be defined by an isfoo method. for example, the following code actually calls the file object's getname and isdirectory methods. js> f.name test.txt js> f.directory false calling overloaded methods the process of choosing a method to call based upon the types of the arguments is called overload resolution. in java, overload resolution is performed at compile time, while in rhino it occurs at runtime. this difference is inevitable given javascript's use o...
... obj. now that we have an object implementing runnable, we can create a thread and run it. the function we defined for run will be called on a new thread. js> t = new java.lang.thread(r) thread[thread-2,5,main] js> t.start() js> running the final js prompt and the output from the new thread may appear in either order, depending on thread scheduling. behind the scenes, rhino generates the bytecode for a new java class that implements runnable and forwards all calls to its run method over to an associated javascript object. the object that implements this class is called a java adapter. because the forwarding to javascript occurs at runtime, it is possible to delay defining the methods implementing an interface until they are called. while omitting a required method is bad practice for prog...
...ertoplevel class as the top level scope. the class provides additional importpackage() and importclass() global functions for scripts but their extensive usage has tendency to pollute the global name space with names of java classes and prevents loaded classes from garbage collection. see bugzilla 245882 for details. java exceptions exceptions thrown by java methods can be caught by javascript code using try...catch statement. rhino wraps java exceptions into error objects with the following properties: javaexception: the original exception thrown by the java method rhinoexception: the exception wrapped by the rhino runtime the instanceof operator can be used to query the type of an exception: try { java.lang.class.forname("nonexistingclass"); } catch (e) { if (e.javaexceptio...
Rhino serialization
serialization provides a way to save the state of an object and write it out to a file or send it across a network connection. simple serialization example the rhino shell has two new top-level functions, serialize and deserialize. ...
... a simple case of a function being serialized to a file and then read into a new instance of rhino and called. rhino serialization apis two new classes, scriptableoutputstream and scriptableinputstream, were introduced to handle serialization of rhino classes. these classes extend objectoutputstream and objectinputstream respectively. writing an object to a file can be done in a few lines of java code: fileoutputstream fos = new fileoutputstream(filename); scriptableoutputstream out = new scriptableoutputstream(fos, scope); out.writeobject(obj); out.close(); here filename is the file to write to, obj is the object or function to write, and scope is the top-level scope containing obj. reading the serialized object back into memory is similarly simple: fileinputstream fis = new fileinputstream(...
...be saved as markers upon serialization and resolved in the new scope upon deserialization. use the addexcludedname method of scriptableoutputstream to add new names. by default, scriptableoutputstream excludes all the names defined using context.initstandardobjects. if you are using rhino serialization in an environment where you always define, say, a constructor foo, you should add the following code before calling writeobject: out.addexcludedname("foo"); out.addexcludedname("foo.prototype"); this code will prevent foo and foo.prototype from being serialized and will cause references to foo or foo.prototype to be resolved to the objects in the new scope upon deserialization. exceptions will be thrown if foo or foo.prototype cannot be found the scopes used in either scriptableoutputstream or ...
...rn 3; } serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java org.mozilla.javascript.tools.shell.main -opt -1test.js 3 $ java org.mozilla.javascript.tools.shell.main test.js js: uncaught javascript exception: java.lang.classnotfoundexception:c1 the problem is that java serialization has no built-in way to serialize java classes themselves. ...
SpiderMonkey Build Documentation
non-developer (optimized) build use these steps if you want to install spidermonkey for production use or run performance benchmarks. ...
... non-developer (optimized) build use these steps if you want to install spidermonkey for production use or run performance benchmarks. ...
...ample on debian linux you'll need the following to cross compile from x86_64 to x86. apt install clang libstdc++-8-dev-i386-cross binutils-i686-gnu zlib1g-dev:i386 you'll also need rust, in addition to having normal rust set up you'll need to add another target to your existing rust toolchain (don't add a new toolchain spidermonkey will use only one toolchain and use it for both host and target code: rustup target add i686-unknown-linux-gnu to build a 32-bit version on a 64-bit linux system, you can use the following: pkg_config_libdir=/usr/lib/pkgconfig cc="gcc -m32 -mfpmath=sse -msse -msse2" cxx="g++ -m32 -mfpmath=sse -msse -msse2" ar=ar \ $src/configure --target=i686-pc-linux or for clang. $src/configure --target=i686-pc-linux-gnu to build a 32-bit arm version on a 64-bit linux sys...
... described above. failure to do so may break your js-config.h header or js-config script. some features detected by the configure script do not work for cross-compilation. using the js-config script in addition to the spidermonkey libraries, header files, and shell, the spidermonkey build also produces a shell script named js-config which other build systems can use to find out how to compile code using the spidermonkey apis, and how to link with the spidermonkey libraries. note: in spidermonkey 1.8.5, the js-config script is not generated properly on many platforms. if the instructions below do not work, you can try this workaround. when invoked with the --cflags option, js-config prints the flags that you should pass to the c compiler when compiling files that use the spidermonkey api.
JSPropertyOp
taking place. provides request. in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). obj js::handleobject the object whose properties are being accessed. id js::handleid the name or index of the property being accessed. this is either a string (unicode property identifier) or an integer (element index). strict bool (jsstrictpropertyop only) if strict is true, treating the assignment as strict mode code. vp js::mutablehandlevalue in/out parameter. points to a js::value variable. the meaning of this variable is different for each of the hooks; see below. description jspropertyop and jsstrictpropertyop callbac...
...then fails, and the error is propagated to the caller. otherwise the callback must return true, and the property operation proceeds. getters and setters when a jsapi application creates a property on an object (for example, using js_defineproperty or js_defineproperties) it can specify getter and setter callbacks for the new property. getters. the getter callback is called each time javascript code accesses the property's value using the syntax obj.prop or obj[propname]. it is also called when the property's value is accessed via jsapi functions such as js_getproperty or (less obviously) js_callfunctionname. on entry, *vp contains the property's stored value or undefined if the property doesn't have a stored value. the callback may modify *vp. on success, the callback returns true and the v...
... accessed via jsapi functions such as js_getproperty or (less obviously) js_callfunctionname. on entry, *vp contains the property's stored value or undefined if the property doesn't have a stored value. the callback may modify *vp. on success, the callback returns true and the value left in *vp is returned to the script or jsapi caller. setters. the setter callback is called each time javascript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators. it is also called when the property is set via jsapi functions such as js_setproperty. on entry, *vp contains the value being assigned to the property. the callback may modify *vp. on success, the callback returns true. if the property has a stored value, it is then updated to the value left in *vp afte...
...bject on which the property was defined. jsclass hooks jsclass offers following hooks: jspropertyop jsclass.addproperty is called just after a new property is added to an object. this happens when a program sets a property that isn't already an own property of the target object. it also happens in jsapi functions such as js_defineproperty. on entry, *vp contains the value provided by the code defining or setting the property. the callback may modify *vp. on success, the post-callback value of *vp becomes the initial stored value of the new property. in js_threadsafe builds, this callback is called with obj locked. it is therefore dangerous for the callback to call jsapi functions, particularly if obj may have been visible to more than one thread. jsclass.getproperty is the de...
JS_InitClass
syntax jsobject * js_initclass(jscontext *cx, js::handleobject obj, js::handleobject parent_proto, const jsclass *clasp, jsnative constructor, unsigned nargs, const jspropertyspec *ps, const jsfunctionspec *fs, const jspropertyspec *static_ps, const jsfunctionspec *static_fs); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject pointer to the "globals" object to use for initializing the class. ...
...s request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject pointer to the "globals" object to use for initializing the class. this must not be null. once js_initclass creates the new class's constructor, it stores the constructor as a property in this object. so, for example, if this object is js_getglobalobject(cx), then javascript code will be able to see the new class as a global name. parent_proto js::handleobject pointer to an object to be used as a prototype. js_initclass always creates a new prototype object that serves as the __proto__ for class instances; parent_proto becomes the __proto__ of that prototype object. clasp jsclass * pointer to the class structure to initialize. this structure ...
...in java.) static_fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end. these functions, if any, are added to the new class's constructor. (this is the javascript equivalent of public static methods in c++ or java.) description js_initclass initializes a jsclass and (optionally) makes it visible to javascript code. this is one way to create jsobjects whose properties and methods are implemented in native c/c++. if you need a native function but you don't need to support instances or inheritance, js_initclass might be overkill. js_definefunction is simpler. a jsapi class consists of a jsclass structure, a constructor, a prototype object, and properties and functions. the jsclass is an internal data structur...
..., its flags, and its property access functions. these include native c functions for instance finalization, adding and deleting properties, getting and setting property values, and enumerating, converting, and resolving properties. the jsapi provides reasonable default behavior for all of these; ordinarily you don't want to overload any of them. after a successful call to js_initclass, javascript code can see and manipulate the class's constructor and prototype just as if it were an ordinary javascript function with a prototype property. javascript code can create new instances using the new keyword. classes can have methods and properties that are present on all instances. they can also have methods and properties that are only present on the constructor; these are called "static methods" and...
JS_InitStandardClasses
request on this jscontext. obj js::handle&lt;jsobject*&gt; the global object to initialize. this object must be of a jsclass that has the jsclass_global_flags bits set. description js_initstandardclasses initializes the built-in javascript global properties. ...
... this jscontext. obj js::handle&lt;jsobject*&gt; the global object to initialize. this object must be of a jsclass that has the jsclass_global_flags bits set. description js_initstandardclasses initializes the built-in javascript global properties. ...
... obj js::handle&lt;jsobject*&gt; the global object to initialize. this object must be of a jsclass that has the jsclass_global_flags bits set. description js_initstandardclasses initializes the built-in javascript global properties. ...
... js::handle&lt;jsobject*&gt; the global object to initialize. this object must be of a jsclass that has the jsclass_global_flags bits set. description js_initstandardclasses initializes the built-in javascript global properties. ...
JS_ReportErrorNumber
report an error with an application-defined error code. syntax void js_reporterrornumber(jscontext *cx, jserrorcallback errorcallback, void *userref, const unsigned errornumber, ...); void js_reporterrornumberuc(jscontext *cx, jserrorcallback errorcallback, void *userref, const unsigned errornumber, ...); bool js_reporterrorflagsandnumber(jscontext *cx, unsigned flags, jserrorcallback errorcallback, void *userref, const unsigned errornumber, ...); bool js_reporterrorflagsandnumberuc(jscontext *cx, unsigned flags, jserrorcallback errorcallback, void *userref, const unsigned errornumber, ...); void js_reporterrornumber...
...aller must be in a request on this jscontext. flags unsigned error report flags. errorcallback jserrorcallback callback to fetch the error message. userref void * a pointer to application data. the javascript engine passes this pointer to errorcallback. the meaning of the data is up to the application. errornumber const unsigned an error code. the javascript engine passes this number to errorcallback. the meaning of the error number is up to the application. ... / args ... / const char16_t ** additional arguments for the error message. these arguments must be of type char * for js_reporterrornumber or js_reporterrorflagsandnumber, or char16_t * for js_reporterrornumberuc or js_reporterrorflagsandnumberuc. the n...
...it to the current error reporter callback or create an error object and set it as the pending exception. first errorcallback(userref, errornumber) is called. if errorcallback returns null, (??? what happens?). otherwise, if the jserrorformatstring returned by the jserrorcallback has .exntype == jsexn_none, then the error reporter, if any, is called, and no error object is created. (??? the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, if any javascript code is running in cx (for example, if the caller is a jsnative that was called from a script), then an error object is created and becomes the pending exception. the error reporter is not called yet, because the script still has an opportunity to catch and handle the exception. oth...
...if the jsoption_dont_report_uncaught option is set, (??? what happens?). otherwise, (??? what happens?). ...
SpiderMonkey 1.8
spidermonkey 1.8 is the javascript engine that shipped in firefox 3.0. it is much faster than spidermonkey 1.7 and contains a few new language features and api features, described in detail below. please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup. or, file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. ...
...us versions. specifically, if a property lookup first calls a resolve hook which does not define the property, then finds the property on a prototype, that result can be cached. future lookups for the same property on the same sort of object may bypass the resolve hook. js_newdouble is now deprecated. use js_newdoublevalue. the security apis js_setcheckobjectaccesscallback, js_setprincipalstranscoder, and js_setobjectprincipalsfinder are still present but are deprecated in this release. in spidermonkey 1.8.1 they will be removed and replaced with a new set of apis (js_getsecuritycallbacks and friends, bug 451729). js.mak, an old windows-specific nmake file, has been deleted. it hasn't worked for a long time. it is fairly easy to create a microsoft visual studio project file for spidermonkey...
...ty and friends are new functions for examining an object without triggering resolve hooks. it was possible to configure spidermonkey 1.7 to treat c/c++ char strings as utf-8 by compiling with a non-default compiler option. in spidermonkey 1.8, it is no longer necessary to make a special build to get this behavior. applications can turn on utf-8 at run time by calling js_setcstringsareutf8. js_encodestring is a new variation on js_getstringbytes that returns a newly allocated, writable buffer which the application must js_free. js_reportallocationoverflow can be used (instead of js_reportoutofmemory) to indicate that the script is trying to do something that would require more memory than the implementation is designed to handle. the main difference is that js_reportallocationoverflow throws...
...ing regular expression searches to fail with an error, and jsoption_anonfunfix, which bans anonymous functions from appearing anyplace where a statement could appear, such as in the argument to eval(). functions that were js_threadsafe-only in spidermonkey 1.7 (js_beginrequest, for example) are now present, but do nothing, in non-js_threadsafe builds. this is to help applications share and reuse code regardless of whether they use threads. there are two new jsextendedclass hooks, jsextendedclass.iteratorobject and jsextendedclass.wrappedobject. both are documented but obscure. many new memory management features have been added as well. the new function js_setscriptstackquota limits the size of the javascript stack. two new functions, js_setgczeal and js_dumpheap, aim to help developer...
SpiderMonkey 38
ore, component: javascript engine. — sep 17, 2015 the download url is outdated and spidermonkey not release alone! get it here mozilla-esr38 you will find it in "firefox extended support release 38" package on hg release platform support spidermonkey 38 is supported on all the platforms where firefox 38 runs. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. if you are compiling with microsoft's visual studio, note that the minimum supported version is msvc10/2010. spidermonkey 38 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not supported. on all other platforms...
...it's the same language, just not as fast. migrating to spidermonkey 38 .... ...
...nt the same interface as js::value, for simplicity and to ease migration pain. changes to introduce handles to the jsapi are not individually documented, because of the breadth of the changes involved. the following features in earlier versions of spidermonkey have been dropped. xxx list removed features here spidermonkey 38 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most functions that have changed still have the same names and implement essentially unchanged functionality. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a l...
...bug 1094176) js_lookupucproperty (bug 1094176) js_newpropertyiterator (bug 1081660) js_nextproperty (bug 1081660) js_resolvestub (bug 1103152) js_setfinalizecallback (bug 996785) js_setfunctioncallback (bug 1103269) jschar (bug 1063962) api changes jschar, a typedef for the standard c++ type char16_t, has been removed. jsapi functions that used jschar now use char16_t directly. embedder code should use char16_t, too. (see bug 1063962.) js_preventextensions now indicates its success or failure in two ways: via return value (as with most jsapi methods), and via outparam (indicating whether the attempt took effect or not, independent of jsapi failure). this change better aligns with ecmascript's [[preventextensions]] hook, which generally returns true or false to indicate whether subs...
SpiderMonkey 45
it continues to improve performance over previous spidermonkey releases. ...
...ing in the mozilla.dev.tech.js-engine newsgroup. or file bugs at bugzilla.mozilla.org under product: core, component: javascript engine. you may wish to make the bugs block bug 837921 (aliased as "sm.embedding"). — apr 14, 2016 platform support spidermonkey 45 is supported on all platforms able to run firefox 45. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. if you are compiling with microsoft's visual studio, note the minimum supported version is msvc 2013. spidermonkey 45 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on several other platforms (sparc, mips), the jit is provided but not supported. on remaining platforms the...
...microsoft's visual studio, note the minimum supported version is msvc 2013. spidermonkey 45 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on several other platforms (sparc, mips), the jit is provided but not supported. on remaining platforms the jit is disabled; javascript code runs in an interpreter, as it has in previous versions. it's the same language, just not as fast. migrating to spidermonkey 45 spidermonkey 45 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types; functions, and callback signatures, have changed though most functions that have retain their previous name, providing relatively unchanged functionality...
...here is a list of the most significant changes: js::nullptr is obsolete. you should now use nullptr instead. (supporting decltype(nullptr)). new javascript language features javascript 45 includes significant updates to its language features, yo. new c++ apis jsapi is a c++ exclusive api. ...
SpiderMonkey: The Mozilla JavaScript runtime
spidermonkey is mozilla's javascript engine written in c and c++. it is used in various mozilla products, including firefox, and is available under the mpl2. standalone source code releases can be found on the releases page. guides building spidermonkey build documentation how to get spidermonkey source code, build it, and run the test suite. using spidermonkey introduction to the javascript shell documentation of the command-line javascript shell, js. ...
...duction to the javascript shell documentation of the command-line javascript shell, js. jsapi user guide this guide provides an overview of spidermonkey and describes how you can embed engine calls in your applications to make them javascript-aware. jsapi cookbook shows the jsapi translation of some commonly used javascript expressions and statements. gc rooting guide guide on how to write code compatible with the generational gc in spidermonkey. how to embed the javascript engine an older tutorial about embedding spidermonkey. hacking on spidermonkey new to spidermonkey a guide to hacking on spidermonkey. setting up cdt to work on spidermonkey how to configure eclipse to work on the spidermonkey code. running automated javascript tests how to run the javascript test suit...
... running automated javascript tests how to run the javascript test suites. creating javascript tests how to add tests to the javascript test suites. reference jsapi reference spidermonkey api reference. js debugger api reference api reference for the debugger object introduced in spidermonkey 1.8.6, which corresponds to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). ...
...the javascript test suites. creating javascript tests how to add tests to the javascript test suites. reference jsapi reference spidermonkey api reference. js debugger api reference api reference for the debugger object introduced in spidermonkey 1.8.6, which corresponds to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). bytecode descriptions listing of spidermonkey's bytecodes. parser api reflection of the spidermonkey parser, made available as a javascript api. tips, tricks and philosophy future directions future directions for functionality, design, and coding practices. spidermonkey internals a design overview and a file-by-file walkthrough of the implementation. bytecode reference spidermonkey bytecode reference. spidermonkey internals: gc separate i...
Creating a Python XPCOM component
his is the same as the nsisimple interface used here. theoretically, because several components can share an interface, the same file could be used. pay special attention to types here - python and javascript are both loosely-typed, so it's fairly easy to pass information from one to the other. note: there are exceptions; see this discussion for information on the use of string and wstring for unicode transfer. see here for info on describing interfaces, and on which types can be used. registering the interface in the "components" directory, execute : ../xpidl -m typelib -w -v -i /usr/share/idl/mozilla/ nsipysimple.idl on windows you must point to the idl directory as part of your mozilla build. for example: xpidl.exe -m typelib -w -v -i c:\source\mozilla\obj-i686-pc-mingw32\dist\idl foo.idl ...
...must point to the idl directory as part of your mozilla build. for example: xpidl.exe -m typelib -w -v -i c:\source\mozilla\obj-i686-pc-mingw32\dist\idl foo.idl xpidl will then create nsipysimple.xpt, which should be placed correctly (e.g., in the 'components' directory). implementing the component unlike c++, pyxpcom does much of the work for you. ...
... # if this object needs to be registered, the following 2 are also needed. # _reg_clsid_ = "{a new clsid generated for this object}" # _reg_contractid_ = "the.object.name" def get_value( self ): # result: string pass def set_value( self, param0 ): # result: void - none # in: param0: string pass as you can see, the output is valid python code, with basic signatures and useful comments for each of the methods. testing it to see this work, you will have to start firefox from the command line, since that'll be where the stuff will be printed out. external links creating xpcom components, on which this short tutorial is based. a three-part tutorial on ibm developerworks: getting to know pyxpcom - info on building pyxpcom (...
... xpcom components, on which this short tutorial is based. a three-part tutorial on ibm developerworks: getting to know pyxpcom - info on building pyxpcom (and maybe mozilla) to get it to work. getting started with pyxpcom, part 2 - accessing xpcom from python. getting started with pyxpcom, part 3 - creating your own components. the problem with this one is that the sample code they give is slightly broken (it ends with a "retu" which shouldn't be there. i haven't tried it, but it looks like nothing is missing, so getting rid of the "retu" should make it work fine.). ...
XPCOM glue
Mozilla › Tech › XPCOM › Glue
ows developers to link only against the frozen xpcom method symbols and maintain compatibility with multiple versions of xpcom. compiling or linking against xpcom headers there are three ways to compile/link against xpcom headers/libraries: frozen linkage: dependent glue (dependent on xpcom.dll) xpcom modules, i.e. extension or xulrunner application components, should use the dependent glue. code which wishes to use only frozen symbols but can tolerate a load-time dependency on xpcom.dll should link against xpcomglue_s.lib and xpcom.lib. it should not link against xpcom_core.lib. this is the case for xpcom components, because they are loaded into mozilla which already has full xpcom loaded and initialized. frozen linkage: standalone glue (no dll dependencies) note: support for locating...
...ou have a custom application where you want to embed gecko to show webpages in your own window. i.e. this linkage strategy is used when an embedder needs to bootstrap xpcom by finding a compatible gre on disk and loading it. in order to use xpcom, the embedding application first needs to find where the xpcom runtime is located. this is typically done using gre_getgrepathwithproperties. then, the code must call xpcomgluestartup, which will dynamically link against the xpcom runtime. only then can the embedding application initialize and use xpcom. embedding code which wishes to use only frozen symbols and cannot tolerate a load-time dependency on xpcom.dll should #define xpcom_glue 1 while compiling, and link against xpcomglue.lib. it should not link against xpcomglue_s.lib or xpcom.lib. emb...
...ell. however, when using threadsafe together with the glue libraries from gecko 1.8 or later, a special step needs to be taken to use ns_impl_threadsafe_isupportsn. this is because it forces a dependency on the nspr library, which can otherwise be avoided. as described in bug 299664, the preprocessor symbol xpcom_glue_use_nspr needs to be defined. using mozilla internal linkage mozilla internal code defines mozilla_internal_api while compiling and links against xpcom.lib and xpcom_core.lib. in almost all cases embedders should *not* use internal linkage. components using internal linkage will have shared-library dependencies against non-frozen symbols in the xpcom libraries, and will not work with any other versions of xpcom other than the one it was compiled against. internal linkage will ...
...h any other versions of xpcom other than the one it was compiled against. internal linkage will be unavailable to extension authors in xulrunner 1.9 (firefox 3) because the nonfrozen symbols will not be exported from libxul. extension and application authors currently using internal linkage should read the guide on migrating from internal linkage to frozen linkage. sample compiler/linker flags code compiled using xpcom headers should always #include "xpcom-config.h" from the sdk, to ensure that xpcom #defines are correct. linking strategy: dependent glue standalone glue compiler flags: cross-platform #include "xpcom-config.h" #include "xpcom-config.h" #define xpcom_glue windows /fi "xpcom-config.h" linux -include "xpcom-con...
Components.utils
specified compartment. createobjectin() creates a new object, created in the scope of the specified object's compartment. dispatch() dispatches a runnable to the current/main thread. if the parameter is passed, the runnable will be dispatch in the compartment of the parameter, which affects which error reporter gets called. evalinsandbox() runs javascript code in a sandbox, usually used to run code with restricted privileges. evalinwindow() removed in gecko 34. evaluate javascript code in a less-privileged javascript context. exportfunction() export a javascript function from a more-privileged to a less-privileged scope, allowing it to be called in the less-privileged scope. forcegc() force...
...ascript function from a more-privileged to a less-privileged scope, allowing it to be called in the less-privileged scope. forcegc() forces a garbage collection cycle. forcecc() forces a cycle collection cycle. forceshrinkinggc() forces a shrinking garbage collection cycle. getcomponentsforscope() this seemingly-paradoxical api allows privileged code to explicitly give unprivileged code a reference to its own components object (whereas it's normally hidden away on a scope chain visible only to xbl methods). see also specialpowers.getcomponents. getglobalforobject() returns the global object with which a given object is associated (through its prototype chain at birth, for example). getjstestingfunctions() ge...
...termines whether this object is backed by a deadobjectproxy. lookupmethod() looks up a native (i.e. declared in the interface) method or property of an xpcom object. serves the same purpose as xpcnativewrapper. makeobjectpropsnormal() ensures that all functions come from the specified object's scope, and aren't cross-compartment wrappers. may only be called from javascript code. nondeterministicgetweakmapkeys() return the keys in a weak map. this operation is non-deterministic because it is affected by the scheduling of the garbage collector and the cycle collector. this should only be used to write tests of the interaction of the gc and cc with weak maps. obsolete since gecko 45 the function was moved to threadsafechromeutils nukes...
...y. this is for gecko internal use only, and may disappear at any moment. reporterror() reports a javascript error object to the error console. setwantxrays() to be called from js only. this is for gecko internal use only, and may disappear at any moment. scheduleprecisegc() schedules a garbage collection cycle for some time in the future at which no javascript code is running. this lets you specify a callback so you can be notified once the garbage collection cycle has been performed. setgczeal() sets the level of garbage collection level for full garbage collection. see js_setgczeal for details; this method calls through to that with the specified value as the zeal value. unwaivexrays() undoes waivexrays(): reapplies the xray filt...
NS_NewNativeLocalFile
nativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path. #include "nsxpcom.h" #include "nsilocalfile.h" nsresult ns_newnativelocalfile( const nsacstring& apath, prbool afollowlinks, nsilocalfile** aresult ); parameters apath [in] a string object that specifies an absolute filesystem path. this string should be encoded using ascii or the multibyte character coding corresponding to the native filesystem. this path does not need to reference an existing file. it is an error to pass a relative filesystem path. afollowlinks [in] this attribute will determine if the nsilocalfile instance will automatically resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes short...
...e symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. return values the ns_newnativelocalfile function returns ns_ok if successful. otherwise, it returns an error code. ns_error_file_unrecognized_path indicates that the specified path is invalid. this error is returned if a relative file path is passed to ns_newnativelocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. if you use this function on windows 2000 or later, you would not be able to handle file names containing characters outside the def...
...s_error_file_unrecognized_path indicates that the specified path is invalid. this error is returned if a relative file path is passed to ns_newnativelocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. ...
...systems, the prefix "~/" is supported as a shorthand for the user's home directory. if you use this function on windows 2000 or later, you would not be able to handle file names containing characters outside the default code page even though the os has no problem dealing with them. do not use this function (on windows) unless it is guaranteed that the full path involved is always ascii. example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newnativelocalfile(nsembedcstring("c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; here, nsembedcstring is used to convert the ascii string literal to an object that can be passed as a const nsacstring& parameter. history this function...
mozIStorageAggregateFunction
p() this is called for each row of results returned by the query. the implementation should store or perform some work to prepare to return a value. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code. likewise, if you execute sql on a different thread, this callback will be executed on that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! void onstep( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function. onfinal() this is called af...
...have been obtained and notified via mozistorageaggregatefunction. the implementation should finish its calculations on the data, and return a result. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code. ...
... javascript // first, create our object that will represent our function. ...
... javascript // first, create our object that will represent our function. ...
nsIAbCard
the nsiabcard interface is used to represent and manipulate cards in the addressbook. following a huge refactoring of the address book code, most of the documentation below is out of date. properties aren't stored anymore on the card, except for a handful of them. complex properties are expected to be accessed through a call to getproperty. see //github.com/realityripple/uxp/blob/master//mailnews/addrbook/public/nsiabcard.idl for more details. ...
...call to getproperty. see //github.com/realityripple/uxp/blob/master//mailnews/addrbook/public/nsiabcard.idl for more details. ...
... cellularnumber astring workphonetype astring homephonetype astring faxnumbertype astring pagernumbertype astring cellularnumbertype astring homeaddress astring homeaddress2 astring homecity astring homestate astring homezipcode astring homecountry astring workaddress astring workaddress2 astring workcity astring workstate astring workzipcode astring workcountry astring jobtitle astring department astring company astring aimscreenname ...
...e you want to set. value the value to set the attribute to. copy() this function will copy all values from one card to another. void copy(in nsiabcard srccard) parameters srccard the source card to copy values from. equals() boolean equals(in nsiabcard card) parameters card the card you are comparing with. return value true if the cards are the same. converttobase64encodedxml() string converttobase64encodedxml() return value converttoxmlprintdata() astring converttoxmlprintdata() return value converttoescapedvcard() string converttoescapedvcard() return value generatename() generate a name from the card for display purposes. using the firstname, lastname and the displayname. we allow the caller to cache the pref value, so we don't have to go to pr...
nsIDOMWindow
ument in the window contains an html frameset document, or if the document contains iframe elements. 66 introduced gecko 1.0 deprecated gecko 44 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) starting with firefox 44, this file is empty as its features were either no longer used or are only available from c++ code; see dom/base/nspidomwindow.h for those. while this interface is not officially defined by any standard bodies, it originates from the de-facto dom level 0 standard. starting in firefox 3, dom windows are actually based on nsidomwindow2, which is a subclass of nsidomwindow that adds some new features to this interface. in gecko 7.0 nsidomwindow2 has been merged into this interface. in gecko ...
...bute type description applicationcache nsidomofflineresourcelist get the application cache object for this window. read only. note: prior to gecko 7.0 this attribute was part of nsidomwindow2. document nsidomdocument the document contained in the window. read only. frames nsidomwindowcollection the child windows for this window. read only. native code only! globalstorage nsidomstoragelist global storage, accessible by domain. read only. note: prior to gecko 8.0 this attribute was part of nsidomstoragewindow. localstorage nsidomstorage local storage for the current browsing context. data stored in local storage may only be accessed from the same origin that inserted the data into storage in the first place. read on...
...s attribute was part of nsidomstoragewindow. textzoom float get or set the document scale factor as a multiplier of the default size. when setting this attribute, an ns_error_not_implemented error may be returned by implementations not supporting zoom. this attribute should always return 1.0 for implementations not supporting text zoom. 1.0 represents normal (unzoomed) size. native code only! top nsidomwindow the root window for the hierarchy of windows that contain this nsidomwindow. this is the window itself if there is no parent, or if the parent is of a different type. the window hierarchy does not cross chrome-content boundaries. this attribute is "replaceable" in javascript. read only. windowroot nsidomeventtarget the window root for this wind...
... if there is no parent, or if the parent is of a different type. the window hierarchy does not cross chrome-content boundaries. this attribute is "replaceable" in javascript. read only. windowroot nsidomeventtarget the window root for this window. this is useful for connecting event listeners to this window as well as every other window nested in that window root. read only. native code only! note: prior to gecko 7.0 this attribute was part of nsidomwindow2. methods getcomputedstyle() see dom-window-getcomputedstyle for details. nsidomcssstyledeclaration getcomputedstyle( in nsidomelement elt, in domstring pseudoelt optional ); parameters elt pseudoelt optional return value getselection() returns the nsiselection object indicating what if any cont...
nsIErrorService
string bundle keys can also be mapped. ...
...egistererrorstringbundle(in short errormodule); void unregistererrorstringbundlekey(in nsresult error); methods geterrorstringbundle() retrieves a string bundle url for an error module. string geterrorstringbundle( in short errormodule ); parameters errormodule the module for which the string bundle is registered. error modules are obtained from nsresult code with ns_error_get_module. return value the url of the string bundle registered for that module. geterrorstringbundlekey() retrieves a key in a string bundle for an nsresult error code. if no key is registered for the specified nsresult, then the caller should use the nsresult's code (obtained with ns_error_get_code) instead. string geterrorstringbundlekey( in nsresult error ); parameters ...
... in string stringbundleurl ); parameters errormodule the module for which the string bundle is to be registered. should be one of the modules listed in xpcom/base/nserror.h, such as ns_error_module_storage. stringbundleurl the url of the string bundle to register for the module. registererrorstringbundlekey() registers a key in a string bundle for an nsresult error code. void registererrorstringbundlekey( in nsresult error, in string stringbundlekey ); parameters error the nsresult for which the string bundle key is to be registered. stringbundlekey the key that should be used to retrieve the error string from string bundle for the given nsresult. unregistererrorstringbundle() unregisters a string bundle url for an error module...
...nregisters a string bundle url for an error module. void unregistererrorstringbundle( in short errormodule ); parameters errormodule the module for which the string bundle is to be unregistered. should be one of the modules listed in xpcom/base/nserror.h, such as ns_error_module_storage. unregistererrorstringbundlekey() unregisters a key in a string bundle for an nsresult error code. void unregistererrorstringbundlekey( in nsresult error ); parameters error the nsresult for which the string bundle key is to be unregistered. ...
nsIIDNService
converttod...
...string converttodisplayidn(in autf8string input, out boolean isascii); acstring convertutf8toace(in autf8string input); boolean isace(in acstring input); autf8string normalize(in autf8string input); methods convertacetoutf8() converts an ace (ascii compatible encoding) hostname into unicode format, returning a utf-8 format string. this combines two operations: running the rfc 3490 "tounicode" operation on the original string, then converting the resulting unicode string into utf-8 format. autf8string convertacetoutf8( in acstring input ); parameters input the ace encoded hostname to convert into utf-8 format. return value the utf-8 encoded equivalent of the hostname. converttodisplayidn() normalizes a hostname into utf-8 format if the hostname is in the idn whitelist. if the hos...
...e hostname isn't in the whitelist, it's converted into ace format. the resulting string is useful for display purposes, and ensures that the encoding is consistent with nsiuri.gethost(). autf8string converttodisplayidn( in autf8string input, out boolean isascii ); parameters input the string to convert to display format. isascii on return, this is set to true if the result is ascii or ace encoded; otherwise it's false. return value the display formatted hostname. convertutf8toace() converts the specified hostname from utf-8 to ace format, using the idna "toascii" algorithm. acstring convertutf8toace( in autf8string input ); parameters input the hostname to convert to ace format. return value the ace encoded version of the hostname. isace() determines whether or not the specified ho...
...s false. return value the display formatted hostname. convertutf8toace() converts the specified hostname from utf-8 to ace format, using the idna "toascii" algorithm. acstring convertutf8toace( in autf8string input ); parameters input the hostname to convert to ace format. return value the ace encoded version of the hostname. isace() determines whether or not the specified hostname is ace encoded. boolean isace( in acstring input ); parameters input the string to check. return value returns true if the specified string is ace encoded; otherwise, returns false. normalize() performs the unicode normalization needed for hostnames in idn. this is useful if you need to normalize a hostname separately from converting it to display format. autf8string normalize( in autf8string input ); ...
nsIMemoryReporterManager
method overview nsisimpleenumerator enumeratemultireporters(); nsisimpleenumerator enumeratereporters(); void init(); void registermultireporter(in nsimemorymultireporter reporter); void registerreporter(in nsimemoryrepor...
...s last changed in gecko 1.9 (firefox 3) implemented by @mozilla.org/memory-reporter-manager;1 as a service: var reportermanager = components.classes["@mozilla.org/memory-reporter-manager;1"] .getservice(components.interfaces.nsimemoryreportermanager); each memory reporter object, which implements nsimemoryreporter interface, provides information for a given code area. each code area is identified by a unique path string, which is displayed in about:memory. method overview nsisimpleenumerator enumeratemultireporters(); nsisimpleenumerator enumeratereporters(); void init(); void registermultireporter(in nsimemorymultireporter reporter); void registerreporter(in nsimemoryreporter reporter); ...
...t() initializes the memory reporter manager. void init(); parameters none. registermultireporter() requests that memory multi-reporter notifications be sent to the specified objects. void registermultireporter( in nsimemorymultireporter reporter ); parameters reporter an object implementing the nsimemorymultireporter interface which provides memory usage information for a given code area. registerreporter() requests that memory reporter notifications be sent to the specified objects. void registerreporter( in nsimemoryreporter reporter ); parameters reporter an object implementing the nsimemoryreporter interface which provides memory usage information for a given code area. unregistermultireporter() stops sending memory multi-reporter notifications to the...
...porter interface which provides memory usage information for a given code area. unregistermultireporter() stops sending memory multi-reporter notifications to the specified object. void unregistermultireporter( in nsimemorymultireporter reporter ); parameters reporter an object implementing the nsimemorymultireporter interface which provides memory usage information for a given code area. unregisterreporter() stops sending memory reporter notifications to the specified object. void unregisterreporter( in nsimemoryreporter reporter ); parameters reporter an object implementing the nsimemoryreporter interface which provides memory usage information for a given code area. see also nsimemorymultireporter nsimemoryreporter ...
nsIPlacesImportExportService
/nsiplacesimportexportservice.idlscriptable provides methods for exporting places data. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) in the past, this interface also offered methods for importing places data, but those methods are now part of the bookmarkhtmlutils.jsm javascript code module. the interface name has been kept for compatibility reasons for code using the export service. implemented by: @mozilla.org/import-export-service;1 as a service: var placesimportexportservice = components.classes["@mozilla.org/import-export-service;1"] .getservice(components.interfaces.nsiplacesimportexportservice); method overview void backupb...
...rrent bookmarks hierarchy to a bookmarks.html file. void exporthtmltofile( in nsilocalfile afile ); parameters afile an nsilocalfile indicating where to save the new bookmarks.html file. importhtmlfromfile() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead. loads the given bookmarks.html file and replaces it with the current bookmarks hierarchy (if aisinitialimport is true) or appends it (if aisinitialimport is false). three nsiobserverservice notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are suc...
...romfile( in nsilocalfile afile, in boolean aisinitialimport ); parameters afile the html file to import into places. aisinitialimport whether this is an initial import or not. importhtmlfromfiletofolder() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead.loads the given bookmarks.html file and puts it in the given folder. three nsiobserverservice notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are successfully imported. "bookmarks-restore-failed" is fired right after a failure occurs when importin...
...ks. aisinitialimport whether or not this is an initial import. importhtmlfromuri() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead. same thing as importhtmlfromfile(), but takes a uri instead. void importhtmlfromuri( in nsiuri auri, in boolean aisinitialimport ); parameters auri the uri from which to import bookmarks. aisinitialimport whether or not this is an initial import. see also bookmarkhtmlutils.jsm ...
nsIScriptableIO
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. nsiscriptableio provides a convenient api for creating files and streams, as well as for reading and writing data to them. for your convenience, this api is published through a global io object. for more details about how to use this object, see the file and stream guide. n...
...d writing data to them. for your convenience, this api is published through a global io object. for more details about how to use this object, see the file and stream guide. network/base/public/nsiscriptableio.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports a scriptable io object can be used in an extension or chrome code by referring to the global io object. for example: io.getfile("profile", "cookies.txt"); from an xpcom component, however, you will need to get a reference as with other components: var scriptableio = components.classes["@mozilla.org/io/scriptable-io;1"] .getservice(); scriptableio.getfile("profile", "cookies.txt"); method overview nsifile getfile(in ...
... transport object such as a socket. nsiinputstream: a stream returned by a previous call to this method, or any other object that implements nsiinputstream. string: a string from which to read data. amode a space-delineated string of mode terms controlling the manner in which the stream is accessed. if none of these modes are desired, specify an empty string. text: read unicode-converted text. the default character set is utf-8; to read text in another character set, set the acharset argument to the desired character set. buffered: a stream that uses a buffer to hold a block of the next piece of the data to be read. this mode is generally used as a wrapper for other streams. by default, the buffer size is 1024 bytes; however, the size may be changed by specifying the ...
... the nsifile interface. nsitransport: a transport object such as a socket. nsioutputstream: a stream returned by a previous call to this method, or any other object that implements nsioutputstream. amode a space-delineated string of mode terms controlling the manner in which the stream is accessed. if none of these modes are desired, specify an empty string. text: write unicode-converted text. the default character set is utf-8; to write text in another character set, set the acharset argument to the desired character set. buffered: a stream that buffers the data being written. this mode is generally used as a wrapper for other streams. by default, the buffer size is 1024 bytes; however, the size may be changed by specifying the abuffersize parameter. if the text mode...
nsISelection
nsidomrange getrangeat(in long index); voi...
...id collapsenative(in nsidomnode parentnode, in long offset); native code only! void collapsetoend(); void collapsetostart(); boolean containsnode(in nsidomnode node, in boolean partlycontained); void deletefromdocument(); void extend(in nsidomnode parentnode, in long offset); void extendnative(in nsidomnode parentnode, in long offset); native code only! nsidomrange getrangeat(in long index); void modify(in domstring alter, in domstring direction, in domstring granularity); void removeallranges(); void removerange(in nsidomrange range); void selectallchildren(in nsidomnode parentnode); void selectionlanguagechange(in boolean langrtl); domstring tostring(); attributes ...
...lapsed(), and the content is focused and editable, the caret will blink there. void collapse( in nsidomnode parentnode, in long offset ); parameters parentnode the given nsidomnode where the selection will be set. offset where in the given dom node to place the selection (the offset into the given node). collapsed() [noscript,notxpcom,nostdcall] boolean collapsed(); native code only!collapsenative void collapsenative( in nsinode parentnode, in long offset ); parameters parentnode offset collapsetoend() collapses the whole selection to a single point at the end of the current selection (regardless of direction). if content is focused and editable, the caret will blink there. void collapsetoend(); parameters none collapsetostart() collapses the whole sele...
...mnode and offset, preserving the selection begin position. the new selection end result will always be from the anchornode to the new focusnode, regardless of direction. void extend( in nsidomnode parentnode, in long offset ); parameters parentnode the node where the selection will be extended to. offset where in the node to place the offset in the new selection end. native code only!extendnative void extendnative( in nsinode parentnode, in long offset ); parameters parentnode offset getrangeat() returns the nsidomrange at the specified index. nsidomrange getrangeat( in long index ); parameters index return value the nsidomrange requested modify() modifies the selection. note that the parameters are case-insensitive. void modify( in domstring a...
nsISocketProvider
constants constant value description proxy_resolves_host 1 << 0 this flag is set if the proxy is to perform hostname resolution instead o...
...ong afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, in prfiledescstar afiledesc, out nsisupports asecurityinfo); native code only! void newsocket(in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, out prfiledescstar afiledesc, out nsisupports asecurityinfo); native code only! constants constant value description proxy_resolves_host 1 << 0 this flag is set if the proxy is to perform hostname resolution instead of the client. when set, the hostname parameter passed in this interface will be used instead of the address structure passed for a later request. anonymous_connect 1 << 1 when setting this flag, the socke...
... of the client. when set, the hostname parameter passed in this interface will be used instead of the address structure passed for a later request. anonymous_connect 1 << 1 when setting this flag, the socket will not apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. methods native code only!addtosocket this function is called to allow the socket provider to layer a prfiledesc (a file descriptor) on top of another prfiledesc. for example, ssl via a socks proxy. parameters are the same as newsocket() with the exception of afiledesc, which is an input parameter instead. void addtosocket( in long afamily, in string ahost, in long aport, in string aproxyhost, in long aprox...
...ction. aproxyhost if non-null, the proxy hostname for this connection. aproxyport the proxy port for this connection. aflags control flags that govern this connection (see constants). afiledesc the existing prfiledesc. asecurityinfo any security info that should be associated with afiledesc. this object typically implements nsitransportsecurityinfo. native code only!newsocket creates a new socket. void newsocket( in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, out prfiledescstar afiledesc, out nsisupports asecurityinfo ); parameters afamily the address family for this socket (pr_af_inet or pr_af_inet6). ahost the hostname for this connection. aport ...
nsISocketTransportService
x 3) implemented by: @mozilla.org/network/socket-transport-service;1. ...
...transportservice); method overview void attachsocket(in prfiledescptr afd, in nsasockethandlerptr ahandler); native code only! nsisockettransport createtransport(in array<acstring> asockettypes, in autf8string ahost, in long aport, in nsiproxyinfo aproxyinfo); void init(); obsolete since gecko 1.8 void notifywhencanattachsocket(in nsirunnable aevent); native code only! void shutdown(); obsolete since gecko 1.8 attributes attribute type description autodialenabled boolean controls whether or not the socket transport service should poke the autodialer on connection failure. obsolete since gecko 1.8 methods native code only! attachsocket adds a new socket to the list of controlled sockets. this will ...
... shutdown(); obsolete since gecko 1.8 attributes attribute type description autodialenabled boolean controls whether or not the socket transport service should poke the autodialer on connection failure. obsolete since gecko 1.8 methods native code only! attachsocket adds a new socket to the list of controlled sockets. this will fail with the error code ns_error_not_available if the maximum number of sockets is already reached. in this case, the notifywhencanattachsocket() method should be used. note: this function may only be called from an event dispatch on the socket thread. void attachsocket( in prfiledescptr afd, in nsasockethandlerptr ahandler ); parameters afd open file descriptor of the socket to control. ahandler socket ha...
...uld be used. for more details on communicating information about proxies like socks (which are transparent to upper protocols), see nsiproxiedprotocolhandler , nsiprotocolproxyservice or proxies in necko. return value an nsisockettransport containing the sockettransport. init() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void init(); parameters none. native code only! notifywhencanattachsocket if the number of sockets reaches the limit, then consumers can be notified when the number of sockets becomes less than the limit. the notification is asynchronous, delivered via the given nsirunnable instance on the socket transport thread. note: this function may only be called from an event dispatch on the socket thread. void notifywhencanattachsocket( in...
nsIWebProgressListener
state_secure_med, or state_secure_low. security strength flags these flags describe the security strength and accompany state_is_secure in a call to the onsecuritychange() method. these flags are mutually exclusive. these flags are not meant to provide a precise description of data transfer security. these are instead intended as a rough indicator that may be used to, for example, color code a security indicator or otherwise provide basic data transfer security feedback to the user. constant value description state_secure_high 0x00040000 this flag indicates a high degree of security. state_secure_med 0x00010000 this flag indicates a medium degree of security. state_secure_low 0x00020000 this flag indicates a low degree of s...
...parameters awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has changed state. this parameter may be null. astateflags flags indicating the new state. this value is a combination of one of the state transition flags and one or more of the state type flags defined above. any undefined bits are reserved for future use. astatus error status code associated with the state change. this parameter should be ignored unless astateflags includes the state_stop bit. the status code indicates success or failure of the request associated with the state change. note: astatus may be a success code even for server generated errors, such as the http 404 file not found error. in such cases, the request itself should be queried for extended error inform...
...message is intended to be displayed to the user (for example, in the status bar of the browser). void onstatuschange( in nsiwebprogress awebprogress, in nsirequest arequest, in nsresult astatus, in wstring amessage ); parameters awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has new status. astatus this value is not an error code. instead, it is a numeric value that indicates the current status of the request. this interface does not define the set of possible status codes. note: some status values are defined by nsitransport and nsisockettransport. amessage localized text corresponding to astatus. example the nsiwebprogresslistener for each tab: gbrowser.mtabprogresslistener can be used in the parent to listen f...
...see the example below on how to use an nsiwebprogresslistener in a frame script to get access to the dom window. this example here shows you how to detect what flags are popping up where. it puts the messages into the browser console. ...
nsIWebSocketChannel
??????????????????????. to create an instance, use: var websocketchannel = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsiwebsocketchannel); method overview void asyncopen(in nsiuri auri, in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext); void close(in unsigned short acode, in autf8string areason); void sendbinarymsg(in acstring amsg); void sendmsg(in autf8string amsg); attributes attribute type description extensions acstring sec-websocket-extensions response header value. read only. loadgroup nsiloadgroup the load group of the websockets code. notificationcallbacks nsiinterfacereques...
...ile: uri) so that the original pre-redirect uri can still be obtained. this is never null. read only. protocol acstring sec-websocket-protocol value. securityinfo nsisupports transport-level security information (if any). read only. uri nsiuri the uri corresponding to the protocol connection after any redirections are completed. read only. status codes the following values are permitted status codes. status code name description 0-999 reserved and not used. 1000 close_normal normal closure; the connection successfully completed whatever purpose for which it was created. 1001 close_going_away the endpoint is going away, either because of a server failure or because the browser is nav...
...r. 1003 close_unsupported the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data). 1004 close_too_large the endpoint is terminating the connection because a data frame was received that is too large. 1005 close_no_status reserved. indicates that no status code was provided even though one was expected. 1006 close_abnormal reserved. used to indicate that a connection was closed abnormally (that is, with no close frame being sent) when a status code is expected. 1007-1999 reserved for future use by the websocket standard. 2000-2999 reserved for use by websocket extensions. 3000-3999 availa...
... in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext ); parameters auri the uri of the websocket protocol; this may be redirected. aorigin the uri of the originating resource. alistener the nsiwebsocketlistener implementation. acontext an opaque parameter forwarded to alistener's methods. close() void close( in unsigned short acode, in autf8string areason ); parameters acode the status of the connection when closed; see status codes for possible values. areason a human-readable string describing the reason the connection closed. sendbinarymsg() sends a binary message to the websocket peer. void sendbinarymsg( in acstring amsg ); parameters amsg the data to send. sendmsg() sends a text messa...
nsIWebSocketListener
void onacknowledge( in nsisupports acontext, in pruint32 asize ); parameters acontext user defined...
... in pruint32 asize); void onbinarymessageavailable(in nsisupports acontext, in acstring amsg); void onmessageavailable(in nsisupports acontext, in autf8string amsg); void onserverclose(in nsisupports acontext, in unsigned short acode, in autf8string areason); void onstart(in nsisupports acontext); void onstop(in nsisupports acontext, in nsresult astatuscode); methods onacknowledge() called to acknowledge a message sent via nsiwebsocketchannel.sendmsg() or nsiwebsocketchannel.sendbinarymsg(). void onacknowledge( in nsisupports acontext, in pruint32 asize ); parameters acontext user defined context. asize number of bytes placed in os send buffer. onbinarymessageavailable() called when a binary message has been received. vo...
...e of errors, onstop() may be called without this method ever getting called. no additional messages through onmessageavailable(), onbinarymessageavailable()() or onacknowledge()() will be delievered to the listener after onserverclose() is called, but outgoing messages can still be sent through the nsiwebsocketchannel connection. void onserverclose( in nsisupports acontext, in unsigned short acode, in autf8string areason ); parameters acontext user defined context. acode the websocket closing handshake status code; see status codes for possible values. areason a text string explaining the reason for the closure of the connection. onstart() called to signify the establishment of the message stream. any listener that receives onstart() will also receive onstop().
... parameters acontext user defined context. onstop() called to signify the completion of the message stream. this is the final notification the listener will receive; once it's been received, the websocket connection is complete. this event can be received in error cases even if nsiwebsocketchannel.close() has not been called. void onstop( in nsisupports acontext, in nsresult astatuscode ); parameters acontext user defined context. astatuscode reason for stopping (ns_ok if completed successfully). see also websockets nsiwebsocketchannel ...
nsIWindowsRegKey
ive hkey and is available to provide c++ consumers with the flexibility of making other windows registry api calls that are not exposed via this interface. it is possible to initialize this object by setting an hkey on it. in that case, it is the responsibility of the consumer setting the hkey to ensure that it is a valid hkey. warning: setting the key does not close() the old key. native code only! valuecount unsigned long this attribute returns the number of values under this key. read only. constants root key constants the values for these keys correspond to the values from winreg.h in the ms platform sdk. the root_key_ prefix corresponds to the hkey_ prefix in the ms platform sdk. this interface is not restricted to using only these root keys. constant...
...he value to query. return value the 64-bit integer contents of the named value. readintvalue() this method reads the integer contents of the named value. unsigned long readintvalue( in astring name ); parameters name the name of the value to query. return value the integer contents of the named value. readstringvalue() this method reads the string contents of the named value as a unicode string. astring readstringvalue( in astring name ); parameters name the name of the value to query. this parameter can be the empty string to request the key's default value. return value the string contents of the named value as a unicode string. note: unlike writestringvalue(), readstringvalue() will work with reg_multi_sz and reg_expand_sz types. note: in gecko 2.0, readstringva...
...the key initiated by a call to startwatching(). this method does nothing if the key is not being watched. void stopwatching(); parameters none. writebinaryvalue() this method writes the binary contents of the named value. the value will be created if it does not already exist. javascript callers should take care with the value passed to this method since it will be truncated from a js string (unicode) to a iso-latin-1 string. (the binary data will be treated as an iso-latin-1 character string, which it is not). so, javascript callers should only pass character values in the range \u0000 to \u00ff, or else data loss will occur. void writebinaryvalue( in astring name, in acstring data ); parameters name the name of the value to modify. data the data for the value to modify...
.... data the data for the value to modify. writeintvalue() this method writes the integer contents of the named value. the value will be created if it does not already exist. void writeintvalue( in astring name, in unsigned long data ); parameters name the name of the value to modify. data the data for the value to modify. writestringvalue() this method writes the unicode string contents of the named value. the value will be created if it does not already exist. void writestringvalue( in astring name, in astring data ); parameters name the name of the value to modify. this parameter can be the empty string to modify the key's default value. data the data for the value to modify. ...
XPCOM tasks
tandard libraries. its role is to extend them with facilities tailored to xpcom development in general, and specifically the needs of mozilla. like the standard libraries, xpcom must be a fairly self-contained library, so as not to encumber clients with any unnecessary external dependencies. changes to the build hierarchy there are things in xpcom that don't belong there. there is likely to be code outside of xpcom that should be in it. there is code above xpcom that should be below it. p3 i/o functionality (except for the filespec facility) probably doesn't belong in xpcom; perhaps it should be moved to netwerk p3 the `twips' units routines (or perhaps all routines) in "nsunitconversion.h" probably belong in layout. p3 nsstringtokenizer probably belongs in the parser. 5.1 3rd party co...
...ow it. p3 i/o functionality (except for the filespec facility) probably doesn't belong in xpcom; perhaps it should be moved to netwerk p3 the `twips' units routines (or perhaps all routines) in "nsunitconversion.h" probably belong in layout. p3 nsstringtokenizer probably belongs in the parser. 5.1 3rd party code that doesn't use any services from our tree should be below xpcom; particularly, code xpcom could exploit, e.g., expat berkeley db changes to apis, functionality, and implementations the following items are listed (very) roughly in their order of importance, i.e., fixing observers is the first thing i want to do. p1 various threading issues, e.g., too many locks. see bug 13009. not enough locks. see bug 5795, bug 12755, and bug 12755. p1 we would like to move to a sche...
...changes to apis, functionality, and implementations the following items are listed (very) roughly in their order of importance, i.e., fixing observers is the first thing i want to do. p1 various threading issues, e.g., too many locks. see bug 13009. not enough locks. see bug 5795, bug 12755, and bug 12755. p1 we would like to move to a scheme where no one writes queryinterface, and we save code-space with a table driven implementation. a first step is moving all qi implementations to the table-like macros already in place (and some slight modifications to those macros). see bug 23737 work is progressing on this. see in particular, the new ns_interface_map_... macros in "nsisupportsutils.h". p1 we need to use ns_get_iid instead of ns_define_iid. see bug 25886. work is progressing on ...
...5.1 we want to provide some mechanism for user-specific components in a multi-user environment. 5.1 fix the shutdown issues that complicate life for embedding applications. things we need to evangelize we need to keep up-to-date documentation, samples, and have brown-bags to keep people informed. we've been doing this, but it should be in the plan. general xpcom guidelines. see, e.g., xpcom code faq, idl author's guide, and implementing queryinterface. writing and using components and modules. building ownership models that work (see xpcom ownership guidelines), using raw pointers, nscomptr (see the nscomptr user's manual), nsiweakreference (see nsiweakreference), nscweakreference, and (across threads) proxies (see nsisupports proxies). original document information author(s): unk...
wrappedJSObject
see xpcnativewrapper for detailed documentation. ...
...terfaces as declared in xpidl. the rest of this article demonstrates what xpconnect wrappers do and how wrappedjsobject can be used to bypass them. example component to see how the wrappedjsobject property works, we need an example xpcom component implemented in js. see how to build an xpcom component in javascript for details on creating one. for simplicity we omit the component registration code. suppose we register the component below with the @myself.com/my-component;1 contract. // constructor function helloworld() { }; helloworld.prototype = { hello: function() { return "hello world!"; }, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsihelloworld)) throw components.results.ns...
... nsisupports: > comp.queryinterface(components.interfaces.nsihelloworld); [xpconnect wrapped (nsisupports, nsihelloworld)] as you can see, the queryinterface call also made the wrapper know about the other interface our component supports. assuming the nsihelloworld interface defines the hello method, we can now call it: > comp.hello() hello world! while this behavior is nice for production code as it forces you to clearly define the interfaces that should be used to access the component, it's inconvenient to write the interfaces (and recompile each time you change them) when working on a prototype of the component. meet wrappedjsobject xpconnect lets you bypass its wrappers and access the underlying js object directly using the wrapper.wrappedjsobject property if the wrapped object al...
...if the wrapped object allows this. more specifically, as xpconnect source comments say, you can get comp.wrappedjsobject if three conditions are met: comp really is an xpconnect wrapper around a js object. wrappers around non-js objects don't have this property. the underlying object has a wrappedjsobject property that returns a js object. nsixpcsecuritymanager allows access (see the source code comments for details; this is usually not an issue for mozilla extensions and applications) this means that in order to access the js object implementing our component directly, we must modify the component. for example: function helloworld() { this.wrappedjsobject = this; }; now we can get the component directly: var comp = components.classes["@myself.com/my-component;1"] ...
Thunderbird Binaries
e: while beta builds have had some testing, they should be considered preview only and should not be used in a production environment. please read the release notes before downloading. preview releases are available from http://www.mozilla.org/thunderbird/channel/ nightly builds nightly builds are cutting-edge builds. they are built every 24 hours by the tinderboxes from the very latest source code. there are various sorts of nightly builds available for download. if you wish to download nightly builds to help us test for the next release, please read the testing page for where we need help. warning: whilst developers try to ensure that nightly builds are stable, it is possible that errors can get into nightly builds that can destroy your data or harm it. they should only be used for ...
... warning: whilst developers try to ensure that nightly builds are stable, it is possible that errors can get into nightly builds that can destroy your data or harm it. they should only be used for testing purposes. if you wish to use a nightly build on your main profile, you should make sure you back up your profile. nightly builds from the comm-central trunk the trunk is the central source code that is used for continuous and ongoing development. trunk builds contain the very latest bleeding-edge changes and updates, as well as 64-bit builds for windows. latest english trunk builds are available at: https://archive.mozilla.org/pub/thunderbird/nightly/latest-comm-central/ latest localized trunk builds are available at: https://archive.mozilla.org/pub/thunderbird/nightly/latest-comm-cen...
....org/pub/thunderbird/nightly/latest-comm-central/ latest localized trunk builds are available at: https://archive.mozilla.org/pub/thunderbird/nightly/latest-comm-central-l10n/ note: please use http://ftp.stage.mozaws.net/pub/thunderbird/nightly/latest-comm-central/ because the above two links currently do not work. frequently asked questions what is the trunk? the trunk is the central source code that is used for continuous and ongoing development. trunk builds contain the very latest bleeding-edge changes and updates. the trunk can be very unstable at times, so it's good to ask around before using trunk builds. what is a branch? branches are "forks" in the code, split from the trunk and destined to become end-user releases. at conception, a branch contains everything that the trunk con...
...some of their changes may also take months to test and implement correctly. their changes will be made to the trunk so that they don't delay the release and will be picked up in future branches. ...
customDBHeaders Preference
f( "mailnews.customdbheaders", "x-superfluous,x-other"); important: please pay careful attention to the case of the mailnews.customdbheaders preference. because comparisons are case-insensitive, all of the custom headers get set to lowercase when the data gets migrated to the message database. also, it has been brought to my attention that the delimiter has been changed to a space in the latest code. ...
...e case of the mailnews.customdbheaders preference. because comparisons are case-insensitive, all of the custom headers get set to lowercase when the data gets migrated to the message database. also, it has been brought to my attention that the delimiter has been changed to a space in the latest code. ...
...this is the superfluous.js file referenced from within the superfluous_overlay.xul file: dump(" ~ ~ ~ ~ superfluous ~ ~ ~ ~ \n"); ...
..."hidden ordinal width" currentview="unthreaded" flex="1" label="superfluous" tooltiptext="click to sort by superfluous" /> </treecols> </tree> </overlay> you should insure that whatever id you use for the treecol you're adding matches the reference from your javascript code (i.e. gdbview.addcolumnhandler("colsuperfluous",columnhandler)). javascript code once again, other tutorials have demonstrated the general javascript code used to populated columns with data from a message header, so i'm just including my file for reference. this is the superfluous.js file referenced from within the superfluous_overlay.xul file: dump(" ~ ~ ~ ~ superfluous ~ ~ ~ ~ \n"); var columnhandler = { getcelltext: function(row, col) { //get the messages h...
Zombie compartments
this page tells you how to detect and avoid zombie compartments, which are a particular kind of memory leak. they can be caused by bugs in firefox itself, or by bugs in firefox add-ons. compartments firefox’s javascript memory is segregated into zones and compartments. roughly speaking, all memory used by javascript code that is from a particular origin (i.e. website) goes into its own compartment. firefox’s own javascript code also gets one or more compartments and so do add-on scripts. multiple compartments can share a zone, where a zone keeps track of things that can easily and securely be shared between related compartments such as string data and type information. viewing live compartments if you want to see a list of live compartments, type "about:memory" into the add...
...mb (02.74%) -- active/window(https://www.google.de/) │ │ │ ├───7.83 mb (01.57%) -- js-compartment(https://www.google.de/) │ │ │ │ ├──3.56 mb (00.71%) -- objects │ │ │ │ │ ├──3.04 mb (00.61%) ++ gc-heap │ │ │ │ │ ├──0.51 mb (00.10%) ++ malloc-heap │ │ │ │ │ └──0.00 mb (00.00%) ── non-heap/code/asm.js │ │ │ │ ├──2.43 mb (00.49%) -- shapes │ │ │ │ │ ├──1.47 mb (00.29%) ++ gc-heap │ │ │ │ │ └──0.96 mb (00.19%) ++ malloc-heap │ │ │ │ ├──1.03 mb (00.21%) -- scripts │ │ │ │ │ ├──0.72 mb (00.14%) ── gc-heap [2] │ │ │ │ │ └──0.31 mb (00.06%) ── malloc-heap...
...ts to be created for a single web page. for example, if i open www.techcrunch.com the following compartments are created. compartment(http://techcrunch.com/) compartment(http://www.facebook.com/plugins/like.php?...) compartment(https://plusone.google.com/_/+1/fastbutton?...) compartment(http://platform.twitter.com/widgets/...utton.html?...) compartment(http://cdn.at.atwola.com/_media/uac/tcode3.html) compartment(https://s-static.ak.fbcdn.net/connec..._proxy.php?...) compartment(http://ads.tw.adsonar.com/adserving/getads.jsp?...) (some of those compartment urls are long and have been truncated.) another thing to beware is each compartment is created for an origin (e.g. https://www.facebook.com/), but the name of the compartment includes all the trailing gunk (e.g. "plugins/like.php...
... and bug 700547. restartless add-ons should also take special care that all their compartments get destroyed after disabling or uninstalling the add-on. (please note that you may need to close the about:addons ui before changes are made). avoiding zombie compartments in add-ons once you know that an add-on causes a zombie compartment, the only way to identify the cause is to read the add-on's code. see common causes of memory leaks in extensions for things to avoid. ...
Declaring and Using Callbacks
warning: callbacks must be invoked on the same thread with which they were registered. there is no concurrency logic in js-ctypes, so invoking callbacks on other threads will cause things to crash. ...
...k() { return undefined; // as the return of the functiontype was ctypes.void_t we must return undefined or dont return at all otherwise js-ctypes will throw an error saying unexpected type } var myccallback = myfunctypedeclaration.ptr(myjscallback); using callbacks since callbacks are function pointers in c, js-ctypes has special handling for function pointer types. consider the following code: function myjscallback(foo, bar) { .... }; var functype = ctypes.functiontype(...); var funcptrtype = functype.ptr; var regularfuncptr = funcptrtype(); var callback = funcptrtype(myjscallback); js-ctypes detects that funcptrtype is a type of function pointer, and adds a special case to its constructor. in the ordinary case, invoking the type object creates a regular cdata object containing a p...
...e of function pointer, and adds a special case to its constructor. in the ordinary case, invoking the type object creates a regular cdata object containing a pointer to the data. however, if the first argument is a function, js-ctypes creates a special object (known internally as a cclosure) that wraps the javascript function within an ordinary c function. this can all be done in a single line of code, like so: var callback = ctypes.functiontype(...).ptr(function(...) {...}); note: the use of .ptr() here isn't a method call; we're accessing a property that dynamically creates a callable object, and then invoking the result. if two arguments are passed to the callback constructor, the second is used as the this parameter: function myjscallback() { alert(this.message); }; var receiver = ...
...d as a sentinel value which the callback returns if an exception is thrown. the sentinel value must be convertible to the return type of the callback: function myjscallback() { throw "uh oh"; }; var callback1 = funcptrtype(myjscallback, null, -1); // returns -1 to the native caller when the exception is thrown. warning: you must store a reference to the callback object as long as the native code might call it. if you don't, the gc might collect the relevant data structures, and the browser will crash when native code attempts to invoke your callback. arguments and return values js-ctypes automatically handles the conversion between javascript and c value representations. before the javascript callback function is invoked, js-ctypes converts the arguments passed by the caller to javascr...
Working with ArrayBuffers
an arraybuffer is a simply byte array. the js-ctypes equivalent is a ctypes.uint8_t.array(###) (ctypes.unsigned_char are also ctypes.uint8_t). bug 732936 includes a discussion of working with an arraybuffer. ...
...cpp#3080 //github.com/realityripple/uxp/blob/master/js/src/vm/arraybufferobject.cpp#1301 example 1 - image data the following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to imagedata of canvas. this example is based on the fact that the imagedata returned from canvasrenderingcontext2d.getimagedata is a uint8clampedarray view for an arraybuffer. ...
...ter to a rgba pixel buffer of 400x400 image. pixelbuffer.tostring(); // "ctypes.uint8_t.ptr(ctypes.uint64("0x352e0000"))" var imgwidth = 400; var imgheight = 400; var myimgdat = new imagedata(imgwidth, imgheight); method 1: passing arraytype cdata to uint8clampedarray.prototype.set one method is to get into a js-ctypes array, and then set it into the imagedata, as illustrated by the following code example. // cast pointer to array, to pass to uint8clampedarray.prototype.set. var casted = ctypes.cast(pixelbuffer.address(), ctypes.uint8_t.array(myimgdata.data.length).ptr).contents; // myimgdat.data.length is imgwidth * imgheight * 4 because per pixel there is r, g, b, a numbers casted.tostring(); // "ctypes.uint8_t.array(640000)([45, 66, 135, 255, 99, 86, 55, 255, .......... ])" myimgdat.da...
...[45, 66, 135, 255, 99, 86, 55, 255, .......... ])" myimgdat.data.set(casted); the ctypes.cast takes a couple of milliseconds, however, the myimgdat.data.set takes up to 800ms for a size of 52,428,800 (which is image size of 1280 x 1024 pixels). so, for the size of 640,000 it takes about 98ms. ...
Using js-ctypes
before you can use js-ctypes, you need to import the ctypes.jsm code module. this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use. on windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the returned object is a library object that you use to declare functions and data types for use wit...
...l to close the library, it will be automatically closed when it is garbage collected. using the library you may need to declare new types. these can be simple types or more complex types such as structures. see declaring types for details. you will almost certainly need to declare one or more functions, so that you can call them. once you've declared the types and functions, you can write your code to make use of them. instantiating c data objects and referencing them is covered in the article working with data. memory management moved to memory management page. examples these examples offer a quick look at how js-ctypes is used. see js-ctypes examples for more intricate examples. calling windows routines this example demonstrates how to use ctypes to call a win32 api. components.uti...
...unction messageboxw. line 15 calls the msgbox() routine, which displays the alert. the last thing we do is call lib.close() to close the library when we're done using it. instead of defining the whole path, you may also just give the file name. about declaring the function how we knew how to declare the function was by going to msdn site and looking at the messagebox (messageboxw is just a unicode version of same function) function. also learn about the lib.declare function used here: lib.declare. learn about the data types used here: data types. we see that it needs to be defined like this: int winapi messagebox( _in_opt_ hwnd hwnd, _in_opt_ lpctstr lptext, _in_opt_ lpctstr lpcaption, _in_ uint utype ); so we read this article here on defining types and replicate it: dec...
... even without the extension. var lib = ctypes.open("user32"); calling carbon routines on mac os x this example demonstrates how to use ctypes to call a carbon function on mac os x. ...
Constants - Plugins
nperr_invalid_instance_error 2 invalid instance passed to the plug-in. nperr_invalid_functable_error 3 function table invalid. nperr_module_load_failed_error 4 loading of plug-in failed. nperr_out_of_memory_error 5 memory allocation failed. ...
... nperr_invalid_instance_error 2 invalid instance passed to the plug-in. nperr_invalid_functable_error 3 function table invalid. nperr_module_load_failed_error 4 loading of plug-in failed. nperr_out_of_memory_error 5 memory allocation failed. ...
...on_error 8 versions of plug-in and communicator do not match. nperr_invalid_param 9 parameter missing or invalid. nperr_invalid_url 10 url missing or invalid. nperr_file_not_found 11 file missing or invalid. nperr_no_data 12 stream contains no data. nperr_stream_not_seekable 13 seekable stream expected. result codes constant value description npres_done 0 (most common): completed normally; all data was sent to the instance. npres_network_err 1 stream failed due to problems with network, disk i/o, lack of memory, or other problems. npres_user_break 2 user canceled stream directly by clicking the stop button or indirectly by some action such as dele...
...k, disk i/o, lack of memory, or other problems. npres_user_break 2 user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. plug-in version constants constant value description np_version_major 0 major version number; changes with major code release number. np_version_minor 22 minor version number; changes with point release number. version feature constants npvers constant: version feature information value description npvers_has_streamoutput 8 streaming data. npvers_has_notification 9 notification of completion. npvers_has_liveconnect 9 liveconnect. ...
URLs - Plugins
n a specific host computer rather than an internet resource. ftp (file transfer protocol) locates files and directories on internet hosts for file download. gopher (gopher protocol) locates specified items on a gopher server. obsolete since gecko 2.0 http (hypertext transfer protocol) locates resources on the internet. javascript executes javascript code that follows the url. netscape-specific. mailto (electronic mail address) locates the internet mailing address of an individual or service. nethelp displays a nethelp topic in a nethelp window. browser-specific. news (usenet news) locates usenet news groups or individual usenet articles. nntp (usenet news using nntp access) locates usenet news group...
...or npn_posturlnotify( npp instance, const char *url, const char *target, uint32 len, const char *buf, npbool file, void* notifydata ); the parameters of this function have the same definitions as those of npn_posturl. the notifydata parameter contains plug-in-private data passed by npp_urlnotify and may be used for tracking multiple posts. ...
...same definitions as those of npn_posturl. the notifydata parameter contains plug-in-private data passed by npp_urlnotify and may be used for tracking multiple posts. posting data to an http server the following code posts two name-value pairs to a cgi script through http. the response from the server is displayed in a new window. char* ppostdata = "content-type:\tapplication/x-www-form-urlencoded\ncontent-length:\t17\n\nname=aaashun@gmail.com\n"; uint32 npostdatalen = (uint32)strlen(ppostdata); npn_posturl(npinstance, "http://www.baidu.com","_blank", npostdatalen, ppostdata, false); uploading files to an ftp server plug-ins can use npn_posturl or npn_posturlnotify to upload files to a remote server using ftp. this example uploads a file from the root of the local file system to an ...
...ile system to an ftp server and displays the response in a frame named response: char* mydata = "file:///c\/mydirectory/myfilename"; uint32 mylength = strlen(mydata) + 1; err = npn_posturl(instance, "ftp://fred@ftp.example.com/pub/", "response", mylength, mydata, true); sending mail a plug-in can send an email message using npn_posturl or npn_posturlnotify. the following code sends a mail message with the default headers from the client machine. char* mydata = "\nhi fred, this is a message from my plug-in!"; uint32 mylength = strlen(mydata) + 1; err = npn_posturlnotify(instance, "mailto:fred@example.com", null, mylength, mydata, false); the example starts by defining the mail message, mydata, and its length, mylength. it sends mydata and mylength to the mailto ...
Debug worker threads - Firefox Developer Tools
setting breakpoints, etc. ...
... setting breakpoints, etc. ...
... setting breakpoints, etc. ...
... setting breakpoints, etc. ...
Examine, modify, and watch variables - Firefox Developer Tools
this feature isn't yet supported in the new debugger. if you need to use it, you can, for now, switch back to the old debugger by visiting about:config and setting the "devtools.debugger.new-debugger-frontend" preference to false. to see the docs for the old debugger, please visit debugger (before firefox 52). examine variables when the code has stopped at a breakpoint, you can examine its state in the variables pane of the debugger: variables are grouped by scope: in function scope you'll see the built-in arguments and this variables as well as local variables defined by the function like user and greeting. similarly, in global scope you'll see global variables you've defined, like greetme, as well as built-in globals like localstorage and console. each object can be expanded...
...ript filter, or by typing into the filter variables box, if you have enabled this in the debugger settings. if a variable exists in the source but has been optimized away by the javascript engine, then it is shown in the variables view, but is given the value (optimized away), and is not editable. ...
...code has stopped at a breakpoint, you can modify variables in the variables pane of the debugger. just click on the variable's current value and you'll be able to type there: watch an expression watch expressions are expressions that are evaluated each time execution pauses. you can then examine the results of these expressions. these are useful in that they let you inspect invariants in your code that you know are there but aren't necessarily in the code ready for inspection. to add a watch expression, click in the box that says "add watch expression" and enter a javascript expression whose output you'd like to monitor as you step through code. then start running your code. ...
...they let you inspect invariants in your code that you know are there but aren't necessarily in the code ready for inspection. to add a watch expression, click in the box that says "add watch expression" and enter a javascript expression whose output you'd like to monitor as you step through code. then start running your code. the watch expression does nothing until you begin to step through your code, so nothing happens until you reach a breakpoint. at that point, a box showing your active watch expressions and their current values will appear: you can step through your code, watching the value of the expression as it changes; each time it does, the box will flash briefly yellow. you can remove a watch expression by clicking the "x" icon next to it, and, of course, you can have more than o...
Set watch expressions - Firefox Developer Tools
each time it does, the box will flash briefly yellow. ...
...each time it does, the box will flash briefly yellow. ...
...each time it does, the box will flash briefly yellow. ...
...xpression and return any results. to set a watch expression, expand the watch expressions sidebar, then click "add watch expression." type the expression you'd like to watch into the text field. the debugger will save the expression and watch it as you step through your code. when the debugger reaches a breakpoint, it will display your watch expressions variables: you can step through your code, watching the value of the expression as it changes. each time it does, the box will flash briefly yellow. you can remove a watch expression by clicking the "x" icon next to it, and you can have more than one watch expression at a time. ...
Set a logpoint - Firefox Developer Tools
the logpoint is especially useful in cases where breaking the execution breaks testing procedures, such as when you are debugging popup windows, or executing focus-related logic. to create a logpoint: right click on a line number in the debugger panel and pick add log action from the context menu. create an expression inline. the result is logged in the console panel every time the line with the logpoint executes. ...
...t of logpoints in the breakpoints side panel. when execution hits a logpoint, the message you have defined is logged to the console. you can make it easier to see the message by opening a split console under the debugger. ...
...when execution hits a logpoint, the message you have defined is logged to the console. you can make it easier to see the message by opening a split console under the debugger. (either press esc or select the elipsis menu (...) and then click show split console.) when should you use logpoints? when you want to know that a specific line in your code has executed, but you don’t want to break code execution, set a logpoint. logpoints are useful to log the value of a variable at a specific point in the code. it’s faster than changing the underlying source code itself to add calls to the console.log method. if you need to execute additional logic related to the source code and you can’t change the source code itself, you can use a logpoint. note that you can use logpoints with source-...
...ion, set a logpoint. logpoints are useful to log the value of a variable at a specific point in the code. it’s faster than changing the underlying source code itself to add calls to the console.log method. if you need to execute additional logic related to the source code and you can’t change the source code itself, you can use a logpoint. note that you can use logpoints with source-mapped code, as well as with your unmapped source files. ...
Using the Debugger map scopes feature - Firefox Developer Tools
it enables you to see the variables from the original source. it’s also possible to inspect variables from the generated scopes (e.g., a bundle file with all concatenated module files). let's take a look at how this works. if you want to follow along, use this example. open the example page and then open the debugger using tools > web developer > debugger (or press ctrl + i and then select the debugger). select the "bundle.js" file in the sources panel on the left and then set a breakpoint at line 102 in the increment function. ...
... file in the sources panel on the left and then set a breakpoint at line 102 in the increment function. ...
...e increment function. when you click the increment button on the page and hit the breakpoint, an additional section is added to the right-hand panel below the call stack to display variables mapped from the original scope, like this: as useful as this is, it would be even nicer if you could view the original code (before it was packages into the "bundle.js" file. right-click on the source code and the context menu now includes an option to jump to original location as shown below. click jump to original location. the debugger opens the file "increment.js" so you can view the original code. notice that your breakpoint is set here in the original code as it was in the corresponding line in the "bundle.js" file. and, since map has been checked in the scopes panel, you also see va...
...s an option to jump to original location as shown below. click jump to original location. the debugger opens the file "increment.js" so you can view the original code. notice that your breakpoint is set here in the original code as it was in the corresponding line in the "bundle.js" file. and, since map has been checked in the scopes panel, you also see variable symbols from the original code. using this feature is expensive in terms of resources, but it certainly makes your life easier when you have to debug source code that has been packaged webpack or a similar tool. ...
Debugger.Environment - Firefox Developer Tools
presents the same debugger.environment instance to the debugger each time. this means that the debugger can use the == operator to recognize when two debugger.environment instances refer to the same environment in the debuggee, and place its own properties on a debugger.environment instance to store metadata about particular environments. ...
... use the == operator to recognize when two debugger.environment instances refer to the same environment in the debuggee, and place its own properties on a debugger.environment instance to store metadata about particular environments. (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.environment instance for a given environment. this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.) if a debugger.environment instance’s referent is not a debuggee environment, then attempting to access its properties (other than inspectable) or call any its methods throws an instance of error. debugger.environment instances prote...
...ult is a debuggee value. javascript engines often omit variables from environments, to save space and reduce execution time. if the given variable should be in scope, but getvariable is unable to produce its value, it returns an ordinary javascript object (not a debugger.object instance) whose optimizedout property is true. this is not an invocation function; if this call would cause debuggee code to run (say, because the environment is a "with" environment, andname refers to an accessor property of the with statement’s operand), this call throws a debugger.debuggeewouldrun exception. setvariable(name,value) storevalue as the value of the variable bound toname in this environment.name must be a string that is a valid ecmascript identifier name;value must be a debuggee value. if t...
...s call throws a debugger.debuggeewouldrun exception. setvariable(name,value) storevalue as the value of the variable bound toname in this environment.name must be a string that is a valid ecmascript identifier name;value must be a debuggee value. if this environment binds no variable namedname, throw a referenceerror. this is not an invocation function; if this call would cause debuggee code to run, this call throws a debugger.debuggeewouldrun exception. find(name) return a reference to the innermost environment, starting with this environment, that bindsname. ifname is not in scope in this environment, return null.name must be a string whose value is a valid ecmascript identifier name. source metadata generated from file: js/src/doc/debugger/debugger.environment.md wat...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
vtools.chrome.enabled preference to true: setting the 'devtools.chrome.enabled' preference open a developer scratchpad (menu button > developer > scratchpad), and select "browser" from the "environment" menu. (this menu will not be present unless you have changed the preference as explained above.) selecting the 'browser' context in the scratchpad enter the following code in the scratchpad: // this simply defines the 'debugger' constructor in this // scratchpad; it doesn't actually start debugging anything. components.utils.import('resource://gre/modules/jsdebugger.jsm'); adddebuggertoglobal(window); (function () { // the debugger we'll use to observe a tab's allocation. var dbg; // start measuring the selected tab's main window's memory // consumptio...
...(log) { // given the log, compute a map from allocation sites to // allocation counts. note that stack entries are '===' if // they represent the same site with the same callers. var counts = new map; for (let site of log) { // this is a kludge, necessary for now. the saved stacks // are new, and firefox doesn't yet understand that they // are safe for chrome code to use, so we must tell it // so explicitly. site = components.utils.waivexrays(site.frame); if (!counts.has(site)) counts.set(site, 0); counts.set(site, counts.get(site) + 1); } // walk from each site that allocated something up to the // root, computing allocation totals that include // children. remember that 'null' is a valid site, // repr...
...page. back in the browser console, evaluate the expression demoplotallocations(). this stops logging allocations, and displays a tree of allocations: an allocation plot, displayed in the console the numbers at the left edge of each line show the total number of objects allocated at that site or at sites called from there. after the count, we see the function name, and the source code location of the call site or allocation. the (root) node's count includes objects allocated in the content page by the web browser, like dom events. indeed, this display shows that popup.xml and content.js, which are internal components of firefox, allocated more objects in the page's compartment than the page itself. (we will probably revise the allocation log to present such allocations in a...
...that popup.xml and content.js, which are internal components of firefox, allocated more objects in the page's compartment than the page itself. (we will probably revise the allocation log to present such allocations in a way that is more informative, and that exposes less of firefox's internal structure.) as expected, the onclick handler is responsible for all allocation done by the page's own code. (the line number for the onclick handler is 1, indicating that the allocating call is located on line one of the handler text itself. we will probably change this to be the line number within page.html, not the line number within the handler code.) the onclick handler calls dodivsandspans, which calls divsandspans, which invokes closures of factory to do all the actual allocation. (it is uncl...
Tutorial: Set a breakpoint - Firefox Developer Tools
this page shows how you can try out the debugger api yourself using firefox’s scratchpad. we use debugger to set a breakpoint in a function, and then evaluate an expression whenever it is hit. this tutorial was tested against firefox 58 beta and nightly. it does not work in firefox 57. since the debugger api is only available to privileged javascript code, you’ll need to use the browser content toolbox to try it out. to do this, open the firefox developer tools, click on the options gear at the upper right of the toolbox, and make sure that both “enable browser chrome and add-on debugging toolboxes” and “enable remote debugging” are checked. these are located at the bottom right of the options panel; you may need to scroll to see them. once they’re checked, you can close ...
...console.log('clicked: ' + what); } </script> visit the html file in your browser, and open the browser content toolbox by opening the firefox menu, choosing “web developer”, and then “browser content toolbox”. if that item doesn’t appear in the “web developer” menu, make sure you checked both boxes to enable the browser content toolbox as explained in step 1. our example code is long enough that the best way to run it is to use the scratchpad panel, which is not enabled by default. to enable it, click on the options gear at the upper right of the browser content toolbox, and make sure the “scratchpad” box in the “default developer tools” section the left is checked. the scratchpad panel should appear at the top of the toolbox alongside the console, debugger, a...
...ich is not enabled by default. to enable it, click on the options gear at the upper right of the browser content toolbox, and make sure the “scratchpad” box in the “default developer tools” section the left is checked. the scratchpad panel should appear at the top of the toolbox alongside the console, debugger, and memory panels. click on the scratchpad panel and enter the following code: components.utils.import("resource://gre/modules/jsdebugger.jsm"); components.utils.import("resource://gre/modules/console.jsm"); // this simply defines 'debugger' in this scratchpad; // it doesn't actually start debugging anything. adddebuggertoglobal(this); // create a 'debugger' instance. var dbg = new debugger; // make the tab's top window a debuggee, and get a // debugger.object referr...
... you have more than one tab visiting a file: url, they all share a single content process, so you may need to use a different element of the array as the debuggee. press “run” in the scratchpad again. now, clicking on “click me!” causes the breakpoint hit to be logged twice—one for each debugger instance. multiple debugger instances can observe the same debuggee. re-running the code in the scratchpad creates a fresh debugger instance, adds the same web page as its debuggee, and then sets a new breakpoint. when you click on the div element, both debuggers’ breakpoints are hit, and both handlers run. this shows how any number of debugger-based tools can observe a single web page simultaneously. in fact, you can use the browser content toolbox’s debugger panel to set its...
Network request list - Firefox Developer Tools
resize the column to the left of it to fit its contents. the reset columns command on the context menu also resets the width of the columns to the default values. clicking the column header label sorts the request list by that column. you can reset the sort to the default by selecting "reset sorting" from the context menu. here is a list of all available columns: status: the http status code returned. the numeric code is displayed on a colored background, to help unusual ones stand out. if there was no response, this column is empty. or you might see a red circle with a diagonal slash for responses that were blocked by the browser or the server. method: the http request method used. domain: domain of the path requested. if the request used ssl/tls and the connection had secu...
...h box recognizes specific keywords, which can be used to filter the requests by specific request properties. those keywords are followed by a colon and a related filter value. the filter values are matched case insensitive. prepending a minus (-) negates the filter. you can combine different filters together by separating them with a space. keyword meaning examples status-code shows resources that have the specific http status code. status-code:304 method shows resources that have were requested via the specific http request method. method:post domain shows resources coming from a specifc domain. domain:mozilla.org remote-ip shows resources coming from a server with the specified ip. remote-ip:63.245.215.53 remote-...
...t-cookie-value shows the resources that have a set-cookie header with a value that matches the specified value. set-cookie-value:true regexp shows the resources having a url that matches the given regular expression. regexp:\d{5} regexp:mdn|mozilla for example, to find all 404, not found, errors, you can type "404" into the search and auto-complete suggests "status-code:404" so you'll end up with something like this: search in requests use the search panel to run a full-text search on headers and content. click the search icon in the toolbar. this opens the search sidebar. enter a string in the search field of the sidebar, and press enter or return. the search results area below the search field displays the requests that contain that string in the re...
...hronous requests. open in style editor for a css resource, opens it in the style editor. start performance analysis use as fetch in console submits the request as a call to the fetch() method in the console. copy as curl the command may include the following options: -x [method] if the method is not get or post --data for url encoded request parameters --data-binary for multipart request parameters --http/version if the http version is not 1.1 -i if the method is head -h one for each request header. if the "accept-encoding" header is present, the curl command includes --compressed instead of -h "accept-encoding: gzip, deflate". this means that the response will be aut...
Flame Chart - Firefox Developer Tools
this gives you a way to know exactly which function was executing at any point during the recording, how long it ran for, and where it was called from. the call tree and the flame chart are both used to analyze your site's javascript, and they both use the same data: a sample of the javascript engine's stack, taken periodically during the recording. but while the call tree organizes this data to show you where your program is spending most time in aggregate across the recording, the flame chart uses it to show you when in the recording particular functions are executing. ...
...e flame chart displays a lot of data, so to get readable results, it's usually necessary to zoom in. in the flame chart view itself, along the x-axis is time. the screenshot above covers the period from 1435ms to a little past 1465ms. along the y-axis are the functions on the call stack at that point in time, with the top-level at the top, and the leaf function at the bottom. functions are color-coded to make them easier to distinguish. this gives you a way to know exactly which function was executing at any point during the recording, how long it ran for, and where it was called from. zooming and panning to work effectively with the flame chart, you'll need to be able to navigate it. there are two main controls you can use to navigate the flame chart: zoom: increase/decrease the...
...op, colored purple, is the sortall() call, running throughout the program from start to finish. underneath that, colored olive-green, are the calls it's making to sort(). underneath that, like the teeth of a comb, are all the calls being made to each sorting algorithm. let's zoom in: this slice is about 140 ms long, and shows us more details of the functions being called by sort(). the sort() code is just this: function sort(unsorted) { console.log(bubblesort(unsorted)); console.log(selectionsort(unsorted)); console.log(quicksort(unsorted)); } the markers labeled "bubb..." and colored olive-green are presumably bubblesort(). the ones colored plain green are presumably the other sort functions. even at a glance, we can see that the bubble sort blocks are much wider (of a longer dura...
... bubblesort() are the calls to swap(). if you counted them all, the call tree view tells us that you'd see 253 of them. all the ones in this zoom are underneath bubblesort(), but according to the call tree view, the profile does contain one under selectionsort(). we can also see that two of the green markers are for selectionsort() and quicksort(), but we're also seeing calls to platform (gecko) code in between our calls to the sorting functions. it seems very likely that this is from the console.log() calls in sort(). ...
Waterfall - Firefox Developer Tools
x-axis is time. recorded operations, called markers, are shown as horizontal bars, laid out in a waterfall to reflect the serial nature of the browser's execution. when a marker is selected you'll see more information about it in a sidebar on the right. this includes the marker's duration and some more information that's specific to the marker type. markers the markers for operations are color-coded and labeled. the following operations are recorded: name and description color detailed information dom event javascript code that's executed in response to a dom event. event type for example, "click" or "message". event phase for example, "target" or "capture". javascript functions exe...
...kers with the console api two markers are directly controlled by console api calls: "console" and "timestamp". console markers these enable you to mark a specific section of the recording. to make a console marker, call console.time() at the start of the section, and console.timeend() at the end. these functions take an argument which is used to name the section. ...
... in firefox 41. starting in firefox 41, the right-hand sidebar will also show the stack at the end of the period: that is, at the point console.timeend() was called. if console.timeend() was called from the resolution of a promise, it will also display "(async: promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made. ...
... settimeout(resolve, t); }); } the waterfall will display a marker for the period between time() and timeend(), and if you select it, you'll see the async stack in the sidebar: timestamp markers timestamps enable you to mark an instant in the recording. to make a timestamp marker, call console.timestamp(). you can pass an argument to label the timestamp. ...
Blob - Web APIs
Web › API › Blob
ontaining the entire contents of the blob interpreted as utf-8 text. examples creating a blob the blob() constructor can create blobs from other objects. ...
...: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data. it then calls url.createobjecturl() to convert the blob into a url. html <p>this example creates a typed array containing the ascii codes for the space character through the letter z, then converts it to an object url. a link to open that object url is created. click the link to see the decoded object url.</p> javascript the main piece of this code for example purposes is the typedarraytourl() function, which creates a blob from the given typed array and returns an object url for it. having converted the data into an ob...
...createobjecturl(new blob([typedarray.buffer], {type: mimetype})) } const bytes = new uint8array(59); for(let i = 0; i < 59; i++) { bytes[i] = 32 + i; } const url = typedarraytourl(bytes, 'text/plain'); const link = document.createelement('a'); link.href = url; link.innertext = 'open the array url'; document.body.appendchild(link); result click the link in the example to see the browser decode the object url. extracting data from a blob one way to read content from a blob is to use a filereader. the following code reads the content of a blob as a typed array: const reader = new filereader(); reader.addeventlistener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readasarraybuffer(blob); another way to read content from a blob is to...
...data from a blob one way to read content from a blob is to use a filereader. the following code reads the content of a blob as a typed array: const reader = new filereader(); reader.addeventlistener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readasarraybuffer(blob); another way to read content from a blob is to use a response. the following code reads the content of a blob as text: const text = await (new response(blob)).text(); or by using blob.prototype.text(): const text = await blob.text(); by using other methods of filereader, it is possible to read the contents of a blob as a string or a data url. specifications specification status comment file apithe definition of 'the blob interface' in that specif...
CanvasRenderingContext2D.miterLimit - Web APIs
see applying styles and color in the canvas tutorial. syntax ctx.miterlimit = value; options value a number specifying the miter limit ratio, in coordinate space units. zero, negative, infinity, and nan values are ignored. the default value is 10.0. examples using the miterlimit property see the chapter applying styles and color in the canvas tutorial for more information. ...
...efault value is 10.0. examples using the miterlimit property see the chapter applying styles and color in the canvas tutorial for more information. ...
... examples using the miterlimit property see the chapter applying styles and color in the canvas tutorial for more information. ...
...ass="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginpath(); ctx.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.addeven...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
crollpathintoview(path); parameters path a path2d path to use. examples using the scrollpathintoview method this example demonstrates the scrollpathintoview() method. ...
... examples using the scrollpathintoview method this example demonstrates the scrollpathintoview() method. ...
... 30); ctx.scrollpathintoview(); edit the code below to see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" min="1" max="12"> </canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginpath(); ctx.rect(10, 10, 30, 30); ctx.scrollpathintoview();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0...
... living standard ...
Applying styles and colors - Web APIs
to be filled (dark blue) only extends halfway into the pixels on either side of the path. an approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blue and dark blue) being filled in with a color only half as dark as the actual stroke color. this is what happens with the 1.0 width line in the previous example code. to fix this, you have to be very precise in your path creation. knowing that a 1.0 width line will extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,5) results in the situation in the third image—the 1.0 line width ends up completely and precisely filling a single pixel vertical line. note: be aware that in our vertical line example, the y position still ...
...d('miterlimit').value); } else { alert('value must be a positive number'); } // draw lines ctx.beginpath(); ctx.moveto(0, 100); for (i = 0; i < 24 ; i++) { var dy = i % 2 == 0 ? ...
...alue); } else { alert('value must be a positive number'); } // draw lines ctx.beginpath(); ctx.moveto(0, 100); for (i = 0; i < 24 ; i++) { var dy = i % 2 == 0 ? ...
...oint to achieve a spherical 3d effect. it's best to try to avoid letting the inside and outside circles overlap because this results in strange effects which are hard to predict. the last color stop in each of the four gradients uses a fully transparent color. if you want to have a nice transition from this to the previous color stop, both colors should be equal. this isn't very obvious from the code because it uses two different css color methods as a demonstration, but in the first gradient #019f62 = rgba(1,159,98,1). screenshotlive sample patterns in one of the examples on the previous page, we used a series of loops to create a pattern of images. there is, however, a much simpler method: the createpattern() method. createpattern(image, type) creates and returns a new canvas pattern...
DirectoryEntrySync - Web APIs
eexception); void removerecursively () raises (fileexception); methods createreader() creates a new directoryreadersync to read entries from this directory. directoryreadersync createreader ( ) raises (fileexception); returns directoryreadersync represents a directory in a file system. parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. security_err the browser determined that it was not safe to look up the metadata. [ todo: explain why ] getfile() depending on how you've set the options parameter, the method either creates a file or looks up an existing file. void getfile ( in domstring path, in optional flags...
...lusive is ignored) path exists the file is returned. create: false (exclusive is ignored) path doesn't exist an error is thrown. create: false (exclusive is ignored) path exists, but is a directory an error is thrown. returns fileentrysync represents a file in a file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the path supplied is invalid. not_found_err the path was structurally correct, but refers to a resource that does not exist. no_modification_allowed_err this is a permission issue. the target directory or file is not writable. path_exists_err the file already exists. you cannot create another one...
...ed) path exists the directory is returned. create: false (exclusive is ignored) path doesn't exist an error is thrown. create: false (exclusive is ignored) path exists, but is a directory an error is thrown. returns directoryentrysync represents a directory in a file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the path supplied is invalid. not_found_err the path was structurally correct, but refers to a resource that does not exist. no_modification_allowed_err this is a permission issue. the target directory or file is not writable. path_exists_err the file already exists. you cannot create another one...
...le system. if you delete a directory that contains a file that cannot be removed or if an error occurs while the deletion is in progress, some of the contents might not be deleted. catch these cases with error callbacks and retry the deletion. void removerecursively ( ) raises (fileexception); parameter none returns void exceptions this method can raise a fileexception with the following codes: exception description not_found_err the target directory does not exist. invalid_state_err this directory is not longer valid for some reason other than being deleted. [todo: explain more ] no_modification_allowed_err one of the following is not writable: the directory, its parent directory, and some of the content in the directory. ...
Document.cookie - Web APIs
Web › API › Document › cookie
the document property cookie lets you read and write cookies associated with the document. it serves as a getter and setter for the actual values of the cookies. syntax read all cookies accessible from this location allcookies = document.cookie; in the code above allcookies is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs). note that each key and value may be surrounded by whitespace (space and tab characters): in fact, rfc 6265 mandates a single space after each semicolon, but some user agents may not abide by this. write a new cookie document.cookie = newcookie; in the code above, newcookie is a string of form key=value. note that you can only set/update a single cookie at a time using this method. consider also that: any of the following cook...
...the default value in modern browsers. the strict value will prevent the cookie from being sent by the browser to the target site in all cross-site browsing contexts, even when following a regular link. the none value explicitly states no restrictions will be applied. the cookie will be sent in all requests—both cross-site and same-site. the cookie value string can use encodeuricomponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values). some user agent implementations support the following cookie prefixes: __secure- signals to the browser that it should only include the cookie in requests transmitted over a secure channel. __host- signals to the browser that in addition to the restrict...
... server omits the path attribute the "directory" of the request uri is used. it also signals that the domain attribute must not be present, which prevents the cookie from being sent to other domains. for chrome the path attribute must always be the origin. the dash is considered part of the prefix. these flags are only settable with the secure attribute. note: as you can see from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the javascript interpreter. examples example #1: simple usage document.cookie = "name=oeschger"; document.cookie = "favorite_food=tripe"; function alertcookie() { alert(d...
... function doonce() { if (!document.cookie.split('; ').find(row => row.startswith('dosomethingonlyonce'))) { alert("do something here!"); document.cookie = "dosomethingonlyonce=true; expires=fri, 31 dec 9999 23:59:59 gmt"; } } <button onclick="doonce()">only do something once</...
Event.preventDefault() - Web APIs
able: true has no effect. syntax event.preventdefault(); examples blocking default click handling toggling a checkbox is the default action of clicking on a checkbox. ...
...t. syntax event.preventdefault(); examples blocking default click handling toggling a checkbox is the default action of clicking on a checkbox. ...
...r name using lowercase letters only.</p> <form> <input type="text" id="my-textbox"> </form> </div> css we use a little bit of css for the warning box we'll draw when the user presses an invalid key: .warning { border: 2px solid #f39389; border-radius: 2px; padding: 10px; position: absolute; background-color: #fbd8d4; color: #3b3c40; } javascript and here's the javascript code that does the job. first, listen for keypress events: var mytextbox = document.getelementbyid('my-textbox'); mytextbox.addeventlistener('keypress', checkname, false); the checkname() function, which looks at the pressed key and decides whether to allow it: function checkname(evt) { var charcode = evt.charcode; if (charcode != 0) { if (charcode < 97 || charcode > 122) { evt.preve...
...xtbox'); mytextbox.addeventlistener('keypress', checkname, false); the checkname() function, which looks at the pressed key and decides whether to allow it: function checkname(evt) { var charcode = evt.charcode; if (charcode != 0) { if (charcode < 97 || charcode > 122) { evt.preventdefault(); displaywarning( "please use lowercase letters only." + "\n" + "charcode: " + charcode + "\n" ); } } } the displaywarning() function presents a notification of a problem. it's not an elegant function but does the job for the purposes of this example: var warningtimeout; var warningbox = document.createelement("div"); warningbox.classname = "warning"; function displaywarning(msg) { warningbox.innerhtml = msg; if (document.body.contains(warningbox))...
FileException - Web APIs
in the file system api, a fileexception object represents error conditions that you might encounter while accessing the file system using the synchronous api. it extends the fileexception interface described in file writer and adds several new error codes. basic concepts synchronous apis do not have error callbacks, which makes it difficult to catch errors. the added complexity of using webworkers with this api makes debugging even more challenging. to simplify things a bit, wrap your worker code in a try/catch. when errors occur, forward them to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" already exists. var fileentry = fs.root.getfile('log.txt', {create: true, excl...
... constants note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. ...
... to the main app using postmessage() as in the following: function onerror(e) { postmessage('error:' + e.tostring()); } try { //error is thrown if "log.txt" already exists. var fileentry = fs.root.getfile('log.txt', {create: true, exclusive:true}0; } catch (e) { onerrror(e); } the sample code was borrowed from html5rocks attribute attribute type description code unsigned short the most appropriate error code for the condition. constants note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. constant value description encoding_err 5 the url is malformed. make sure that the url is complete and valid. invalid_...
...'s not enough remaining storage space or the storage quota was reached and the user declined to give more space to the database. security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application. too many calls are being made on file resources. other unspecified security error code or situations. type_mismatch_err 11 the user has attempted to look up a file or directory, but the entry found is of the wrong type. for example, the app is accessing a directoryentry when the user is requesting a fileentry. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please ...
FileSystemEntrySync - Web APIs
f the filesystementrysync is a file. name readonly domstring the name of the entry, excluding the path leading to it. methods getmetadata() look up metadata about this entry. [ todo: specify what kind of metadata ] metadata getmetada () raises (fileexception); parameter none returns metadata exceptions this method can raise a fileexception with the following codes: exception description not_found_err the entry does not exist. invalid_state_err the filesystemsync is no longer valid for some reason besides being deleted. moveto() move an entry to a different location on the file system. moving a file over an existing file replaces that existing file. moving a directory over an existing empty directory replace...
...arent, optional domstring newname ) raises (fileexception); parameters parent the directory to which to move the entry. newname the new name of the entry. if you do not specify a name, the browser preserves the entry's current name. returns filesystementrysync an object that represents an entry in the file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the name supplied is invalid, because at least one of the characters is reserved or illegal. examples include a backslash (\), dot (.), and two dots (..). not_found_err the target directory does not exist. invalid_modification_err you tried one of the following disallowed operations: moving ...
...ng newname ) raises (fileexception); parameters parent the directory where you want the entry to move to. newname the new name of the entry. if you do not specify a name, the browser preserves the filesystementrysync's current name. returns filesystementrysync an object that represents an entry in the file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the name supplied is invalid, because at least one of the characters is reserved or illegal. examples include a backslash (\), dot (.), and two dots (..). not_found_err the target directory does not exist. invalid_modification_err you tried one of the following disallowed operations: moving ...
... parameter none. returns domstring exceptions none remove() deletes a file or directory. you cannot delete an empty directory or the root directory of a file system. if you want to remove an empty directory, use removerecursively() instead. void remove ( ) raises (fileexception); parameter none returns void exceptions this method can raise a fileexception with the following codes: exception description not_found_err the target directory does not exist. invalid_modification_err you tried to remove a directory that is not empty. if you want to remove an empty directory, use removerecursively() instead. no_modification_allowed_err one of the following is not writable: the source entry, its parent directory, and t...
IDBDatabaseSync - Web APIs
y path used by the new object store. if a null path is specified, then the object store does not have a key path, and uses out-of-line keys. autoincrement if true, the object store uses a key generator; if false, it does not use one. returns idbobjectstoresync an object to access the newly created object store. exceptions this method can raise an idbdatabaseexception with the following code: constraint_err if an object store with the same name (based on case-sensitive comparison) already exists in the connected database. openobjectstore() opens the object store with the given name in the connected database using the specified mode. idbobjectstoresync openobjectstore ( in domstring name, in optional unsigned short mode ) raises (idbdatabaseexception); parameters name...
... idbobjectstoresync openobjectstore ( in domstring name, in optional unsigned short mode ) raises (idbdatabaseexception); parameters name the name of the object store to open. mode the mode that is used to access the object store. returns idbobjectstoresync an object to access the opened object store. exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if an object store with the given name (based on case-sensitive comparison) already exists in the connected database. removeobjectstore() destroys an object store with the given name, as well as all indexes that reference that object store. void removeobjectstore ( in domstring storename ) raises (idbdatabaseexception); parameters storename the name of an existing o...
... connected database. removeobjectstore() destroys an object store with the given name, as well as all indexes that reference that object store. void removeobjectstore ( in domstring storename ) raises (idbdatabaseexception); parameters storename the name of an existing object store to remove. returns void exceptions this method can raise an idbdatabaseexception with the following code: not_found_err if the object store with the given name (based on case-sensitive comparison) does not exist in the connected database. setversion() sets the version of the connected database. void setversion ( in domstring version ); parameters returns void version the version to store in the database. transaction() creates and returns a transaction, acquiring locks on the ...
...rs storenames the names of object stores and indexes in the scope of the new transaction. timeout the interval that this operation is allowed to take to acquire locks on all the objects stores and indexes identified in storenames. returns idbtransactionsync an object to access the newly created transaction. exceptions this method can raise an idbdatabaseexception with the following code: timeout_err if reserving all the database objects identified in storenames takes longer than the timeout interval. ...
KeyboardEvent.shiftKey - Web APIs
the keyboardevent.shiftkey read-only property is a boolean that indicates if the shift key was pressed (true) or not (false) when the event occurred. ...
...ardevent.shiftkey read-only property is a boolean that indicates if the shift key was pressed (true) or not (false) when the event occurred. ...
...nly property is a boolean that indicates if the shift key was pressed (true) or not (false) when the event occurred. ...
...a boolean that indicates if the shift key was pressed (true) or not (false) when the event occurred. ...
Keyboard API - Web APIs
to correctly identify that key to a user. keyboard locking enables a web page to capture keys that are normally reserved by the user agent or the underlying operating system. the intended use of the keyboard api is by web applications such as games or remote access apps that provide a full-screen immersive experience. keyboard api concepts and usage keyboard mapping on physical keyboards, the code attribute contains the physical location of the key that was pressed, and the key attribute contains the string generated by pressing the key at that physical location on the keyboard. the key value takes into account the keyboard's locale (for example, 'en-us'), layout (for example, 'qwerty'), and modifier-key state (shift, control, etc.). historically there has been no way to retrieve that info...
...information. the keyboard map api provides a way to retrieve the string generated by a particular key press, through the keyboard interface and the keyboardlayoutmap interface. the keyboard interface is accessed through navigator.keyboard. keyboard provides the keyboard.getlayoutmap method, which returns a promise that resolves with a keyboardlayoutmap object that contains members for converting codes to keys. a list of valid code values is found in the writing system keys section of the ui events keyboardevent code values spec. the following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled w on an english qwerty keyboard. if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardla...
...en require access to special keys and keyboard shortcuts while in full-screen mode. examples of such key/key combinations include escape, alt+tab, and ctrl+n. those keys and key combinations are typically captured by the user agent or the underlying operating system, as illustrated in the following example. to capture the "w", "a", "s", and "d" keys, call lock() with a list that contains the key code attribute value for each of these keys: navigator.keyboard.lock(["keyw", "keya", "keys", "keyd"]); this captures these keys regardless of which modifiers are used with the key press. assuming a standard united states qwerty layout, registering keyw ensures that "w", shift+"w", control+"w", control+shift+"w", and all other key modifier combinations with "w" are sent to the app. the same applies ...
...yboard.lock(["keyw", "keya", "keys", "keyd"]); this captures these keys regardless of which modifiers are used with the key press. assuming a standard united states qwerty layout, registering keyw ensures that "w", shift+"w", control+"w", control+shift+"w", and all other key modifier combinations with "w" are sent to the app. the same applies to for keya, keys and keyd. writing system keys the codes passed keyboard.lock and the various methods of the keyboardlayoutmap interface are called “writing system keys”. “writing system keys” are defined in the writing system keys section of the ui events keyboardevent code values spec as the physical keys that change meaning based on the current locale and keyboard layout. these keys are shown below. blue keys are present on all standard ke...
LockManager.request() - Web APIs
the request() method of the lockmanager interface requests a lock object with parameters specifying its name and characteristics. the requested lock is passed to a callback, while the function itself returns a promise that resolves with undefined. the mode property of the options parameter may be either "exclusive" or "shared". request an "exclusive" lock when it should only be held by one code instance at a time. this applies to code in both tabs and workers. use this to represent mutually exclusive access to a resource. when an "exclusive" lock for a given name is held, no other lock with the same name can be held. request a "shared" lock when multiple instances of the code can share access to a resource. when a "shared" lock for a given name is held, other "shared" locks for the same ...
... if specified and the abortcontroller is aborted, the lock request is dropped if it was not already granted. callback … return value a promise that resolves with undefined when the request is granted. examples general example the following example shows the basic use of the request() method with an asynchronous function as the callback. once the callback is invoked, no other running code on this orign can hold `my_resource` until the callback returns. await navigator.locks.request('my_resource', async lock => { // the lock was granted. }); mode example the following example shows how to use the mode option for readers and writers. notice that both functions use a lock called my_resource. the do_read() requests a lock in 'shared' mode meaning that multiple calls may occur s...
...ng example shows how to use the mode option for readers and writers. notice that both functions use a lock called my_resource. the do_read() requests a lock in 'shared' mode meaning that multiple calls may occur simultaneously across different event handlers, tabs, or workers. async function do_read() { await navigator.locks.request('my_resource', {mode: 'shared'}, async lock => { // read code here. }); } the do_write() function use the same lock but in 'exclusive' mode which will delay invocation of the request() call in do_read() until the write operation has completed. this applies across event handlers, tabs, or workers. function do_write() { await navigator.locks.request('my_resource', {mode: 'exclusive'}, async lock => { // write code here. }); } ifavailable example ...
... means the method will not return until the callback is complete. since the lock is only granted if it was available, this call avoids needing to wait on the lock being released elsehwere. await navigator.locks.request('my_resource', {ifavailable: true}, async lock => { if (!lock) { // the lock was not granted - get out fast. return; } // the lock was granted, and no other running code in this origin is holding // the 'my_res_lock' lock until this returns. }); signal example to only wait for a lock for a short period of time, use the signal option. const controller = new abortcontroller(); // wait at most 200ms. settimeout(() => controller.abort(), 200); try { await navigator.locks.request('my_resource', {signal: controller.signal}, async lock => { // the lock was ...
MediaConfiguration - Web APIs
ding configuration, to be submitted as the parameter for mediacapabilities.encodinginfo() method, has it's `type` set as: record: for recording media. transmission: for media to be electronically transmitted. a valid audio configuration includes: contenttype: valid audio mime type. channels: number of channels used by the audio track. bitrate: number of bits used to encode one second of the audio file. samplerate: number of audio samples making up one second of the audio file. a valid video configuration includes: contenttype: valid video mime type. width: width of the video. height: height of the video. bitrate: number of bits used to encode one second of the video file. framerate: number of frames making up one second of video playback. ...
...aking up one second of the audio file. a valid video configuration includes: contenttype: valid video mime type. width: width of the video. height: height of the video. bitrate: number of bits used to encode one second of the video file. framerate: number of frames making up one second of video playback. ...
...ype. width: width of the video. height: height of the video. bitrate: number of bits used to encode one second of the video file. framerate: number of frames making up one second of video playback. example //create a video configuration to be tested const videodecoderconfig = { type : 'file', // 'record', 'transmission', or 'media-source' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames making up that 1s. ...
...t videodecoderconfig = { type : 'file', // 'record', 'transmission', or 'media-source' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames making up that 1s. } }; const audioencoderconfig = { type : 'file', // 'record', 'transmission', or 'media-source' audio : { contenttype : "audio/ogg", // valid content type channels : 2, // audio channels used by the track bitrate : 132700, // number of bits used to encode 1s of audio samplerate : 5200 // number of audio samples making up that 1s. } }; specifications specification status commen...
MediaDevices.ondevicechange - Web APIs
let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator...
... let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getuser...
...the fulfillment handler is called when the device list is ready. the list is passed into the fulfillment handler as an array of mediadeviceinfo objects, each describing one media input or output device. a foreach() loop is used to scan through all the devices. for each device, we create a new <li> object to be used to displ...
... or videolist, as appropriate based on the device type. handling device list changes we call updatedevicelist() in two places. the first is in the getusermedia() promise's fulfillment handler, to initially fill out the list when the stream is opened. the second is in the event handler for devicechange: navigator.mediadevices.ondevicechange = function(event) { updatedevicelist(); } with this code in place, each time the user plugs in a camera, microphone, or other media device, or turns one on or off, we call updatedevicelist() to redraw the list of connected devices. result specifications specification status comment media capture and streamsthe definition of 'ondevicechange' in that specification. candidate recommendation initial specification. ...
MediaRecorder() - Web APIs
syntax var mediarecorder = new mediarecorder(stream[, options]); parameters stream the mediastream that will be recorded. ...
... syntax var mediarecorder = new mediarecorder(stream[, options]); parameters stream the mediastream that will be recorded. ...
... syntax var mediarecorder = new mediarecorder(stream[, options]); parameters stream the mediastream that will be recorded. ...
...be recorded. this source media can come from a stream created using navigator.mediadevices.getusermedia() or from an <audio>, <video> or <canvas> element. options optional a dictionary object that can contain the following properties: mimetype: a mime type specifying the format for the resulting media; you may simply specify the container format (the browser will select its preferred codecs for audio and/or video), or you may use the codecs parameter and/or the profiles parameter to provide detailed information about which codecs to use and how to configure them. applications can check in advance if a mimetype is supported by the user agent by calling mediarecorder.istypesupported(). audiobitspersecond: the chosen bitrate for the audio component of the media. videobitspersecon...
MediaRecorder.mimeType - Web APIs
the mimetype read-only property returns the mime media type that was specified when creating the mediarecorder object, or, if none was specified, which was chosen by the browser. this is the file format of the file that would result from writing all of the recorded data to disk. keep in mind that not all codecs are supported by a given container; if you write media using a codec that is not supported by a given media container, the resulting file may not work reliably if at all when you try to play it back. see our media type and format guide for information about container and codec support across browsers. note: the term "mime type" is officially considered to be historical; these strings are now officially known as media types. mdn web docs content uses the terms interchangeably. synt...
... the media type strings are standardized by the internet assigned numbers authority (iana). for their official list of defined media type strings, see the article media types on the iana site. ...
...wsers. note: the term "mime type" is officially considered to be historical; these strings are now officially known as media types. mdn web docs content uses the terms interchangeably. syntax var mimetype = mediarecorder.mimetype value the mime media type which describes the format of the recorded media, as a domstring. this string may include the codecs parameter, giving details about the codecs and the codec configurations used by the media recorder. the media type strings are standardized by the internet assigned numbers authority (iana). for their official list of defined media type strings, see the article media types on the iana site. see also media types to learn more about media types and how they're used in web content and by web browers. example ... if (navigator.mediadevi...
...er; m.mimetype; // would return 'video/mp4' ... }) .catch(function(error) { console.log(error.message); }); changing line 14 to the following causes mediarecorder to try to use avc constrained baseline profile level 4 for video and aac-lc (low complexity) for audio, which is good for mobile and other possible resource-constrained situations. mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assuming this configuration is acceptable to the user agent, the value returned later by m.mimetype would then be video/mp4; codecs="avc1.424028, mp4a.40.2". specifications specification status comment mediastream recordingthe definition of 'mediarecorder.mimetype' in that specification. working draft initial definition ...
MediaRecorder - Web APIs
top event, which occurs when media recording ends, either when the mediastream ends — or after the mediarecorder.stop() method is called. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. also available via the onerror property. example if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var mediarecorder = new mediarecorder(stream); visualize(stream); record.onclick = function() { mediarecorder.start...
...t.add('clip'); audio.setattribute('controls', ''); deletebutton.innerhtml = "delete"; cliplabel.innerhtml = clipname; clipcontainer.appendchild(audio); clipcontainer.appendchild(cliplabel); clipcontainer.appendchild(deletebutton); soundclips.appendchild(clipcontainer); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; var audiourl = url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); deletebutton.onclick = function(e) { evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } }) .catch(f...
... specifications specification status comment mediastream recording working draft initial definition ...
... specifications specification status comment mediastream recording working draft initial definition ...
Using the MediaStream Recording API - Web APIs
eb dictaphone to demonstrate basic usage of the mediarecorder api, we have built a web-based dictaphone. it allows you to record snippets of audio and then play them back. it even gives you a visualization of your device's sound input, using the web audio api. we'll concentrate on the recording and playback functionality for this article. you can see this demo running live, or grab the source code on github. css goodies the html is pretty simple in this app, so we won't go through it here; there are a couple of slightly more interesting bits of css worth mentioning, however, so we'll discuss them below. if you are not interested in css and want to get straight to the javascript, skip to the basic app setup section. keeping the interface constrained to the viewport, regardless of device ...
...e following getusermedia error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser!'); } the whole thing is wrapped in a test that checks whether getusermedia is supported before running anything else. next, we call getusermedia() and inside it define: the constraints: only audio is to be captured for our dictaphone. the success callback: this code is run once the getusermedia call has been completed successfully. the error/failure callback: the code is run if the getusermedia call fails for whatever reason. note: all of the code below is placed inside the getusermedia success callback. capturing the media stream once getusermedia has created a media stream successfully, you create a new media recorder instance with the mediarecorder...
... first, we display a prompt asking the user to name their clip. next, we create an html struc...
... first, we display a prompt asking the user to name their clip. next, we create an html structure like the following, inserting it into our clip container, which is an <article> element. ...
Microdata DOM API - Web APIs
element's value. can be set, to change the element's value. setting the value when the element has no itemprop attribute or when the element's value is an item throws an invalidaccesserror exception. element . properties if the element has an itemscope attribute, returns an htmlpropertiescollection object with all the element's properties. otherwise, an empty htmlpropertiescollection object. code example this sample shows how the getitems() method can be used to obtain a list of all the top-level microdata items of a particular type given in the document: var cats = document.getitems("http://example.com/feline"); once an element representing an item has been obtained, its properties can be extracted using the properties idl attribute. this attribute returns an htmlpropertiescollection,...
... the properties idl attribute. this attribute returns an htmlpropertiescollection, which can be enumerated to go through each element that adds one or more properties to the item. it can also be indexed by name, which will return an object with a list of the elements that add properties with that name. each element that adds a property also has an itemvalue idl attribute that returns its value. code example this sample gets the first item of type "http://example.net/user" and then pops up an alert using the "name" property from that item. var user = document.getitems('http://example.net/user')[0]; alert('hello ' + user.properties['name'][0].itemvalue + '!'); the htmlpropertiescollection object, when indexed by name in this way, actually returns a propertynodelist object with all the match...
...ument.getitems('http://example.net/user')[0]; alert('hello ' + user.properties['name'][0].itemvalue + '!'); the htmlpropertiescollection object, when indexed by name in this way, actually returns a propertynodelist object with all the matching properties. the propertynodelist object can be used to obtain all the values at once usingits getvalues method, which returns an array of all the values. code example in an earlier example, a "http://example.org/animals#cat" item had two "http://example.com/color" values. this script looks up the first such item and then lists all its values. var cat = document.getitems('http://example.org/animals#cat')[0]; var colors = cat.properties['http://example.com/color'].getvalues(); var result; if (colors.length == 0) { result = 'color unknown.'; } else if...
...cat.properties['http://example.com/color'].getvalues(); var result; if (colors.length == 0) { result = 'color unknown.'; } else if (colors.length == 1) { result = 'color: ' + colors[0]; } else { result = 'colors:'; for (var i = 0; i < colors.length; i += 1) result += ' ' + colors[i]; } it's also possible to get a list of all the property names using the object's names idl attribute. code example this example creates a big list with a nested list for each item on the page, each with all of the property names used in that item. var outer = document.createelement('ul'); var items = document.getitems(); for (var item = 0; item < items.length; item += 1) { var itemli = document.createelement('li'); var inner = document.createelement('ul'); for (var name = 0; name < items[item]...
Using Navigation Timing - Web APIs
unlike other tools or libraries, the navigation timing api lets you gather information that only the browser can provide at a level of accuracy much improved over other techniques. it also offers the advantage of being able to provide timing information as perceived by the user rather than data that has no correlation to what the user experiences. ...
...rformance object using window.performance and looking up what you need within the object returned. for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.queryselector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which the navigation whose timing was recorded began (performance.timing.navigationstart), and outputs that information to the screen by inserting it into an element. html <div class="output"> </div> css .output { border: 1px solid #bbb; font: 16px "open sans", "helvetica", "arial", sans-serif; } in tande...
...know: was this a load or a reload? was this a navigation or a move forward or backward through history? how many (if any) redirects were required in order to complete the navigation? this information is provided by the performance.navigation property, which returns a performancenavigation object that includes the needed information. let's add this information to the example above. ...
...the number of redirects that were incurred during the navigation from performance.navigation.redirectcount. this information is output to the screen just like the page load time was previously: by inserting it into the element with class "output". html <div class="output"> </div> css .output { border: 1px solid #bbb; font: 16px "open sans", "helvetica", "arial", sans-serif; } with this code in place, the result looks like this: the values listed are for the <iframe> in which the sample is presented. ...
Page Visibility API - Web APIs
and -150 ms, respectively. chrome is very similar except that the budget is specified in seconds. windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see reasons for delays longer than specified). in chrome, this value is 10 seconds. timer tasks are only permitted when the budget is non-negative. once a timer's code has finished running, the duration of time it took to execute is subtracted from its window's timeout budget. the budget regenerates at a rate of 10 ms per second, in both firefox and chrome. some processes are exempt from this throttling behavior. in these cases, you can use the page visibility api to reduce the tabs' performance impact while they're hidden. tabs which are playing a...
...tracted from its window's timeout budget. the budget regenerates at a rate of 10 ms per second, in both firefox and chrome. some processes are exempt from this throttling behavior. in these cases, you can use the page visibility api to reduce the tabs' performance impact while they're hidden. tabs which are playing audio are considered foreground and aren’t throttled. tabs running code that's using real-time network connections (websockets and webrtc) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed. indexeddb processes are also left unthrottled in order to avoid timeouts. example view live example (video with sound). the example, which pauses the video when you switch to another tab and plays again when you return to it...
...tions (websockets and webrtc) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed. indexeddb processes are also left unthrottled in order to avoid timeouts. example view live example (video with sound). ...
...to the user. a document may start in the prerender state, but will never switch to this state from any other state, since a document can only prerender once. note: not all browsers support prerendering. unloaded the page is in the process of being unloaded from memory. note: not all browsers support the unloaded value. document.onvisibilitychange an eventlistener providing the code to be called when the visibilitychange event is fired. //startsimulation and pausesimulation defined elsewhere function handlevisibilitychange() { if (document.hidden) { pausesimulation(); } else { startsimulation(); } } document.addeventlistener("visibilitychange", handlevisibilitychange, false); specifications specification status comment page vi...
Using the Permissions API - Web APIs
the permissions api in chrome are geolocation and notification, with firefox also recognizing push and webmidi. more features will be added as time progresses. a simple example for this article, we have put together a simple demo called location finder. it uses geolocation to query the user's current location and plot it out on a google map: you can run the example live, or view the source code on github. most of the code is simple and unremarkable — below we'll just be walking through the permissions api-related code, so check the code yourself if you want to study any of the other parts. accessing the permissions api the navigator.permissions property has been added to the browser to allow access to the global permissions object. this object will eventually include methods for que...
...ompted to grant permission for geolocation. the geolocation.getcurrentposition() function is then run, which prompts the user for permission; it runs the revealposition() function if permission is granted (which shows the map), or the positiondenied() function if permission is denied (which makes the "enable geolocation" button appear). "denied" the "enable geolocation" button is revealed (this code needs to be here too, in case the permission state is already set to denied for this origin when the page is first loaded). function handlepermission() { navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { report(result.state); geobtn.style.display = 'none'; } else if (result.state == 'prompt') { report(result.st...
...ervisibleonly is true or false. revoking permissions starting in firefox 47, you can now revoke existing permissions, using the permissions.revoke() method. this works in exactly the same way as the permissions.query() method, except that it causes an existing permission to be reverted back to its default state when the promise successfully resolves (which is usually prompt). see the following code in our demo: var revokebtn = document.queryselector('.revoke'); ... revokebtn.onclick = function() { revokepermission(); } ... function revokepermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(result) { report(result.state); }); } the revoke() function has been disabled by default starting in firefox 51, since its design has been brought into ques...
...) { report(result.state); }); } the revoke() function has been disabled by default starting in firefox 51, since its design has been brought into question in the web applications security working group. it can be re-enabled by setting the preference dom.permissions.revoke.enable to true. responding to permission state changes you'll notice that there is an onchange event handler in the code above, attached to the permissionstatus object — this allows us to respond to any changes in the permission status for the api we are interested in. at the moment we are just reporting the change in state. conclusion and future work at the moment this doesn't offer much more than what we had already. if we choose to never share our location from the permission prompt (deny permission), then w...
RTCDataChannel: error event - Web APIs
or event is sent to an rtcdatachannel object's onerror error handler when an error occurs on the data channel. bubbles yes cancelable no interface rtcerrorevent event handler property onerror the rtcerrorevent object provides details about the error that occurred; see that article for details. ...
... bubbles yes cancelable no interface rtcerrorevent event handler property onerror the rtcerrorevent object provides details about the error that occurred; see that article for details. ...
... const err = ev.error; console.error("webrtc error: ", err.message); // handle specific error detail types switch(err.errordetail) { case "sdp-syntax-error": console.error(" sdp syntax error in line ", err.sdplinenumber); break; case "idp-load-failure": console.error(" identity provider load failure: http error ", err.httprequeststatuscode); break; case "sctp-failure": if (err.sctpcausecode < sctpcausecodes.length) { console.error(" sctp failure: ", err.sctpcausecode); } else { console.error(" unknown sctp error"); } break; case "dtls-failure": if (err.receivedalert) { console.error(" received dlts failure alert: ", err.receivedalert); } if (er...
... the source file's name, line number, and column number at which the error occurred. in addition, however, depending on the value of errordetail, additional information may be output. each error type has a different set of information output. for example, an sdp syntax error displays the line number of the error within the sdp, and an sctp error displays a message corresponding to the sctp cause code. other error types similarly output appropriate information. you can also set up an event handler for error events using the rtcdatachannel interface's onerror event handler property: dc.onerror = ev => { const err = ev.error; /* ... */ } note: since rtcerror is not one of the legacy errors, the value of rtcerror.code is always 0. specifications specification status com...
RTCError - Web APIs
Web › API › RTCError
es and returns a new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property. ...
...null if the error isn't an sctp error. ...
...null if the error isn't an sctp error. sdplinenumber read only if errordetail is sdp-syntax-error, this property is a long integer identifying the line number of the sdp on which the syntax error occurred. null if the error isn't an sdp syntax error. ...
...se { terminatemyconnection(); } }); if the error is an sdp syntax error—indicated by its errordetail property being sdp-syntax-error—, a message string is constructed to present the error message and the line number within the sdp at which the error occurred. this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use. any other error is treated as terminal, causing a terminatemyconnection() function to be called. the above example uses addeventlistener() to add the handler for error events. you can also use the rtcdatachannel object's onerror event handler property, like this: datachannel.onerror = (event) => { let error = event.error; /* and so forth */ }; specifications specifi...
RTCErrorEvent.error - Web APIs
the event is announcing. syntax let errorinfo = rtcerrorevent.error; value an rtcerror object whose properties provide details about the error which has occurred in the context of a webrtc operation. since rtcerror is based upon domexception, it includes those properties. ...
...null if the error isn't an sctp error. ...
...null if the error isn't an sctp error. sdplinenumber read only if errordetail is sdp-syntax-error, this property is a long integer identifying the line number of the sdp on which the syntax error occurred. null if the error isn't an sdp syntax error. ...
...se { terminatemyconnection(); } }); if the error is an sdp syntax error—indicated by its errordetail property being sdp-syntax-error—, a message string is constructed to present the error message and the line number within the sdp at which the error occurred. this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use. any other error is treated as terminal, causing a terminatemyconnection() function to be called. the above example uses addeventlistener() to add the handler for error events. you can also use the rtcdatachannel object's onerror event handler property, like this: datachannel.onerror = (event) => { let error = event.error; /* and so forth */ }; specifications specifi...
RTCPeerConnection.addStream() - Web APIs
he stream to add to the webrtc peer connection. return value none. example this simple example adds the audio and video stream coming from the user's camera to the connection. navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); stream.gettracks().foreach(function(track) { pc.addtrack(track, stream); }); }); the newer addtrack() api avoids confusion over whether later changes to the track-makeup of a stream affects a peer connection (they do not). the exception is in chr...
...ds confusion over whether later changes to the track-makeup of a stream affects a peer connection (they do not). the exception is in chrome, where addstream() does make the peer connection sensitive to later stream changes (though such changes do not fire the negotiationneeded event). if you are relying on the chrome behavior, note that other browsers do not have it. ...
...changes (though such changes do not fire the negotiationneeded event). if you are relying on the chrome behavior, note that other browsers do not have it. ...
...addtrack(track, stream); } else { // if you have code listening for negotiationneeded events: settimeout(() => pc.dispatchevent(new event('negotiationneeded'))); } // remove a track from a stream and the peer connection said stream was added to: stream.removetrack(track); if (pc.removetrack) { pc.removetrack(pc.getsenders().find(sender => sender.track == track)); } else { // if you have code listening for negotiationneeded events: settimeout(() => pc.dispatchevent(new event('negotiationneeded'))); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.addstream()' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.createAnswer() - Web APIs
the answer is delivered to the returned promise, and should then be sent to the source of the offer to continue the negotiation process. ...
...d then be sent to the source of the offer to continue the negotiation process. syntax apromise = rtcpeerconnection.createanswer([options]); rtcpeerconnection.createanswer(successcallback, failurecallback[, options]); parameters options optional an object which contains options which customize the answer; this is based on the rtcansweroptions dictionary. deprecated parameters in older code and documentation, you may see a callback-based version of this function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of createanswer() instead. the parameters for this form of createanswer() are described below, to aid in updating existing code. successcallback an rtcsessiondescriptioncallback which wil...
...entity provider wasn't able to provide an identity assertion. operationerror generation of the sdp failed for some reason; this is a general failure catch-all exception. return value a promise whose fulfillment handler is called with an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp answer to be delivered to the other peer. example here is a segment of code taken from the code that goes with the article signaling and video calling. this code comes from the handler for the message sent to carry an offer to another peer across the signaling channel. keep in mind that this is part of the signaling process, the transport layer for which is an implementation detail that's entirely up to you. in this case, a websocket connection is used to send a json m...
...te and return a new answer. in our promise handler, the returned answer is set as the description of the local end of the connection by calling setlocaldescription(). once that succeeds, the answer is sent to the signaling server using whatever protocol you see fit. promise.catch() is used to trap and handle errors. see handling the invitation in signaling and video calling to see the complete code, in context, from which this snippet is derived; that will help you understand the signaling process and how answers work. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'createanswer()' in that specification. candidate recommendation initial definition. ...
RTCRtpSender.setParameters() - Web APIs
ible. in other words, setparameters() updates the configuration of the rtp transmission as well as the encoding configuration for a specific media track on the webrtc connection. syntax var promise = rtcrtpsender.setparameters(parameters) parameters parameters an object conforming with the rtcrtpsendparameters dictionary, specifying options for the rtcrtpsender; these include potential codecs that could be use for encoding the sender's track. the available options are: degradationpreference specifies the preferred way the webrtc layer should handle optimizing bandwidth against quality in constrained-bandwidth situations; the value comes from the rtcdegradationpreference enumerated string type, and the default is balanced. encodings an array of rtcrtpencodingparameters object...
...track. the available options are: degradationpreference specifies the preferred way the webrtc layer should handle optimizing bandwidth against quality in constrained-bandwidth situations; the value comes from the rtcdegradationpreference enumerated string type, and the default is balanced. encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media. priority a string from the rtcprioritytype enumerated type which indicates the encoding's priority. the default value is low. transactionid a string containing a unique id for the last set of parameters applied; this value is used to ensure that setparameters() can only be called to alter changes made by a specific previous call to getparameter...
...he order of the specified encodings has changed from the current list's order. an attempt has been made to alter a property that cannot be changed after the sender is first created. invalidstateerror the transceiver of which the rtcrtpsender is a part is not running, or has no parameters to set. operationerror any error condition which occurs that isn't covered by one of the other error codes results in an operationerror. rangeerror the value specified for scaleresolutiondownby is less than 1.0, which would result in scaling up rather than down, which is not allowed; or one or more of the specified encodings' maxframerate values is less than 0.0. in addition, if a webrtc error occurs while configuring or accessing the media, an rtcerror is thrown with its errordetail set to hardw...
...lts in an operationerror. rangeerror the value specified for scaleresolutiondownby is less than 1.0, which would result in scaling up rather than down, which is not allowed; or one or more of the specified encodings' maxframerate values is less than 0.0. in addition, if a webrtc error occurs while configuring or accessing the media, an rtcerror is thrown with its errordetail set to hardware-encoder-error. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.setparameters()' in that specification. candidate recommendation initial definition. ...
RTCRtpStreamStats - Web APIs
ed rtcrtpstreamstats until a specification update in the spring of 2017. check the browser compatibility table to know if and when the name change was implemented in specific browsers. properties the rtcrtpstreamstats dictionary is based on rtcstats, and inherits its properties. in addition, some or all of the following properties are available. standard fields included for all media types codecid a domstring which uniquely identifies the object which was inspected to produce the rtccodecstats object associated with this rtp stream. kind a domstring whose value is "audio" if the associated mediastreamtrack is audio-only or "video" if the track contains video. this value will match that of the media type indicated by rtccodecstats.codec, as well as the track's kind property. previousl...
...umber of times the receiver notified the sender that one or more rtp packets has been lost by sending a negative acknowledgement (nack, also called "generic nack") packet to the sender. this value is only available to the receiver. plicount the number of times the receiving end of the stream sent a picture loss indiciation (pli) packet to the sender, indicating that it has lost some amount of encoded video data for one or more frames. only the receiver has this value, and it's only valid for video tracks. qpsum the sum of the quantization parameter (qp) values associated with every frame received to date on the video track described by this rtcrtpstreamstats object. in general, the higher this number is, the more heavily compressed the video track was. combined with rtcreceivedrtpstreamsta...
...a for one or more frames. only the receiver has this value, and it's only valid for video tracks. qpsum the sum of the quantization parameter (qp) values associated with every frame received to date on the video track described by this rtcrtpstreamstats object. in general, the higher this number is, the more heavily compressed the video track was. combined with rtcreceivedrtpstreamstats.framesdecoded or rtcsentrtpstreamstats.framesencoded, you can approximate the average qp over those frames, keeping in mind that codecs often vary the quantizer values even within frames. also keep in mind that the values of qp can vary from codec to codec, so this value is only potentially useful when compared against the same codec. slicount the number of times the receiver notified the sender that one or...
...oded, you can approximate the average qp over those frames, keeping in mind that codecs often vary the quantizer values even within frames. also keep in mind that the values of qp can vary from codec to codec, so this value is only potentially useful when compared against the same codec. slicount the number of times the receiver notified the sender that one or more consecutive (in scan order) encoded video macroblocks have been lost or corrupted; this notification is sent by the receiver to the sender using a slice loss indication (sli) packet. this is a fairly technical part of how codecs work and while the higher this value is, the more errors occurred in the stream, generally most of the time this value is only interesting to very intensively hardcore media developers. specifications ...
ReadableStream.cancel() - Web APIs
stream — the job is finished so it is no longer needed. ...
... is finished so it is no longer needed. ...
... if (matchfoundat === -1) { matchfoundat = (caseinsensitive ? buffer.tolowercase() : buffer).indexof(tomatch); } if (matchfoundat === -1) { buffer = buffer.slice(-buffersize); } else if (buffer.slice(matchfoundat + tomatch.length).length >= contextafter) { console.log...
... if (matchfoundat === -1) { matchfoundat = (caseinsensitive ? buffer.tolowercase() : buffer).indexof(tomatch); } if (matchfoundat === -1) { buffer = buffer.slice(-buffersize); } else if (buffer.slice(matchfoundat + tomatch.length).length >= contextafter) { console.log("here's...
Using the Resource Timing API - Web APIs
r properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document shows the use of resource timing interfaces. for more details about the interfaces, including examples, see each interface's reference page and the references in the see also section. a live version of the examples is available on github, as is the source code. pull requests and bug reports are welcome. resource loading phases an application can get timestamps for the various phases of resource loading such as redirection, dns lookup, and tcp connection setup. those phases and their property names are illustrated in figure 1. figure 1. resource timing properties an application developer can use the property values to calculate the length of time a...
...ct an application's performance so getting accurate data on resource size can be important (especially for non-hosted resources). the performanceresourcetiming interface has three properties that can be used to obtain size data about a resource. the transfersize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. the encodedbodysize property returns the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. decodedbodysize returns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. the following example demonstrates using these three properties. function display_size_data()...
... var list = performance.getentriesbytype("resource"); if (list === undefined) { console.log("= display size data: performance.getentriesbytype() is not supported"); return; } // for each "resource", display its *size property values console.log("= display size data"); for (var i=0; i < list.length; i++) { console.log("== resource[" + i + "] - " + list[i].name); if ("decodedbodysize" in list[i]) console.log("... decodedbodysize[" + i + "] = " + list[i].decodedbodysize); else console.log("... decodedbodysize[" + i + "] = not supported"); if ("encodedbodysize" in list[i]) console.log("... encodedbodysize[" + i + "] = " + list[i].encodedbodysize); else console.log("... encodedbodysize[" + i + "] = not supported"); if ("transfer...
...ze() = supported"); performance.setresourcetimingbuffersize(n); } else { console.log("... performance.setresourcetimingbuffersize() = not supported"); } } the performance interface has a onresourcetimingbufferfull event handler that gets called (with an event of type event.type of "resourcetimingbufferfull") when the browser's resource performance entry buffer is full. the following code example sets a onresourcetimingbufferfull event callback in the init() function. function buffer_full(event) { console.log("warning: resource timing buffer is full!"); set_resource_timing_buffer_size(200); } function init() { // load some image to trigger "resource" fetch events var image1 = new image(); image1.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; var...
SVGAngle - Web APIs
Web › API › SVGAngle
pe_grad an <angle> with a grad unit. properties unittype the type of the value as specified by one of the svg_angletype_* constants defined on this interface. value the value as a floating point value, in user units. setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automatically to reflect this setting. ...
... valueasstring the value as a domstring value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. ...
...e no_modification_allowed_err is raised when the length corresponds to a read-only attribute, or when the object itself is read-only. valueasstring the value as a domstring value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <angle>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read-only attribute, or when the object itself is read-only. methods newvaluespecifiedunits reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on th...
...cannot be parsed as a valid <angle>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read-only attribute, or when the object itself is read-only. methods newvaluespecifiedunits reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_angletype_unknown or not a valid unit type constant (one of the other svg_angletype_* constants defined on this interface). a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. converttospecifiedunits preserve the same underlying stored value, bu...
SVGLength - Web APIs
Web › API › SVGLength
unittype unsigned short the type of the value as specified by one of the svg_lengthtype_* constants defined on this interface. value float the value as a floating point value, in user units. setting this attribute will cause valueinspecifiedunits and valueasstring to be updated automatically to reflect this setting. exceptions on setting: a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. valueinspecifiedunits float the value as a floating point value, in the units expressed by unittype. setting this attribute will cause value and valueasstring to be updated automatically to reflect this setting. exceptions on setting: a do...
..._allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. valueinspecifiedunits float the value as a floating point value, in the units expressed by unittype. setting this attribute will cause value and valueasstring to be updated automatically to reflect this setting. exceptions on setting: a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. valueasstring domstring the value as a string value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on settin...
...ised when the length corresponds to a read only attribute or when the object itself is read only. valueasstring domstring the value as a string value, in the units expressed by unittype. setting this attribute will cause value, valueinspecifiedunits, and unittype to be updated automatically to reflect this setting. exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <length>. a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. methods name & arguments return description newvaluespecifiedunits(in unsigned short unittype, in float valuein...
...when the object itself is read only. methods name & arguments return description newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object. exceptions: a domexception with code not_supported_err is raised if unittype is svg_lengthtype_unknown or not a valid unit type constant (one of the other svg_lengthtype_* constants defined on this interface). a domexception with code no_modification_allowed_err is raised when the length corresponds to a read only attribute or when the object itself is read only. converttospecifiedunits(in unsigned short unitt...
Using the Screen Capture API - Web APIs
ns a promise that resolves to a stream containing the live screen contents. starting screen capture: async/await style async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below. starting screen capture: promise style function startcapture(displaymediaoptions) { let capturestream = null; return navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.error("error:" + err); return null; }); } either way, the user ...
...cally. authorizing capture of display contents before streaming of captured screen contents can begin, the user agent will ask the user to confirm the sharing request, and to select the content to share. examples simple screen capture in this example, the contents of the captured screen area are simply streamed into a <video> element on the same page. javascript there isn't all that much code needed in order to make this work, and if you're familiar with using getusermedia() to capture video from a camera, you'll find getdisplaymedia() to be very familiar. setup first, some constants are set up to reference the elements on the page to which we'll need access: the <video> into which the captured screen contents will be streamed, a box into which logged output will be drawn, and the s...
...r.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, which will stream the contents of the screen, window, or other region selected by the user. the stream is connected to the <video> element by storing the returned mediastream into the element's srcobject. the dumpoptionsinfo() function—which we will look at...
...xample, this line in the http headers will enable screen capture api for the document and any embedded <iframe> elements that are loaded from the same origin: feature-policy: display-capture 'self' if you're performing screen capture within an <iframe>, you can request permission just for that frame, which is clearly more secure than requesting a more general permission: <iframe src="https://mycode.example.net/etc" allow="display-capture"> </iframe> ...
Screen Wake Lock API - Web APIs
ng off, dimming or locking. it allows for a simple platform based solution which up until now could only be achieved via workarounds which were potentially power hungry. only visible (active) documents can acquire the screen wake lock. there are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a qr/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). you acquire a wakelocksentinel object by calling the navigator.wakelock.request() promise based method that resolves if the platform allows it. a request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the d...
... dimming or locking when an application needs to keep running. wakelocksentinel provides a handle to the underlying platform wake lock and if referenced can be manually released and reacquired. get an instance of the object by calling wakelock.request. navigator.wakelock returns a wakelock object instance, from which all other functionality can be accessed. examples feature detection this code checks for wake lock support and updates the ui accordingly. if ('wakelock' in navigator) { issupported = true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled = true; statuselem.textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object. the ...
...e() .then(() => { wakelock = null; }); listening for wake lock release this example updates the ui if the wake lock has been released for any reason (such as navigating away from the active window/tab). wakelock.addeventlistener('release', () => { // the wake lock has been released statuselem.textcontent = 'wake lock has been released'; }); reacquiring a wake lock the following code reacquires the wake lock should the visibility of the document change and the wake lock is released. document.addeventlistener('visibilitychange', () => { if (wakelock !== null && document.visibilitystate === 'visible') { wakelock = await navigator.wakelock.request('screen'); } }); putting it all together you can find the complete code on github here. the demo uses a button to acquire ...
...s the ui. the ui also updates if the wake lock is released automatically for any reason. there's a checkbox which when checked, will automatically reacquire the wake lock if the document's visibility state changes and becomes visible again. performance considerations release the screen wake lock when user ends activity that required always-on screen. for example, a ticketing app which uses qr codes to transmit ticket information, might acquire screen wake lock when the qr code is displayed (so that code is successfully scanned) but release afterwards. a presentation app might hold the lock only while a presentation is active, but not when presentation is being edited. if your app is performing long-running downloads, consider using background fetch. if you app is synchronizing data from ...
ServiceWorkerContainer.register() - Web APIs
cript is located. see the examples section for more information on how it works. return value a promise that resolves with a serviceworkerregistration object. examples the examples described here should be taken together to get a better understanding of how service workers scope applies to a page. the following example uses the default value of scope (by omitting it). the service worker code in this case, if included in example.com/index.html, will control example.com/index.html, as well as pages underneath it, like example.com/product/description.html. if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope. navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worke...
...ce worker hosted at the root of the // site using the default scope. ...
...*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } the following code, if included in example.com/index.html, at the root of a site, would apply to exactly the same pages as the example above. remember the scope, when included, uses the page's location as its base. alternatively, if this code were included in a page at example.com/product/description.html, with the javascript file residing at example.com/product/sw.js, then the service worker would only apply to resources under example.com/product. if ('serviceworker' in navigator) { // declaring scope manually navigator.serviceworker.register('/sw.js', {scope: './'}).then(function(registration) { console.log('service worker ...
...tch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } there is frequent confusion surrounding the meaning and use of scope. since a service worker can't have a scope broader than its own location, only use the scope option when you need a scope that is narrower than the default. the following code, if included in example.com/index.html, at the root of a site, would only apply to resources under example.com/product. if ('serviceworker' in navigator) { // declaring scope manually navigator.serviceworker.register('/sw.js', {scope: '/product/'}).then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { conso...
Streams API concepts - Web APIs
...
...l readable stream there is a type called a byte stream — this is an extended version of a conventional stream for reading underlying byte sources (otherwise known as byob, or “bring your own buffer”) sources. these allow streams to be read straight into a buffer supplied by the developer, minimizing the copying required. which underlying stream (and by extension, reader and controller) your code will use depends on how the stream was created in the first place (see the readablestream() constructor page). important: byte streams are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. this may change over time. you can make use of ready-made readable streams via mechanisms like a respo...
...le stream is a destination into which you can write data, represented in javascript by a writablestream object. this serves as an abstraction over the top of an underlying sink — a lower-level i/o sink into which raw data is written. the data is written to the stream via a writer, one chunk at a time. a chunk can take a multitude of forms, just like the chunks in a reader. you can use whatever code you like to produce the chunks ready for writing; the writer plus the associated code is called a producer. when a writer is created and starts writing to a stream (an active writer), it is said to be locked to it. only one writer can write to a writable stream at one time. if you want another writer to start writing to your stream, you typically need to abort it before you then attach another w...
...ough() — pipes the stream through a transform stream, which is a pair comprised of a writable stream that has data written to it, and a readable stream that then has the data read out of it — this acts as a kind of treadmill that constantly takes data in and transforms it to a new state. effectively the same stream is written to, and then the same values are read. a simple example is a text decoder, where raw bytes are written, and then strings are read. you can find more useful ideas and examples in the spec — see transform streams for ideas, and this web sockets example. readablestream.pipeto() — pipes to a writable stream that acts as the end point of the pipe chain. the start of the pipe chain is called the original source, and the end is called the ultimate sink. note: this...
Using readable streams - Web APIs
consume fetch body objects as streams and create your own custom readable streams in firefox 65+ and chrome 42+ (and equivalent chromium-based browsers). pipe chains are only supported in chrome at the moment, and that functionality is subject to change. finding some examples we will look at various examples in this article, taken from our dom-examples/streams repo. you can find the full source code there, as well as links to the examples. consuming a fetch as a stream the fetch api allows you to fetch resources across the network, providing a modern alternative to xhr. it has a number of advantages, and what is really nice about it is that browsers have recently added the ability to consume a fetch response as a readable stream. the body mixin now includes the body property, which is a s...
...l, and allows you to specify a custom queuing strategy to use for your stream. you’ll rarely have to do this, so we’ll just concentrate on the first one for now. the first object can contain up to five members, only the first of which is required: start(controller) — a method that is called once, immediately after the readablestream is constructed. inside this method, you should include code that sets up the stream functionality, e.g. beginning generation of data or otherwise getting access to the source. pull(controller) — a method that, when included, is called repeatedly until the stream’s internal queue is full. this can be used to control the stream as more chunks are enqueued. cancel() — a method that, when included, will be called if the app signals that the stream is ...
...s necessary to release access to the stream source. type and autoallocatechunksize — these are used — when included — to signify that the stream is to be a bytestream. bytestreams will be covered separately in a future tutorial, as they are somewhat different in purpose and use case to regular (default) streams. they are also not implemented anywhere as yet. looking at our simple example code again, you can see that our readablestream() constructor only includes a single method — start(), which serves to read all the data out of our fetch stream. return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if ...
...der to it. as an example, have a look at our simple random stream demo (see it live also), which creates a custom stream, enqueues some random strings into it, and then reads the data out of the stream again once the stop string generation button is pressed. note: in order to consume a stream using fetchevent.respondwith(), the enqueued stream contents must be of type uint8array; for example, encoded using textencoder. the custom stream constructor has a start() method that uses a windowtimers.setinterval() call to generate a random string every second. readablestreamdefaultcontroller.enqueue() is then used to enqueue it into the stream. when the button is pressed, the interval is cancelled, and a function called readstream() is invoked to read the data back out of the stream again. we als...
SubtleCrypto.deriveKey() - Web APIs
es it harder for an attacker to use brute-force to discover the key using a dictionary attack. pbkdf2 is specified in rfc 2898. examples note: you can try the working examples on github. ecdh in this example alice and bob each generate an ecdh key pair, then exchange public keys. they then use derivekey() to derive a shared aes key, that they could use to encrypt messages. see the complete code on github. /* derive an aes key, given: - our ecdh private key - their ecdh public key */ function derivesecretkey(privatekey, publickey) { return window.crypto.subtle.derivekey( { name: "ecdh", public: publickey }, privatekey, { name: "aes-gcm", length: 256 }, false, ["encrypt", "decrypt"] ); } async function agreesharedsecretkey() { //...
...ypt(alicessecretkey); }); // bob can use his copy to decrypt the message. let decryptbutton = document.queryselector(".ecdh .decrypt-button"); decryptbutton.addeventlistener("click", () => { decrypt(bobssecretkey); }); } pbkdf2 in this example we ask the user for a password, then use it to derive an aes key using pbkdf2, then use the aes key to encrypt a message. ...
... in this example we ask the user for a password, then use it to derive an aes key using pbkdf2, then use the aes key to encrypt a message. see the complete code on github. /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. ...
...an aes key using pbkdf2, then use the aes key to encrypt a message. see the complete code on github. /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. ...
SubtleCrypto.unwrapKey() - Web APIs
using the aes-kw algorithm, with a key derived from a password. to unwrap, we ask the user for the password and use pbkdf2 and some salt to derive the aes-kw unwrapping key. the salt needs to be the same as the salt that was used to derive the original aes-kw key wrapping key. once we have the unwrapping key we pass it into unwrapkey() with the wrapped key and other parameters. see the complete code on github. /* salt that is to be used in derivation of the key-wrapping key, alongside the password the user supplies. this must match the salt value that was originally used to derive the key. */ const saltbytes = [89,113,135,234,168,204,21,36,55,93,1,132,242,242,192,156]; /* the wrapped key itself. */ const wrappedkeybytes = [171,223,14,36,201,233,233,120,164,68,217,192,226,80, 224,39,199...
... const bytesasarraybuffer = new arraybuffer(bytes.length); const bytesuint8 = new uint8array(bytesasarraybuffer); bytesuint8.set(bytes); return bytesasarraybuffer; } /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. */ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-kw key using pbkdf2. */ async function getunwrappingkey() { // 1. get the key material (user-supplied password) const keymaterial = await getkeymaterial(); // 2 initialize the salt parameter. // the salt must match the ...
... key. the salt needs to be the same as the salt that was used to derive the original aes-gcm key wrapping key. once we have the unwrapping key we pass it into unwrapkey() with the wrapped key and other parameters. note that when using aes-gcm we have to pass the iv value into unwrapkey(), and this must be the same as the iv that was used in the corresponding wrapkey() operation. see the complete code on github. /* salt that is to be used in derivation of the key-wrapping key, alongside the password the user supplies. this must match the salt value that was originally used to derive the key. */ const saltbytes = [180,253,62,216,47,35,90,55,218,233,103,10,172,143,161,177]; /* iv that is to be used in decrypting the key to unwrap. this must the the same iv that was originally used to encrypt t...
... const bytesasarraybuffer = new arraybuffer(bytes.length); const bytesuint8 = new uint8array(bytesasarraybuffer); bytesuint8.set(bytes); return bytesasarraybuffer; } /* get some key material to use as input to the derivekey method. the key material is a password supplied by the user. */ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-gcm key using pbkdf2. */ async function getunwrappingkey() { // 1. get the key material (user-supplied password) const keymaterial = await getkeymaterial(); // 2 initialize the salt parameter. // the salt must match the...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
e index to gl.vertexattribpointer(). alternatively, you use the index that is assigned by the graphics card when compiling the vertex shader. depending on the graphics card, the index will vary, so you must call gl.getattriblocation() to find out the index, and then provide this index to gl.vertexattribpointer(). ...
...instead, we can supply a default value that will be identical for all vertices. ...
...instead, we can supply a default value that will be identical for all vertices. ...
...gl.getvertexattrib() and gl.getvertexattriboffset() to get the current parameters for an attribute, e.g. the data type or whether the attribute should be normalized. keep in mind that these webgl functions have a slow performance and it is better to store the state inside your javascript application. however, these functions are great for debugging a webgl context without touching the application code. examples this example shows how to send your vertex attributes to the shader program. we use an imaginary data structure where the attributes of each vertex are stored interleaved with a length of 20 bytes per vertex: position: we need to store the x, y and z coordinates. for highest precision, we use 32-bit floats; in total this uses 12 bytes. normal vector: we need to store the x, y and ...
Creating 3D objects using WebGL - Web APIs
ces, and not just 8, it is because each corner belongs to three faces of different colors, and a single vertex needs to have a single specific color; therefore we will create three copies of each vertex in three different colors, one for each face. 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>. define the positions of the cube's vertices first, let's build the cube's vertex position buffer by updating the code in initbuffers(). this is pretty much the same as it was for the square plane, but somewhat longer since there are 24 vertices (4 per side): const positions = [ // front face -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, ...
...exposition attribute { const numcomponents = 3; ... gl.vertexattribpointer( programinfo.attriblocations.vertexposition, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexposition); } define the vertices' colors we also need to build an array of colors for each of the 24 vertices. this code starts by defining a color for each face, then uses a loop to assemble an array of all the colors for each of the vertices. const facecolors = [ [1.0, 1.0, 1.0, 1.0], // front face: white [1.0, 0.0, 0.0, 1.0], // back face: red [0.0, 1.0, 0.0, 1.0], // top face: green [0.0, 0.0, 1.0, 1.0], // bottom face: blue [1.0, 1.0, 0.0, 1.0], // right fac...
..._buffer, new uint16array(indices), gl.static_draw); return { position: positionbuffer, color: colorbuffer, indices: indexbuffer, }; } the indices array defines each face like a pair of triangles, specifying each triangle's vertices as an index into the cube's vertex arrays. thus the cube is described as a collection of 12 triangles. drawing the cube next we need to add code to our drawscene() function to draw using the cube's index buffer, adding new gl.bindbuffer() and gl.drawelements() calls: // tell webgl which indices to use to index the vertices gl.bindbuffer(gl.element_array_buffer, buffers.indices); ... { const vertexcount = 36; const type = gl.unsigned_short; const offset = 0; gl.drawelements(gl.triangles, vertexcount, type, offset)...
...tices per side, or 36 total vertices in the cube, even though many of them are duplicates. finally, let's replace our variable squarerotation by cuberotation and add a second rotation around the x axis: mat4.rotate(modelviewmatrix, modelviewmatrix, cuberotation * .7, [0, 1, 0]); at this point, we now have an animated cube rotating, its six faces rather vividly colored. view the complete code | open this demo on a new page « previousnext » ...
Getting started with WebGL - Web APIs
next » webgl enables web content to use an api based on opengl es 2.0 to perform 2d and 3d rendering in an html canvas in browsers that support it without the use of plug-ins. webgl programs consist of control code written in javascript and shader code (glsl) 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 article will introduce you to the basics of using webgl. it's assumed that you already have an understanding of the mathematics involved in 3d graphics, and this article doesn't pretend to try to teach you 3d graphics concepts itself. the code examples in this tutorial can also be found in the webgl-examples github repository. it's wo...
... it easier to build 3d applications and games, such as three.js and babylon.js. preparing to render in 3d the first thing you need in order to use webgl for rendering is a canvas. the html fragment below declares a canvas that our sample will draw into. <body> <canvas id="glcanvas" width="640" height="480"></canvas> </body> preparing the webgl context the main() function in our javascript code, is called when our script is loaded. its purpose is to set up the webgl context and start rendering content. // // start here // function main() { const canvas = document.queryselector("#glcanvas"); // 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 brows...
...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. ...
...ccessfully 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). ...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
he simplest things you can do is to implement a "hold" feature, wherein a participant in a call can click a button and turn off their microphone, begin sending music to the other peer instead, and stop accepting incoming audio. note: this example makes use of modern javascript features including async functions and the await expression. this enormously simplifies and makes far more readable the code dealing with the promises returned by webrtc methods. in the examples below, we'll refer to the peer which is turning "hold" mode on and off as the local peer and the user being placed on hold as the remote peer. activating hold mode local peer when the local user decides to enable hold mode, the enablehold() method below is called. it accepts as input a mediastream containing the audio t...
...is called. it accepts as input a mediastream containing the audio to play while the call is on hold. ...
... the audiostream, containing the audio to play instead of the local peer's microphone audio, can come from anywhere. ...
...dio transceiver's rtcrtpsender's track is replaced with the specified stream's first audio track. the transceiver's incoming audio track is re-enabled. the audio transceiver's direction is set to "sendrecv", indicating that it should return to both sending and receiving streamed audio, instead of only sending. just like when hold was engaged, this triggers negotiation again, resulting in your code sending a new offer to the remote peer. remote peer when the "sendrecv" offer is received by the remote peer, it calls its holdended() method: async function holdended(offer, micstream) { try { await peerconnection.setremotedescription(offer); await audiotransceiver.sender.replacetrack(micstream.getaudiotracks()[0]); audiotransceiver.direction = "sendrecv"; await sendanswer(...
Lifetime of a WebRTC session - Web APIs
g the connection all the way through closing the connection when it's no longer needed. this article doesn't get into details of the actual apis involved in establishing and handling a webrtc connection; it simply reviews the process in general with some information about why each step is required. see signaling and video calling for an actual example with a step-by-step explanation of what the code does. this page is currently under construction, and some of the content will move to other pages as the webrtc guide material is built out. pardon our dust! establishing the connection the internet is big. really big. it’s so big that years ago, smart people saw how big it was, how fast it was growing, and the limitations of the 32-bit ip addressing system, and realized that something had...
... by labeling it “michelle” and dropping it in a mailbox when you don't know her address. you need to look up her address and include it on the package, or she'll wind up wondering why you forgot her birthday again. this is where signaling comes in. signaling signaling is the process of sending control information between two devices to determine the communication protocols, channels, media codecs and formats, and method of data transfer, as well as any required routing information. the most important thing to know about the signaling process for webrtc: it is not defined in the specification. why, you may wonder, is something fundamental to the process of establishing a webrtc connection left out of the specification? the answer is simple: since the two devices have no way to directly ...
...changed during signaling there are three basic types of information that need to be exchanged during signaling: control messages used to set up, open, and close the communication channel, and to handle errors. information needed in order to set up the connection: the ip addressing and port information needed for the peers to be able to talk to one another. media capability negotiation: what codecs and media data formats can the peers understand? these need to be agreed upon before the webrtc session can begin. only once signaling has been successfully completed can the true process of opening the webrtc peer connection begin. it's worth noting that the signaling server does not actually need to understand or do anything with the data being exchanged through it by the two peers during ...
... it possible to begin a webrtc session: each peer creates an rtcpeerconnection object representing their end of the webrtc session. each peer establishes a handler for icecandidate events, which handles sending those candidates to the other peer over the signaling channel. each peer establishes a handler for track event, which is received when the remote peer adds a track to the stream. this code should connect the tracks to its consumer, such as a <video> element. the caller creates and shares with the receiving peer a unique identifier or token of some kind so that the call between them can be identified by the code on the signaling server. the exact contents and form of this identifier is up to you. each peer connects to an agreed-upon signaling server, such as a websocket server the...
WebRTC API - Web APIs
party software. webrtc consists of several interrelated apis and protocols which work together to achieve this. the documentation you'll find here will help you understand the fundamentals of webrtc, how to set up and use both data and media connections, and more. interoperability because implementations of webrtc are still evolving, and because each browser has different levels of support for codecs and webrtc features, you should strongly consider making use of the adapter.js library provided by google before you begin to write your code. adapter.js uses shims and polyfills to smooth over the differences among the webrtc implementations across the environments supporting it. adapter.js also handles prefixes and other naming differences to make the entire webrtc development process easier...
...iation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two. signaling and two-way video calling a tutorial and example which turns a websocket-based chat system created for a previous example and adds support for opening video calls among participants. the chat server's websocket connection is used for webrtc signaling. codecs used by webrtc a guide to the codecs which webrtc requires browsers to support as well as the optional ones supported by various popular browsers. included is a guide to help you choose the best codecs for your needs. using webrtc data channels this guide covers how you can use a peer connection and an associated rtcdatachannel to exchange arbitrary data between two peers. using dtmf with w...
...ink to old-school telephone systems includes support for sending dtmf tones using the rtcdtmfsender interface. this guide shows how to do so. tutorials improving compatibility using webrtc adapter.js the webrtc organization provides on github the webrtc adapter to work around compatibility issues in different browsers' webrtc implementations. the adapter is a javascript shim which lets your code to be written to the specification so that it will "just work" in all browsers with webrtc support. taking still photos with webrtc this article shows how to use webrtc to access the camera on a computer or mobile phone with webrtc support and take a photo with it. a simple rtcdatachannel sample the rtcdatachannel interface is a feature which lets you open a channel between two peers over whi...
... sample the rtcdatachannel interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. the api is intentionally similar to the websocket api, so that the same programming model can be used for each. ...
WebXR permissions and security - Web APIs
presentation of vr first, any requests to activate the immersive-vr mode are rejected if the domain issuing the request does not have permission to enable an immersive session. this permission comes from the xr-spatial-tracking feature policy. once that check is passed, the request to enter immersive-vr mode is allowed if all of the following are true: the requestsession() call was issued by code executing within the handler for a user event, or the from the startup code for a user-launched web application. the document is considered trustworthy, in that it is responsible and is both currently active and has focus. the user's intent to enter immersive vr mode is well understood; see user intent below for details. if all of that is true, the promise returned by requestsession() is reso...
...ct is passed into the fulfillment handler. otherwise, an appropriate exception is thrown, such as securityerror if the document doesn't have permission to enter immersive mode. inline presentation when you request an xrsession with the mode set to inline, and any features are required or requested, the browser will only allow the session to be created if the call to requestsession() was made by code which is executing expressly due to user intent. specifically: if the requestsession() call isn't coming from within the handler executed in response to a user event, and is not being issued while launching a web application, the request is denied and false is delivered to the promise's fulfillment handler. if the document making the request isn't the one which is responsible for the script,...
...r's intent to open an inline xr presentation is not well understood, the request is denied. understanding of the user's intent may be either implicit or explicit. note: additional requirements may be put into effect due to the specific features requested by the options object when calling requestsession(). user intent user intent is the concept of whether or not an action being performed by code is being performed because of something the user intends to do or not. there are two kinds of user intent: implicit and explicit. explicit user intent (explicit user consent) is granted when the user has specifically and expressly been asked for permission to perform an action. implicit user intent (implicit user consent) is assumed if either of the following scenarios is the case: the user ...
...n to perform an action. implicit user intent (implicit user consent) is assumed if either of the following scenarios is the case: the user has interacted with the document in some way which has in turn caused your request to occur. for example, if you have an "enter xr mode" button, and the user clicks it, calling requestsession() from the button's click event handler will permitted. if your code is executing during the launch of a web application, the runtime may consider the act of launching your web application to qualify as user intent. ...
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
you may need to set the user's position within the 3d world. you can do that using getoffsetreferencespace(). xrsession.requestreferencespace("local") .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(startposition, {x:0, y:0, z:1.0, w: 1.0})); xrsession.requestanimationframe(drawframe); }); in this code, we obtain a local reference space, then use getoffsetreferencespace() to create a new space whose origin is adjusted to a position given by startposition and whose orientation is looking directly along the z azis. then the first animation frame is requested using xrsession's requestanimationframe(). implementing rotation based on non-xr inputs the input controls supported directly by webxr are...
...rst animation frame is requested using xrsession's requestanimationframe(). implementing rotation based on non-xr inputs the input controls supported directly by webxr are all dedicated vr or ar input devices. in order to use mouse, keyboard, or other input devices to move or otherwise transform objects in the 3d space—or to allow the user to move through the space—you'll need to write some code to read the inputs and move perform the movements. this is another good use case for getoffsetreferencespace(). in this example, we'll show code that lets the user look around by right-clicking and moving the mouse to change the viewing angle. first, we add an event handler for mousemove events, which calls our code to perform the rotation if the right mouse button is down. note also that we se...
...itch and mouseyaw. let mouseyaw = 0.0; let mousepitch = 0.0; const inverseorientation = quat.create(); const mouse_speed = 0.003; function rotateviewby(dx, dy) { mouseyaw += dx * mouse_speed; mousepitch += dy * mouse_speed; if (mousepitch < -math.pi * 0.5) { mousepitch = -math.pi * 0.5; } else if (mousepitch > math.pi * 0.5) { mousepitch = math.pi * 0.5; } } finally, we need code that actually applies the computed yaw and pitch to the viewer's orientation. this function, applymousemovement(), handles that: function applymousemovement(refspace) { if (!mouseyaw && !mousepitch) { return refspace; } quat.identity(inverseorientation); quat.rotatex(inverseorientation, inverseorientation, -mousepitch); quat.rotatey(inverseorientation, inverseorientation, -mouseya...
...this new reference space is one in which the viewer's position is unchanged, but their orientation has been altered based on the pitch and yaw values generated from the accumulated mouse inputs. applymousemovement() should be called when drawing a frame, immediately before fetching the viewer's pose using getviewerpose(), and the rendering should be performed in this reference space. you can see code similar to this in use in our broader webxr tutorial article called movement, orientation, and motion. in particular, check out the section called starting the webxr session. specifications specification status comment webxr device apithe definition of 'getoffsetreferencespace()' in that specification. working draft initial definition. ...
ARIA: textbox role - Accessibility
ine input, in which return or enter submits the form; in this case, it is preferable to use an html <input> with type="text". to create a multi-line text box which supports line breaks, as in an html <textarea>, set aria-multiline="true". including the html contenteditable attribute ensures the text node is editable. ...
...e to use an html <input> with type="text". to create a multi-line text box which supports line breaks, as in an html <textarea>, set aria-multiline="true". including the html contenteditable attribute ensures the text node is editable. <!-- simple text input field --> <div id="txtboxlabel">enter your five-digit zipcode</div> <div role="textbox" contenteditable="true" aria-placeholder="5-digit zipcode" aria-labelledby="txtboxlabel"></div> <!-- multi-line text area --> <div id="txtboxmultilinelabel">enter the tags for the article</div> <div role="textbox" contenteditable="true" aria-multiline="true" aria-labelledby="txtboxmultilinelabel" aria-required="true"></div> semantic elements are more concise and require no javascript to support textbox features. <label for="txtbox">enter your f...
...edby="txtboxlabel"></div> <!-- multi-line text area --> <div id="txtboxmultilinelabel">enter the tags for the article</div> <div role="textbox" contenteditable="true" aria-multiline="true" aria-labelledby="txtboxmultilinelabel" aria-required="true"></div> semantic elements are more concise and require no javascript to support textbox features. <label for="txtbox">enter your five-digit zipcode</label> <input type="text" placeholder="5-digit zipcode" id="txtbox"/> <!-- multi-line text area --> <label for="txtboxmultiline">enter the tags for the article</label> <textarea id="txtboxmultiline" required></textarea> where a text field is read-only, indicated this by setting aria-readonly="true" on the element. associated aria properties aria-activedescendent attribute taking as ...
...s label and role when focus first lands on a textbox. if it also contains content, this should be announced as with a regular textbox. screen magnifiers may enlarge the textbox. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: adding the role in the html code for single line input the snippet below shows how the textbox role is added directly into the html source code. <div role="textbox" contenteditable="true"></div> example 2: adding the role in the html code for multi-line input the snippet below shows how the textbox role is added directly into the html source code. <div role="textbox" contenteditable="true" aria-multiline="true"></div> best...
Architecture - Accessibility
y just another text container with more embedded objects. however in accessibility hierarchies such as atk and iaccessible2, text is not exposed in leaf nodes as it is in a w3c dom. the text is actually exposed via a special text interface in the parent of the text nodes. it is concatenated together with all its sibling text nodes, and embedded objects between the text nodes are exposed as the unicoded embedded object character '\xfffc'. one reason for this is that there are fewer nodes to pass across process, and that improves performance. node types text content (role_text) objects are implemented by nstextaccessible. their text is actually exposed in their parent nshypertextaccessible via nsiaccessibletext. when the hierarchy is finally exposed to atk they are stripped out. they are in t...
...ible. when the hierarchy is finally exposed to atk they are stripped out as leaf nodes, but the \n remains in the containing text. they are in the nsiaccessible hierarchy to make it easy for nshypertextaccessible to piece its text representation together. everything else uses whatever nsaccessible-derived implementation that's appropriate. if it has text siblings, then it gets exposed as the unicode char for an embedded object, which is '\xfffc' within the parent nshypertextaccessible. in addition, nsiaccessiblehyperlink is implemented on any non-text child inside a container that also has text. this allows at's to find its position within that text, because the hyperlink interface exposes a start and end index. in fact, the end index will always be 1 larger than the start index, because the...
... redundant with the information in the parent object's nsiaccessibletext. this is done for backward compatibility with older msaa clients which didn't have access to a text interface. the children of a hypertext object are a superset of the links it exposes. the new system makes it easier to show caret positions etc., which will be an improvement in ia2 over msaa. example take the following html code: <div>hello<a href="http://www.mozilla.org/access">my link<img src="image.gif">is cool</a>bye</div> both the <a> and <img> are hyperlinks also, both the <div> and <a> are hypertexts so the <a> is both a hypertext and a hyperlink, because it contains text and is contained within text. this means that we have an exact mirror to the dom, but text lives in the parents instead of in the leaves, whic...
...get around this problem, mozilla allows the magic value of -2 to be passed into accessibletext/accessiblehypertext methods that take a character offset. this value of -2 means, use the caret position. not only can this save extra calls, but it will always return the visual line of text when used with the gettext methods and line boundaries. the following magic offsets are useful to define in your code: #define char_offset_end_of_line = -1 #define char_offset_caret = -2 more information many more details on the mozilla document hierarchy are in the original design document for newatk. there are also details on the general implementation of mozilla accessibility architecture (needs updating). ...
Keyboard-navigable JavaScript widgets - Accessibility
essible web applications and widgets.) the aria-activedescendant property identifies the id of the descendent element that currently has the virtual focus. the event handler on the container must respond to key and mouse events by updating the value of aria-activedescendant and ensuring that the current item is styled appropriately (for example, with a border or background color). see the source code of this aria radiogroup example for a direct illustration of how this works. general guidelines use onkeydown to trap key events, not onkeypress ie will not fire keypress events for non-alphanumeric keys. use onkeydown instead. ensure that keyboard and mouse produce the same experience to ensure that the user experience is consistent regardless of input device, keyboard and mouse event handl...
...iogroup example for a direct illustration of how this works. general guidelines use onkeydown to trap key events, not onkeypress ie will not fire keypress events for non-alphanumeric keys. use onkeydown instead. ensure that keyboard and mouse produce the same experience to ensure that the user experience is consistent regardless of input device, keyboard and mouse event handlers should share code where appropriate. for example, the code that updates the tabindex or the styling when users navigate using the arrow keys should also be used by mouse click handlers to produce the same changes. ensure that the keyboard can be used to activate element to ensure that the keyboard can be used to activate elements, any handlers bound to mouse events should also be bound to keyboard events. for ex...
...anges. ensure that the keyboard can be used to activate element to ensure that the keyboard can be used to activate elements, any handlers bound to mouse events should also be bound to keyboard events. for example, to ensure that the enter key will activate an element, if you have an onclick="dosomething()", you should bind dosomething() to the key down event as well: onkeydown="return event.keycode != 13 || dosomething();". always draw the focus for tabindex="-1" items and elements that receive focus programatically ie will not automatically draw the focus outline for items that programatically receive focus. choose between changing the background color via something like this.style.backgroundcolor = "gray"; or add a dotted border via this.style.border = "1px dotted invert". in the dotted...
... an invisible 1px border to start with, so that the element doesn't grow when the border style is applied (borders take up space, and ie doesn't implement css outlines). prevent used key events from performing browser functions if your widget handles a key event, prevent the browser from also handling it (for example, scrolling in response to the arrow keys) by using your event handler's return code. if your event handler returns false, the event will not be propagated beyond your handler. for example: <span tabindex="-1" onkeydown="return handlekeydown();"> if handlekeydown() returns false, the event will be consumed, preventing the browser from performing any action based on the keystroke. don't rely on consistent behavior for key repeat, at this point unfortunately onkeydown may or m...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
ontent: "look at this orange box."; background-color: #ffba10; border-color: black; border-style: dotted; } result to-do list in this example we will create a simple to-do list using pseudo-elements. this method can often be used to add small touches to the ui and improve user experience. ...
...rder-color: #009933; border-style: solid; border-width: 0 0.3em 0.25em 0; height: 1em; top: 1.3em; left: 0.6em; margin-top: -1em; transform: rotate(45deg); width: 0.5em; } javascript var list = document.queryselector('ul'); list.addeventlistener('click', function(ev) { if (ev.target.tagname === 'li') { ev.target.classlist.toggle('done'); } }, false); here is the above code example running live. note that there are no icons used, and the check-mark is actually the ::before that has been styled in css. go ahead and get some stuff done. result special characters as this is css; not html, you can not use markup entities in content values. if you need to use a special character, and can not enter it literally into your css content string, use a unicode escape seque...
...the check-mark is actually the ::before that has been styled in css. go ahead and get some stuff done. result special characters as this is css; not html, you can not use markup entities in content values. if you need to use a special character, and can not enter it literally into your css content string, use a unicode escape sequence, consisting of a backslash followed by the hexadecimal unicode value. html <ol> <li>crack eggs into bowl</li> <li>add milk</li> <li>add flour</li> <li aria-current='step'>mix thoroughly into a smooth batter</li> <li>pour a ladleful of batter onto a hot, greased, flat frying pan</li> <li>fry until the top of the pancake loses its gloss</li> <li>flip it over and fry for a couple more minutes</li> <li>serve with your favorite topping</li> </ol...
... working draft no significant changes to the previous specification. css animations working draft allows animations on properties defined on pseudo-elements. se...
backface-visibility - CSS: Cascading Style Sheets
, effectively making the element invisible when turned away from the user. formal definition initial valuevisibleapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax visible | hidden examples cube with transparent and opaque faces this example shows a cube with transparent faces, and one with opaque faces. ...
...isible when turned away from the user. formal definition initial valuevisibleapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax visible | hidden examples cube with transparent and opaque faces this example shows a cube with transparent faces, and one with opaque faces. ...
...way from the user. formal definition initial valuevisibleapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax visible | hidden examples cube with transparent and opaque faces this example shows a cube with transparent faces, and one with opaque faces. ...
...ion initial valuevisibleapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax visible | hidden examples cube with transparent and opaque faces this example shows a cube with transparent faces, and one with opaque faces. ...
border-image-slice - CSS: Cascading Style Sheets
ular, but can have some interesting effects. border-width: changes the width of the border. the sampled image size is scaled to fit inside the border, which means that if the width is bigger than the slice, the image can start to look somewhat pixellated (unless of course you use an svg image). ...
...some interesting effects. border-width: changes the width of the border. the sampled image size is scaled to fit inside the border, which means that if the width is bigger than the slice, the image can start to look somewhat pixellated (unless of course you use an svg image). ...
...igger than the slice, the image can start to look somewhat pixellated (unless of course you use an svg image). ...
... image can start to look somewhat pixellated (unless of course you use an svg image). ...
<length> - CSS: Cascading Style Sheets
Web › CSS › length
an element or its parent. note: these units, especially em and rem, are often used to create scalable layouts, which maintain the vertical rhythm of the page even when the user changes the font size. cap represents the "cap height" (nominal height of capital letters) of the element’s font. ch represents the width, or more precisely the advance measure, of the glyph "0" (zero, the unicode character u+0030) in the element's font. in the cases where it is impossible or impractical to determine the measure of the “0” glyph, it must be assumed to be 0.5em wide by 1em tall. em represents the calculated font-size of the element. if used on the font-size property itself, it represents the inherited font-size of the element. ex represents the x-height of the element's font. on ...
...: 50px; background-color: #999; box-shadow: inset 3px 3px 5px rgba(255,255,255,0.5), inset -3px -3px 5px rgba(0,0,0,0.5); } .result { height: 20px; background-color: #999; box-shadow: inset 3px 3px 5px rgba(255,255,255,0.5), inset -3px -3px 5px rgba(0,0,0,0.5); background-color: orange; display: flex; align-items: center; margin-top: 10px; } .result code { position: absolute; margin-left: 20px; } .results { margin-top: 10px; } .input-container { position: absolute; display: flex; justify-content: flex-start; align-items: center; height: 50px; } label { margin: 0 10px 0 20px; } javascript const inputdiv = document.queryselector('.inner'); const inputelem = document.queryselector('input'); const resultsdiv = document.querysel...
... editor's draft adds the vi, vb, ic, lh, and rlh units. css values and units module level 3the d...
... editor's draft adds the vi, vb, ic, lh, and rlh units. css values and units module level 3the definition of '<length>' in that ...
overflow-block - CSS: Cascading Style Sheets
ars if content overflows. formal definition initial valueautoapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto examples html <ul> <li><code>overflow-block:hidden</code> — hides the text outside the box <div id="div1"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu ...
...utside the box <div id="div1"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:scroll</code> — always adds a scrollbar <div id="div2"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat ...
...ds a scrollbar <div id="div2"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:visible</code> — displays the text outside the box if needed <div id="div3"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cil...
... box if needed <div id="div3"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </div> </li> <li><code>overflow-block:auto</code> — on most browser, equivalent to <code>scroll</code> <div id="div4"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse...
place-content - CSS: Cascading Style Sheets
ocomputed valueas specifiedanimation typediscrete formal syntax <'align-content'> <'justify-content'>? ...
...ecifiedanimation typediscrete formal syntax <'align-content'> <'justify-content'>? ...
...iv> <div class="large"></div> <div class="large"></div> </div> <code>writing-mode:</code><select id="writingmode"> <option value="horizontal-tb" selected>horizontal-tb</option> <option value="vertical-rl">vertical-rl</option> <option value="vertical-lr">vertical-lr</option> <option value="sideways-rl">sideways-rl</option> <option value="sideways-lr">sideways-lr</option> </select><code>;</code><br/> <code>direction:</code><select id="direction"> <option value="ltr" selected>ltr</option> <option value="rtl">rtl</option> </select><code>;</code><br/> <code>place-content:</code><select id="aligncontentalignment"> <option value="normal">normal</option> <option value="first baseline">first baseline</option> <option value="last baseline">last baseline</option> <option valu...
...>stretch</option> <option value="center" selected>center</option> <option value="start">start</option> <option value="end">end</option> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="left">left</option> <option value="right">right</option> <option value="safe">safe</option> <option value="unsafe">unsafe</option> </select><code>;</code> var update = function () { document.getelementbyid("container").style.placecontent = document.getelementbyid("aligncontentalignment").value + " " + document.getelementbyid("justifycontentalignment").value; } var aligncontentalignment = document.getelementbyid("aligncontentalignment"); aligncontentalignment.addeventlistener("change", update); var justifycontentalignment = document...
text-justify - CSS: Cascading Style Sheets
which is most appropriate for languages like japanese. distribute exhibits the same behaviour as inter-character; this value is kept for backwards compatibility. formal definition initial valueautoapplies toinline-level and table-cell elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | inter-character | inter-word | none examples <p class="none"><code>text-justify: none</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc ornare maximus vehicula. duis nisi velit, dictum id mauris vitae, lobortis pretium quam. quisque sed nisi pulvinar, consequat justo id, feugiat leo. cras eu elementum dui.</p> <p class="auto"><code>text-justify: auto</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc ornare maxi...
...m. quisque sed nisi pulvinar, consequat justo id, feugiat leo. cras eu elementum dui.</p> <p class="auto"><code>text-justify: auto</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc ornare maximus vehicula. duis nisi velit, dictum id mauris vitae, lobortis pretium quam. quisque sed nisi pulvinar, consequat justo id, feugiat leo. cras eu elementum dui.</p> <p class="dist"><code>text-justify: distribute</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc ornare maximus vehicula. duis nisi velit, dictum id mauris vitae, lobortis pretium quam. quisque sed nisi pulvinar, consequat justo id, feugiat leo. cras eu elementum dui.</p> <p class="word"><code>text-justify: inter-word</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc...
...nunc ornare maximus vehicula. duis nisi velit, dictum id mauris vitae, lobortis pretium quam. quisque sed nisi pulvinar, consequat justo id, feugiat leo. ...
...nunc ornare maximus vehicula. duis nisi velit, dictum id mauris vitae, lobortis pretium quam. quisque sed nisi pulvinar, consequat justo id, feugiat leo. ...
white-space - CSS: Cascading Style Sheets
pre-wrap preserve preserve wrap hang pre-line preserve collapse wrap remove break-spaces preserve preserve wrap wrap formal definition initial valuenormalapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | pre | nowrap | pre-wrap | pre-line | break-spaces examples basic example code { white-space: pre; } line breaks inside <pre> elements pre { word-wrap: break-word; /* ie 5.5-7 */ white-space: pre-wrap; /* modern browsers */ } in action html <div id="css-code" class="box"> p { white-space: <select> <option>normal</option> <option>nowrap</option> <option>pre</option> <option>pre-wrap</option> <option>pre-line</option> <option>...
...m veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ...
...is aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ...
...> </div> .box { width: 300px; padding: 16px; border-radius: 10px; } #css-code { background-color: rgb(220, 220, 220); font-size: 16px; font-family: monospace; } #css-code select { font-family: inherit; } #results { background-color: rgb(230, 230, 230); overflow-x: scroll; height: 400px; white-space: normal; font-size: 14px; } var select = document.queryselector("#css-code select"); var results = document.queryselector("#results p"); select.addeventlistener("change", function(e) { results.setattribute("style", "white-space: "+e.target.value); }) <p> lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea co...
Video player styling basics - Developer guides
in the previous cross browser video player article we described how to build a cross-browser html5 video player using the media and fullscreen apis. this follow-up article looks at how to style this custom player, including making it responsive. the example in action you can find the code for the updated, styled example on github, and view it live. preliminary modifications from the original example this section summarises the modifications that were made to the original video player example to make the styling task easier, before the bulk of the work was started. html markup there are a few changes that were made to the html markup shown in the previous article. the custom video controls and <progress> element are now contained within <div> elements, rather than residing ins...
...ton" data-state="volup">vol+</button> <button id="voldec" type="button" data-state="voldown">vol-</button> <button id="fs" type="button" data-state="go-fullscreen">fullscreen</button> </div> related css alteration the previous article simply set the display property of the video controls to block in order to display them. this has now been changed to use a data-state attribute, which this code already uses to handle its fullscreen implementation. this "data-state" idea is also used for setting the current state of buttons within the video control set, which allows specific state styling. javascript as mentioned above, a data-state attribute is used in various places for styling purposes and these are set using javascript. specific implementations will be mentioned at appropriate pla...
...ute is used in various places for styling purposes and these are set using javascript. specific implementations will be mentioned at appropriate places below. styling the resultant video player style used here is rather basic — this is intentional, as the purpose is to show how such a video player could be styled and be made responsive. note: in some cases some basic css is omitted from the code examples here as its use is either obvious or not specifically relevant to styling the video player. basic styling the html video and its controls are all contained within a <figure> element, which is given a maximum width and height (based on the dimensions of the video used) and centered within the page: figure { max-width:64rem; width:100%; max-height:30.875rem; height:100%; ...
...ransparent, non-repeated, and the element should fully contain the image. simple :hover and :focus states are then set for each button that simply alters the opacity of the button: .controls button:hover, .controls button:focus { opacity:0.5; } to obtain appropriate button images, a set of free common control set icons was downloaded from the web. each image was then converted to a base64 encoded string (using an online base64 image encoder), since the images are quite small, the resultant encoded strings are quite short. since some buttons have dual functionality, e.g. play/pause, and mute/unmute, these buttons have different states that need to be styled. as mentioned earlier, a `data-state` variable is used to indicate which state such buttons are currently in. for example, the play...
<input type="color"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › color
}); } selecting the value if the <input> element's implementation of the color type on the user's browser doesn't support a color well, but is instead a text field for entering the color string directly, you can use the select() method to select the text currently in the edit field. if the browser instead uses a color well, select() does nothing. you should be aware of this behavior so your code can respond appropriately in either case. colorwell.select(); appearance variations as previously mentioned, when a browser doesn't support a color picker interface, its implementation of color inputs will be a text box that validates the contents automatically to ensure that the value is in the correct format. for example, in safari 10.1, you would see something that looks looks like this: ...
...a little more with the color input by tracking the change and input events to take the new color and apply it to every <p> element in the document. html the html is fairly straightforward — a couple of paragraphs of descriptive material with an <input> of type color with the id colorwell, which we'll use to change the color of the paragraphs' text. ...
...t by tracking the change and input events to take the new color and apply it to every <p> element in the document. html the html is fairly straightforward — a couple of paragraphs of descriptive material with an <input> of type color with the id colorwell, which we'll use to change the color of the paragraphs' text. ...
...f the paragraphs' text. <p>an example demonstrating the use of the <code>&lt;input type="color"&gt;</code> control.</p> <label for="colorwell">color:</label> <input type="color" value="#ff0000" id="colorwell"> <p>watch the paragraph colors change when you adjust the color picker. as you make changes in the color picker, the first paragraph's color changes, as a preview (this uses the <code>input</code> event). when you close the color picker, the <code>change</code> event fires, and we detect that to change every paragraph to the selected color.</p> javascript first, there's some setup. here we establish some variables, setting up a variable that contains the color we'll set the color well to when we first load up, and then setting up a load handler to do the main startu...
<input type="image"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › image
indicating the url to which to submit the data. this takes precedence over the action attribute on the <form> element that owns the <input>. this attribute is also available on <input type="submit"> and <button> elements. formenctype a string that identifies the encoding method to use when submitting the form data to the server. there are three permitted values: application/x-www-form-urlencoded this, the default value, sends the form data as a string after url encoding the text using an algorithm such as encodeuri(). multipart/form-data uses the formdata api to manage the data, allowing for files to be submitted to the server. you must use this encoding type if your form includes any <input> elements of type file (<input type="file">). text/plain plain text; mostly useful only for...
...<input type="submit"> and <button> elements. formmethod a string indicating the http method to use when submitting the form's data; this value overrides any method attribute given on the owning form. permitted values are: get a url is constructed by starting with the url given by the formaction or action attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by formenctype or the form's enctype attribute. this url is then sent to the server using an http get request. this method works well for simple forms that contain only ascii characters and have no side effects. this is the default value. post the form's data is included in the body of the request that is sent to the url given by the formaction or action attribute using an http po...
...ns — can accept a number of attributes that override the default form behavior: formaction html5 the uri of a program that processes the information submitted by the input element; overrides the action attribute of the element's form owner. formenctype html5 specifies the type of content that is used to submit the form to the server. possible values are: application/x-www-form-urlencoded: the default value if the attribute is not specified. text/plain. if this attribute is specified, it overrides the enctype attribute of the element's form owner. formmethod html5 specifies the http method that the browser uses to submit the form. possible values are: post: the data from the form is included in the body of the form and is sent to the server. get: the data from the...
...y=55. this, of course, applies to all other attributes as well. these are the x and y coordinates of the image that the mouse clicked on to submit the form, where (0,0) is the top-left of the image. these can be used when the position the image was clicked on is significant, for example you might have a map that when clicked, sends the coordinates that were clicked to the server. the server-side code then works out what location was clicked on, and returns information about places nearby. in our above example, we could write server-side code that works out what color was clicked on by the coordinates submitted, and keeps a tally of the favorite colors people voted for. adjusting the image's position and scaling algorithm you can use the object-position property to adjust the positioning of...
HTTP Messages - HTTP
Web › HTTP › Messages
in http/1.1, and earlier versions of the protocol, these messages were openly sent across the connection. ...
...file, defined by the two headers: content-type and content-length. multiple-resource bodies, consisting of a multipart body, each containing a different bit of information. this is typically associated with html forms. http responses status line the start line of an http response, called the status line, contains the following information: the protocol version, usually http/1.1. a status code, indicating success or failure of the request. common status codes are 200, 404, or 302 a status text. a brief, purely informational, textual description of the status code to help a human understand the http message. a typical status line looks like: http/1.1 404 not found. headers http headers for responses follow the same structure as any other header: a case-insensitive string followed b...
...e message. response headers, like vary and accept-ranges, give additional information about the server which doesn't fit in the status line. entity headers, like content-length, apply to the body of the response. typically, no such headers are transmitted when there is no body in the response. body the last part of a response is the body. ...
... multiple-resource bodies, consisting of a multipart body, each containing a different section of information. these are relatively rare. http/2 frames http/1.x messages have a few drawbacks for performance: headers, unlike bodies, are uncompressed. ...
Network Error Logging - HTTP
hanism that can be configured via the nel http response header. this experimental header allows web sites and applications to opt-in to receive reports about failed (and, if desired, successful) network fetches from supporting browsers. reports are sent to a reporting group defined within a report-to header. usage web applications opt in to this behaviour with the nel header, which is a json-encoded object: nel: { "report_to": "nel", "max_age": 31556952 } an origin considered secure by the browser is required. the following object keys can be specified in the nel header: report_to the reporting api group to send network error reports to (see below). max_age specifies the lifetime of the policy, in seconds (in a similar way to e.g. hsts policies are time-restricted). the...
... contains the network error report. http 400 (bad request) response { "age": 20, "type": "network-error", "url": "https://example.com/previous-page", "body": { "elapsed_time": 338, "method": "post", "phase": "application", "protocol": "http/1.1", "referrer": "https://example.com/previous-page", "sampling_fraction": 1, "server_ip": "137.205.28.66", "status_code": 400, "type": "http.error", "url": "https://example.com/bad-request" } } dns name not resolved note that the phase is set to dns in this report and no server_ip is available to include. { "age": 20, "type": "network-error", "url": "https://example.com/previous-page", "body": { "elapsed_time": 18, "method": "post", "phase": "dns", "protocol": "http/1.1", ...
...note that the phase is set to dns in this report and no server_ip is available to include. ...
...ion was reset tcp.refused the tcp connection was refused by the server tcp.aborted the tcp connection was aborted tcp.address_invalid the ip address is invalid tcp.address_unreachable the ip address is unreachable tcp.failed the tcp connection failed due to reasons not covered by previous errors http.error the user agent successfully received a response, but it had a 4xx or 5xx status code http.protocol.error the connection was aborted due to an http protocol error http.response.invalid response is empty, has a content-length mismatch, has improper encoding, and/or other conditions that prevent user agent from processing the response http.response.redirect_loop the request was aborted due to a detected redirect loop http.failed the connection failed due to errors in http pr...
HTTP Public Key Pinning (HPKP) - HTTP
his means that for users who imported custom root certificates all pinning violations are ignored. enabling hpkp to enable this feature for your site, you need to return the public-key-pins http header when your site is accessed over https: public-key-pins: pin-sha256="base64=="; max-age=expiretime [; includesubdomains][; report-uri="reporturi"] pin-sha256 the quoted string is the base64 encoded subject public key information (spki) fingerprint. it is possible to specify multiple pins for different public keys. some browsers might allow other hashing algorithms than sha-256 in the future. see below on how to extract this information out of a certificate or key file. max-age the time, in seconds, that the browser should remember that this site is only to be accessed using one of the de...
...ied, pin validation failures are reported to the given url. note: the current specification requires including a second pin for a backup key which isn't yet used in production. this allows for changing the server's public key without breaking accessibility for clients that have already noted the pins. this is important for example when the former key gets compromised. extracting the base64 encoded public key information note: while the example below shows how to set a pin on a server certificate, it is recommended to place the pin on the intermediate certificate of the ca that issued the server certificate, to ease certificates renewals and rotations. first you need to extract the public key information from your certificate or key file and encode them using base64. the following com...
...e example below shows how to set a pin on a server certificate, it is recommended to place the pin on the intermediate certificate of the ca that issued the server certificate, to ease certificates renewals and rotations. first you need to extract the public key information from your certificate or key file and encode them using base64. the following commands will help you extract the base64 encoded information from a key file, a certificate signing request, or a certificate. openssl rsa -in my-rsa-key-file.key -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64 openssl ec -in my-ecc-key-file.key -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64 openssl req -in my-signing-request.csr -pubkey -noout | openssl pkey -pubin -outform der | openssl...
... openssl s_client -servername www.example.com -connect www.example.com:443 | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 example hpkp header public-key-pins: pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws="; pin-sha256="m8hztczm3eluxkcjr2s5p4hhybnf6lhkmjahkhpgpwe="; max-age=5184000...
Classes - JavaScript
classes in js are built on prototypes but also have some syntax and semantics that are not shared with es5 classalike semantics. defining classes classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations. class declarations one way to define a class is using a class declaration. to declare a class, you use the class keyword with the name of the class ("rectangle" here). ...
...the class keyword with the name of the class ("rectangle" here). class rectangle { constructor(height, width) { this.height = height; this.width = width; } } hoisting an important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. you first need to declare your class and then access it, otherwise code like the following will throw a referenceerror: const p = new rectangle(); // referenceerror class rectangle {} class expressions a class expression is another way to define a class. class expressions can be named or unnamed. the name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) name property, though). // unname...
...ectangle.name); // output: "rectangle2" note: class expressions are subject to the same hoisting restrictions as described in the class declarations section. class body and method definitions the body of a class is the part that is in curly brackets {}. this is where you define class members, such as methods or constructor. strict mode the body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ecmascript. constructor the constructor method is a special method for creating and initializing an object created with a class. there can only be one special method with the name "constructor" in a class. a syntaxerror will ...
...//undefined console.log(point.distance(p1, p2)); // 7.0710678118654755 binding this with prototype and static methods when a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method. this behavior will be the same even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode. class animal { speak() { return this; } static eat() { return this; } } let obj = new animal(); obj.speak(); // the animal object let speak = obj.speak; speak(); // undefined animal.eat() // class animal let eat = animal.eat; eat(); // undefined if we rewrite the above using traditional function-base...
SyntaxError: unterminated string literal - JavaScript
uotes (single or double) for your string literal, you have escaped your string literal correctly, your string literal isn't split across multiple lines. ...
...make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. ...
...se the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. ...
...ooks like this: var longstring = 'this is a very long string which needs \ to wrap across multiple lines because \ otherwise my code is unreadable.'; another possibility is to use template literals, which are supported in ecmascript 2015 environments: var longstring = `this is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.`; ...
Function - JavaScript
constructor function() creates a new function object. calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. however, unlike eval, the function constructor creates functions that execute in the global scope only. instance properties function.arguments an array corresponding to the arguments passed to a function. this is deprecated as a property of function. use the arguments object (available within the function) instead. ...
... when called, has its this set to the provided thisarg. optionally, a given sequence of arguments will be prepended to arguments provided the newly-bound function is called. function.prototype.call(thisarg[, arg1, arg2, ...argn]) calls a function and sets its this to the provided value. arguments can be passed as they are. function.prototype.tostring() returns a string representing the source code of the function. overrides the object.prototype.tostring method. examples difference between function constructor and function declaration functions created with the function constructor do not create closures to their creation contexts; they always are created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones fro...
...function constructor and function declaration functions created with the function constructor do not create closures to their creation contexts; they always are created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the function constructor was created. this is different from using eval with code for a function expression. var x = 10; function createfunction1() { var x = 20; return new function('return x;'); // this |x| refers global |x| } function createfunction2() { var x = 20; function f() { return x; // this |x| refers local |x| above } return f; } var f1 = createfunction1(); console.log(f1()); // 10 var f2 = createfunction2(); console.log(...
...this is because the top-level scope in node is not the global scope, and x will be local to the module. specifications specification ecmascript (ecma-262)the definition of 'function' in that specification. ...
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
nstruction of the current displaynames object. syntax displaynames.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given displaynames object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. style the value provided for this property in the options argument of the constructor or the default value ("long"). its value is either "long", "short", or "narrow". type the value provided for this propert...
...the constructor or the default value ("long"). its value is either "long", "short", or "narrow". type the value provided for this property in the options argument of the constructor or the default value ("language"). its value is either "language", "region", "script", or "currency". ...
...t value ("long"). its value is either "long", "short", or "narrow". type the value provided for this property in the options argument of the constructor or the default value ("language"). its value is either "language", "region", "script", or "currency". fallback the value provided for this property in the options argument of the constructor or the default value ("code"). its value is either "code" or "none". ...
...default value ("code"). its value is either "code" or "none". examples using resolvedoptions const displaynames = new intl.displaynames(['de-de'], {type: 'region'}); const usedoptions = displaynames.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "long" console.log(usedoptions.type); // "region" console.log(usedoptions.fallback); // "code" specifications specification intl.displaynamesthe definition of 'resolvedoptions()' in that specification. ...
Intl.Locale.prototype.collation - JavaScript
m search query results to ordering records in a database. while the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. the collation property helps to make it easier for javascript programmers to access the collation type used by a particular locale. below is a table with the available collation types, taken from the unicode collation specification. valid collation types collation type description big5han pinyin ordering for latin, big5 charset ordering for cjk characters (used in chinese) compat a previous version of the ordering, for compatibility dict dictionary style ordering (such as in sinhala) the direct collation type has been deprected.
...ypes collation type description big5han pinyin ordering for latin, big5 charset ordering for cjk characters (used in chinese) compat a previous version of the ordering, for compatibility dict dictionary style ordering (such as in sinhala) the direct collation type has been deprected. do not use. ...
... pinyin ordering for latin, big5 charset ordering for cjk characters (used in chinese) compat a previous version of the ordering, for compatibility dict dictionary style ordering (such as in sinhala) the direct collation type has been deprected. do not use. ...
...dering for cjk characters (used in chinese) zhuyin pinyin ordering for latin, zhuyin order for bopomofo and cjk characters (used in chinese) examples like other locale subtags, the collation type can be added to the intl.locale object via the locale string, or a configuration object argument to the constructor. adding a collation type via the locale string in the unicode locale string spec, collation types are locale key "extension subtags". these subtags add additional data about the locale, and are added to locale identifiers by using the -u extension. thus, the collation type can be added to the inital locale identifier string that is passed into the locale constructor. to add the collation type, first add the -u extension to the string. next, add the -co exte...
Object.prototype.constructor - JavaScript
ceof type, types[i].tostring()] } console.log(types.join('\n')) this example displays the following output (comments added for reference): function type() {},false, // new array() function type() {},false, // [] function type() {},false,false // new boolean() function boolean() { [native code] },false,true // true function type() {},false,mon sep 01 2014 16:03:49 gmt+0600 // new date() function type() {},false,error // new error() function type() {},false,function anonymous() { } // new function() function type() {},false,function () {} ...
...ew error() function type() {},false,function anonymous() { } // new function() function type() {},false,function () {} // function () {} function type() {},false,[object math] // math function type() {},false,0 // new number() function number() { [native code] },false,1 // 1 function type() {},false,[object object] // new object() function type() {},false,[object object] // {} function type() {},false,/(?:)/ // new regexp() function type() {},false,/(?:)/ // /(?:)/ function type() {},false, ...
... function parent() { /* ... */ } parent.prototype.parentmethod = function parentmethod() {} function child() { parent.call(this) // make s...
...ject.create(parent.prototype) // re-define child prototype to parent prototype child.prototype.constructor = child // return original constructor to child but when do we need to perform the last line here? unfortunately, the answer is: it depends. let's try to define the cases in which re-assignment of the original constructor will play a major role, and when it will be one superfluous line of code. take the following case: the object has the create() method to create itself. function parent() { /* ... */ } function createdconstructor() { parent.call(this) } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.create = function create() { return new this.constructor() } new createdconstructor().create().create() // typeerror undefined is not ...
Object.prototype.toString() - JavaScript
s a tostring() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. by default, the tostring() method is inherited by every object descended from object. if this method is not overridden in a custom object, tostring() returns "[object type]", where type is the object type. the following code illustrates this: const o = new object(); o.tostring(); // returns [object object] note: starting in javascript 1.8.5, tostring() called on null returns [object null], and undefined returns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata. see using tostring() to detect object class. parameters for numbers and bigints tostring() takes an optional para...
... for decimal numbers, 16 for hexadecimal numbers. examples overriding the default tostring method you can create a function to be called in place of the default tostring() method. the tostring() method takes no arguments and should return a string. the tostring() method you create can be any value you want, but it will be most useful if it carries information about the object. ...
...this function generates a string containing the name, breed, color, and sex of the object, in the form "property = value;". dog.prototype.tostring = function dogtostring() { const ret = 'dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; return ret; } or, using es6 template strings: do...
... and sex of the object, in the form "property = value;". dog.prototype.tostring = function dogtostring() { const ret = 'dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; return ret; } or, using es6 template strings: dog.prototype.tostring = function dogtostring() { return `dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`; } with the preceding code in place, any time thedog is used in a string context, javascript automatically calls the dogtostring() function, which returns the following string: "dog gabby is a female chocolate lab" using tostring() to detect object class tostring() can be used with every object and (by default) allows you to get its class. to use the object.prototype.tostring() with every object, you need to call func...
Object - JavaScript
ype object and properties. object.defineproperty() adds the named property described by a given descriptor to an object. object.defineproperties() adds the named properties described by the given descriptors to an object. object.entries() returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties. object.freeze() freezes an object. other code cannot delete or change its properties. object.fromentries() returns a new object from an iterable of [key, value] pairs. (this is the reverse of object.entries). object.getownpropertydescriptor() returns a property descriptor for a named property on an object. object.getownpropertydescriptors() returns an object containing all own property descriptors for an object. object.getownpropertyn...
... object.isextensible() determines if extending of an object is allowed. object.isfrozen() determines if an object was frozen. object.issealed() determines if an object is sealed. object.keys() returns an array containing the names of all of the given object's own enumerable string properties. object.preventextensions() prevents any extensions of an object. object.seal() prevents other code from deleting properties of an object. object.setprototypeof() sets the object's prototype (its internal [[prototype]] property). object.values() returns an array containing the values that correspond to all of a given object's own enumerable string properties. instance properties object.prototype.constructor specifies the function that creates an object's prototype. object.prototype._...
... when a function is called, the arguments to the call are held in the array-like "variable" arguments. for example, in the call myfn(a, b, c), the arguments within myfn's body will contain 3 ...
... objects the following examples store boolean objects in o: // equivalent to o = new boolean(true) let o = new object(true) // equivalent to o = new boolean(false) let o = new object(boolean()) object prototypes when altering the behavior of existing object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic. for example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed. when a function is called, the arguments to the call are held in the array-like "variable" arguments. for example, in the call myfn(a, b, c), the arguments within myfn's body will contain 3 array-like elements corresponding to (a, b, c). when modifying prototypes with hooks, pass this ...
SyntaxError() constructor - JavaScript
the syntaxerror constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ...
... the syntaxerror constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ...
...e syntaxerror constructor creates a new error object that represents an error when trying to interpret syntactically invalid code. ...
... ...
WebAssembly.instantiate() - JavaScript
the returned promise resolves to both a compiled webassembly.module and its first webassembly.instance. the secondary overload takes an already-compiled webassembly.module and returns a promise that resolves to an instance of that module. this overload is useful if the module has already been compiled. important: this method is not the most efficient way of fetching and instantiating wasm modules. ...
...that resolves to an instance of that module. this overload is useful if the module has already been compiled. important: this method is not the most efficient way of fetching and instantiating wasm modules. if at all possible, you should use the newer webassembly.instantiatestreaming() method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an arraybuffer. syntax primary overload — taking wasm binary code promise<resultobject> webassembly.instantiate(buffersource, importobject); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. importobject optional an object containing the values to be imported into the newly-creat...
...cture, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. examples note: you'll probably want to use webassembly.instantiatestreaming() in most cases, as it is more efficient than instantiate(). first overload example after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiate() function, importing a javascript function into the webassembly module in the process. we then call an exported webassembly function that is exported by the instance. var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => ...
...(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(result => result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also). second overload example the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. whe...
WebAssembly - JavaScript
most other global objects, webassembly is not a constructor (it is not a function object). you can compare it to math, which is also a namespace object for mathematical constants and functions, or to intl which is the namespace object for internationalization constructors and other language-sensitive functions. description the primary uses for the webassembly object are: loading webassembly code, using the webassembly.instantiate() function. creating new memory and table instances via the webassembly.memory()/webassembly.table() constructors. providing facilities to handle errors that occur in webassembly via the webassembly.compileerror()/webassembly.linkerror()/webassembly.runtimeerror() constructors. constructor properties webassembly.compileerror() indicates an error during w...
...ssembly.instance() is a stateful, executable instance of a webassembly.module webassembly.linkerror() indicates an error during module instantiation (besides traps from the start function). webassembly.memory() an object whose buffer property is a resizable arraybuffer that holds the raw bytes of memory accessed by a webassembly instance. webassembly.module() contains stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times. webassembly.runtimeerror() error type that is thrown whenever webassembly specifies a trap. webassembly.table() an array-like structure representing a webassembly table, which stores function references. static methods webassembly.instantiate() the primary api for c...
...browser and can be efficiently shared with workers, and instantiated multiple times. webassembly.runtimeerror() error type that is thrown whenever webassembly specifies a trap. webassembly.table() an array-like structure representing a webassembly table, which stores function references. static methods webassembly.instantiate() the primary api for compiling and instantiating webassembly code, returning both a module and its first instance. webassembly.instantiatestreaming() compiles and instantiates a webassembly module directly from a streamed underlying source, returning both a module and its first instance. webassembly.compile() compiles a webassembly.module from webassembly binary code, leaving instantiation as a separate step. webassembly.compilestreaming() compiles a weba...
...returning both a module and its first instance. webassembly.compile() compiles a webassembly.module from webassembly binary code, leaving instantiation as a separate step. webassembly.compilestreaming() compiles a webassembly.module directly from a streamed underlying source, leaving instantiation as a separate step. webassembly.validate() validates a given typed array of webassembly binary code, returning whether the bytes are valid webassembly code (true) or not (false). examples stream a .wasm module then compile and instantiate it the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject. because the instant...
Object initializer - JavaScript
eject computed property names and an error will be thrown. examples creating objects an empty object with no properties can be created like this: let object = {} however, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. you simply notate a list of key: value pairs delimited by commas. the following code creates an object with three properties and the keys are "foo", "age" and "baz". the values of these keys are a string "bar", the number 42, and another object. let object = { foo: 'bar', age: 42, baz: {myprop: 12} } accessing properties once you have created an object, you might want to read or change them. object properties can be accessed by using the dot notation or the bracket notat...
...e created an object, you might want to read or change them. object properties can be accessed by using the dot notation or the bracket notation. (see property accessors for detailed information.) object.foo // "bar" object['age'] // 42 object.foo = 'baz' property definitions we have already learned how to notate properties using the initializer syntax. ...
...bject properties can be accessed by using the dot notation or the bracket notation. (see property accessors for detailed information.) object.foo // "bar" object['age'] // 42 object.foo = 'baz' property definitions we have already learned how to notate properties using the initializer syntax. oftentimes, there are variables in your code that you would like to put into an object. ...
...a shorter notation available to achieve the same: let a = 'foo', b = 42, c = {}; // shorthand property names (es2015) let o = {a, b, c} // in other words, console.log((o.a === {a}.a)) // true duplicate property names when using the same name for your properties, the second property will overwrite the first. let a = {x: 1, x: 2} console.log(a) // {x: 2} in ecmascript 5 strict mode code, duplicate property names were considered a syntaxerror. with the introduction of computed property names making duplication possible at runtime, ecmascript 2015 has removed this restriction. function havees2015duplicatepropertysemantics() { 'use strict'; try { ({prop: 1, prop: 2}); // no error thrown, duplicate property names allowed in strict mode return true; } catch(e) { ...
Operator precedence - JavaScript
ble by the representation below. note that both op1 and op2 are fill-in-the-blanks for operators. a op1 b op2 c if op1 and op2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code. console.log(3 + 10 * 2); // logs 23 console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous console.log((3 + 10) * 2); // logs 26 because the parentheses change the order left-associativity (left-to-right) means that it is processed as (a op1 b) op2 c, while right-associativity (right-to-left) means it is interpreted as a op1 (b op2 c). assignment operators are right-...
...alue that is assigned. first, b is set to 5. then the a is also set to 5, the return value of b = 5, aka right operand of the assignment. as another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. it is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity. ...
...evaluating the right side 8 the difference in associativity comes into play when there are multiple operators of the same precedence. with only one operator or operators of different precedences, associativity doesn't affect the output, as seen in the example above. in the example below, observe how associativity affects the output when multiple of the same operator are used. ...
...exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above. remember that precedence comes before associativity. so, mixing division and exponentiation, the exponentiation co...
label - JavaScript
t. break can be used with any labeled statement, and continue can be used with looping labeled statements. description you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution. note that javascript has no goto statement, you can only use labels with break or continue. in strict mode code, you can't use "let" as a label name. it will throw a syntaxerror (let is a reserved identifier). examples using a labeled continue with for loops var i, j; loop1: for (i = 0; i < 3; i++) { //the first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { //the second for statement is labeled "loop2" if (i === 1 && j === 1) { continue loop1; } ...
... block with break you can use labels within simple blocks, but only break statements can make use of non-loop labels. ...
... use of non-loop labels. foo: { console.log('face'); break foo; console.log('this will not be executed'); } console.log('swap'); // this will log: // "face" // "swap" labeled function declarations starting with ecmascript 2015, labeled function declarations are now standardized for non-strict code in the web compatibility annex of the specification. ...
...abeled function declarations starting with ecmascript 2015, labeled function declarations are now standardized for non-strict code in the web compatibility annex of the specification. l: function f() {} in strict mode code, however, this will throw a syntaxerror: 'use strict'; l: function f() {} // syntaxerror: functions cannot be labelled generator functions can neither be labeled in strict code, nor in non-strict code: l: function* f() {} // syntaxerror: generator functions cannot be labelled specifications specification ecmascript (ecma-262)the definition of 'labelled statement' in that specification. ...
JavaScript reference - JavaScript
this part of the javascript section on mdn serves as a repository of facts about the javascript language. read more about this reference. built-ins javascript standard built-in objects, along with their methods and properties. ...
...is part of the javascript section on mdn serves as a repository of facts about the javascript language. read more about this reference. built-ins javascript standard built-in objects, along with their methods and properties. ...
...t section on mdn serves as a repository of facts about the javascript language. read more about this reference. built-ins javascript standard built-in objects, along with their methods and properties. ...
...n serves as a repository of facts about the javascript language. read more about this reference. built-ins javascript standard built-in objects, along with their methods and properties. ...
Privacy, permissions, and information security
rity and privacy features available to users on the web, let's define some important terms. personally identifiable information personally identifiable information (pii) is information which can be used, in whole or in part, to track down and/or identify a specific person. as such, pii extends beyond the web to all aspects of life. for example, if a site leaks a list of users' names and zip codes online, a bad actor could almost certainly track down at least some percentage of those users by simply using the corresponding phone books. personally identification can include information like usernames, real names, passwords, phone numbers or addresses (or even portions of them), information about medical history, social security numbers, driver licenses, or any other form of id or id numb...
... to timers in order to make them less useful for identifying the user's system. privacy and security controls there are multiple layers of controls for helping to protect users against security and privacy breaches. these start at the web server, include the very communication layer used over the network, and then extend through the web browser's security offerings before reaching your web app code and the efforts it takes to secure itself and the data the user entrusts to it. there are several web technologies and features at play to manage privacy and security. the following list includes features affecting both, since many of these features are used for both. web technologies and features used to enforce security and privacy technology or feature description c...
... way to determine the status of permissions for the current browser context transport layer security (tls); formerly known as secure sockets layer (ssl) tls provides security and privacy by encrypting data during transport over the network. this is the technology behind the https (hypertext transport protocol secured) protocol not all of these are generally directly used within code; notably, the permissions api, feature policy, and the allow attribute on <iframe> elements are primary tools directly used by code to help secure a site and its content. keeping personal data safe managing site permissions bringing it all together <using feature policy with permissions and so forth; how to use them together, how they interact, etc> permission requests in <iframe> elements ...
...vide ways around this. ...
The building blocks of responsive design - Progressive web apps (PWAs)
he browser or device accessing the site to provide an optimized experience. one approach to this is to create different versions of your site/app for different platforms or browsers and serve them appropriately after detecting which browser or platform is looking at your site. but this is increasingly inefficient: browser sniffing is inherently error prone, and maintaining multiple copies of your code can turn out to be a nightmare. it is usually much better to create a single version of your code which doesn't care about what browser or platform is accessing the site, but instead uses feature tests to find out what code features the browser supports or what the values of certain browser features are, and then adjusts the code appropriately. this tends to be termed responsive design or adapti...
... there are disadvantages to this approach as well. if the content, layout, and functionality need to change greatly for different devices, it may not be such a good approach. ...
...h takes a video stream from your webcam (using getusermedia()) then allows you to capture stills from that video stream (using html5 <canvas>), and save them to a gallery. you can then view previously-captured images and delete them. other articles will discuss the functionality in more detail, but here we're interested in the layout. note: you can find the snapshot app on github; check out the code and help improve it. you can also see snapshot running live. note that getusermedia() is an experimental technology, which currently only works in google chrome and firefox desktop. more functionality and a clean up of the styling of snapshot are planned for a future date. our desktop layout for snapshot is three columns, containing the camera viewer, image capture view, and gallery, respective...
...the layout. this is pretty horrible, but generally this kind of problem is easily fixed with some simple css: img, video { max-width: 100%; } this tells the replaced elements to remain constrained inside their container's widths, no matter what. however, if they aren't as wide as their containers, they will not stretch to fill them. in the snapshot example, we ended up with slightly different code: x-card:nth-child(1) video, x-card:nth-child(2) img { width: 100%; … } this is because in our case, we do in fact want the video and image to stretch to always fill their containers no matter what — a subtle but important difference from max-width — and therefore always be the same size. the video always resizes dynamically, but the screen captures taken from it do not, so upon resi...
Structural overview of progressive web apps - Progressive web apps (PWAs)
/a></p> </header> <main> <h1>js13kgames a-frame entries</h1> <p class="description">list of games submitted to the <a href="http://js13kgames.com/aframe"> a-frame category</a> in the <a href="http://2017.js13kgames.com">js13kgames 2017</a> competition. ...
...the <body> is split into the <header> (which displays an image) and the body of the app, which is found inside a <main> element. the app displays its title, a description, and then a place for the app content to be shown (a <section> element with the id content. below the content is a <footer>, which provides a copyright notice and assorted links. the app's only job is to list all the a-fr...
...sion to send notifications to the user, then generates and sends a random notification. ...
...-cyberspace' }, { slug: 'vernissage', name: 'vernissage', author: 'platane', twitter: 'platane_', website: 'github.com/platane', github: 'github.com/platane/js13k-2017' }, // ... { slug: 'emma-3d', name: 'emma-3d', author: 'prateek roushan', twitter: '', website: '', github: 'github.com/coderprateek/emma-3d' } ]; each entry in the array games describes a specific game, and has a corresponding image file in the data/img/ directory. this is the content we'll load into the content section of the page using javascript code. ...
Progressive web apps (PWAs)
simple javascript library for making client-side data storage really simple; it uses indexeddb by default and falls back to web sql/web storage if necessary. serviceworkerware — an express-like microframework for easy service worker development. oghliner — not only a template but a tool for deploying offline web apps to github pages. ...
... progressive web apps on google developers. progressive web apps: escaping tabs without losing our soul by alex russell. progressive web apps check list. the lighthouse tool by google. tools for building progressive web apps with angular. ...
...resources. workbox — spiritual successor to sw-precache with more advanced caching strategies and easy precaching. upup — a tiny script that makes sure your site is always there for your users. the service worker cookbook — a series of excellent service worker/push recipes, showing how to implement an offline app, but also much more. pwa vs code extension - a collection of all essential code snippets you need to build progressive web apps right there in your vs code environment. progressive web apps on google developers. progressive web apps: escaping tabs without losing our soul by alex russell. progressive web apps check list. the lighthouse tool by google. tools for building progressive web apps with angular. react pwa guide kit. offline-capable pokédex web site. hac...
... check list. the lighthouse tool by google. tools for building progressive web apps with angular. react pwa guide kit. ...
Subresource Integrity - Web security
attacks such as this, by ensuring that the files your web application or web document fetches (from a cdn or anywhere) have been delivered without a third-party having injected any additional content into those files — and without any other changes of any kind at all having been made to those files. using subresource integrity you use the subresource integrity feature by specifying a base64-encoded cryptographic hash of a resource (file) you’re telling the browser to fetch, in the value of the integrity attribute of any <script> or <link> element. an integrity value begins with at least one string, with each string including a prefix indicating a particular hash algorithm (currently the allowed prefixes are sha256, sha384, and sha512), followed by a dash, and ending with the actual base...
...ptographic hash of a resource (file) you’re telling the browser to fetch, in the value of the integrity attribute of any <script> or <link> element. ...
...e string, with each string including a prefix indicating a particular hash algorithm (currently the allowed prefixes are sha256, sha384, and sha512), followed by a dash, and ending with the actual base64-encoded hash. note: an integrity value may contain multiple hashes separated by whitespace. a resource will be loaded if it matches one of those hashes. example integrity string with base64-encoded sha384 hash: sha384-oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc so oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc is the "hash" part, and the prefix sha384 indicates that it's a sha384 hash. note: an integrity value's "hash" part is, strictly speaking, a cryptographic digest formed by applying a particular hash function to some input (for example, a sc...
...-a 384 filename.js | awk '{ print $1 }' | xxd -r -p | base64 notes: the pipe-through-xxd step takes the hexadecimal output from shasum and converts it to binary. the pipe-through-awk step is necessary because shasum will pass the hashed filename in its output to xxd. that can have disastrous consequences if the filename happens to have valid hex characters in it — because xxd will also decode that and pass it to base64. additionally, the sri hash generator at https://www.srihash.org/ is an online tool you can use to generate sri hashes. cross-origin resource sharing and subresource integrity for subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using cross-origin resource...
Types of attacks - Web security
e, to steal login credentials or to get the user's unwitting permission to install a piece of malware. (click-jacking is sometimes called "user interface redressing", though this is a misuse of the term "redress".) cross-site request forgery (csrf) cross-site scripting (xss) cross-site scripting (xss) is a security exploit which allows an attacker to inject into a website malicious client-side code. this code is executed by the victims and lets the attackers bypass access controls and impersonate users. according to the open web application security project, xss was the seventh most common web app vulnerability in 2017. these attacks succeed if the web app does not employ enough validation or encoding. the user's browser cannot detect the malicious script is untrustworthy, and so gives it ...
...nsitive site-specific information, or lets the malicious script rewrite the html content. cross-site scripting attacks usually occur when 1) data enters a web app through an untrusted source (most often a web request) or 2) dynamic content is sent to a web user without being validated for malicious content. the malicious content often includes javascript, but sometimes html, flash, or any other code the browser can execute. the variety of attacks based on xss is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to a webpage controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site. xss attacks can be put into three cate...
...also called non-persistent), or dom-based. stored xss attacks the injected script is stored permanently on the target servers. the victim then retrieves this malicious script from the server when the browser sends a request for data. reflected xss attacks when a user is tricked into clicking a malicious link, submitting a specially crafted form, or browsing to a malicious site, the injected code travels to the vulnerable website. the web server reflects the injected script back to the user's browser, such as in an error message, search result, or any other response that includes data sent to the server as part of the request. the browser executes the code because it assumes the response is from a "trusted" server which the user has already interacted with. dom-based xss attacks the pay...
... wikipedia mentions a good example for csrf. ...
Web security
content security content security policy (csp) content security policy (csp) is an added layer of security that helps to detect and mitigate certain types of attacks, including cross-site scripting (xss) and data injection attacks. ...
... content security content security policy (csp) content security policy (csp) is an added layer of security that helps to detect and mitigate certain types of attacks, including cross-site scripting (xss) and data injection attacks. ...
... reference lists the web platform features available only in secure contexts. weak signature algorithms the strength of the hash algorithm used in signing a digital certificate is a critical element of the security of the certificate. this article provides some information about signature algorithms known to be weak, so you can avoid them when appropriate. redirection with 301 and 302 response codes to be written data security using http cookies an http cookie (web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. the browser may store it and send it back with later requests to the same server. typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example. local storage the window obje...
...ity (sri) is a security feature that enables browsers to verify that resources they fetch (for example, from a cdn) are delivered without unexpected manipulation. it works by allowing you to provide a cryptographic hash that a fetched resource must match. http access-control-allow-origin the access-control-allow-origin response header indicates whether the response can be shared with requesting code from the given origin. http x-content-type-options the x-content-type-options response http header is a marker used by the server to indicate that the mime types advertised in the content-type headers should not be changed and be followed. this is a way to opt out of mime type sniffing, or, in other words, to say that the mime types are deliberately configured. clickjacking protection in...
Caching compiled WebAssembly modules - WebAssembly
ed data on the client-side. it is ideal for persisting assets locally for the saved state of an application, including text, blobs, and any other type of cloneable object. this includes compiled wasm modules (webassembly.module javascript objects). setting up a caching library because indexeddb is a somewhat old-fashioned api, we wanted to provide a library function to speed up writing caching code, and make it work better along with today's more modern apis. in our wasm-utils.js library script, you'll find instantiatecachedurl() — this function fetches the wasm module at url with a version of dbversion, instantiates it with the given importobject, and returns a promise resolving to the finished wasm instance. additionally, it handles creating a database to cache the compiled wasm module...
... wasm instance. additionally, it handles creating a database to cache the compiled wasm modules in, attempts to store new modules 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'; settin...
... if opening the database failed (for example due to permissions or quota), we fall back to simply fetching and compiling the module and don't try to store the results (since there is no database to store the...
...module is updated or moved to a different url. the url of the wasm module you want to instantiate. an import object, if required. const wasmcacheversion = 1; instantiatecachedurl(wasmcacheversion, 'test.wasm').then(instance => console.log("instance says the answer is: " + instance.exports.answer()) ).catch(err => console.error("failure to instantiate: " + err) ); you can find the source code for this example on github as indexeddb-cache.html (see it live also). browser support at the moment, this technique will work in firefox and edge, as they both have support for structured cloning of webassembly modules. chrome has support implemented behind the webassembly structured cloning support flag, but is yet to turn it on by default because of some concerns (see this discussion, for e...
Index - WebAssembly
it is also designed to run alongside javascript, allowing both to work together. ...
...y, compile, wasm caching is useful for improving the performance of an app — we can store compiled webassembly modules on the client so they don't have to be downloaded and compiled every time. this article explains the best practices around this. 3 compiling a new c/c++ module to webassembly c, c++, compiling, emscripten, webassembly, wasm when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten. let’s look at how it works. 4 compiling an existing c module to webassembly c++, compiling, emscripten, webassembly, wasm a core use-case for webassembly is to take the existing ecosystem of c libraries and allow developers to use them on the web. 5 compiling from r...
...ripten. let’s look at how it works. 4 compiling an existing c module to webassembly c++, compiling, emscripten, webassembly, wasm a core use-case for webassembly is to take the existing ecosystem of c libraries and allow developers to use them on the web. 5 compiling from rust to webassembly compiling, webassembly, rust, wasm if you've written some rust code, you can compile it into webassembly! this tutorial takes you through all you need to know to compile a rust project to wasm and use it in an existing web app. 6 converting webassembly text format to wasm webassembly, assembly, conversion, text format, wabt, wasm, wast2wasm, wat2wasm webassembly has an s-expression-based textual representation, an intermediate form designed t...
...7 exported webassembly functions guide, javascript, webassembly, export, exported functions, exported wasm functions, wasm exported webassembly functions are how webassembly functions are represented in javascript. this article describes what they are in a little more detail. 8 index index, webassembly found 12 pages: 9 loading and running webassembly code fetch, javascript, webassembly, xmlhttprequest, bytecode to use webassembly in javascript, you first need to pull your module into memory before compilation/instantiation. this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. 10 understanding webassembly text format ...
Private Properties - Archive of obsolete content
getthumbnail(image) { let thumbnail = thumbnails[image]; if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails[image] = thumbnail; } return thumbnail; } there are two problems with the above approach. first, it's not possible to use objects as keys. when an object is used as a key, it's converted to a string using its tostring method. to make the above code work, a unique identifier must be associated with each image and override its tostring method. the second problem is more severe: the thumbnail cache maintains a strong reference to each thumbnail object, so they will never be freed, even when their corresponding image has gone out of scope. this is a memory leak waiting to happen. the above two problems are exactly what weakmaps were designed t...
...thumbnail(image); thumbnails.set(image, thumbnail); } return thumbnail; } this version suffers from none of the problems we mentioned earlier. when a thumbnail's image goes out of scope, the weakmap ensures that its entry in the thumbnail cache will eventually be garbage collected. as a final caveat: the image cache created earlier suffers from the same problem, so for the above code to work properly, the image cache must be rewritten using weakmaps too. from weakmap to namespace in the previous section, a separate weakmap was used to associate each private property with an object. this is cumbersome if the number of private properties becomes large. a better solution would be to store all private properties on a single object, called a namespace, and then store the namespa...
...nd its internal namespace. keeping the namespace hidden from all functions, except members of point, effectively implements private properties. moreover, because members of point have a reference to the internal namespace, they can access private properties on other instances of point. namespaces in the add-on sdk the add-on sdk is built on top of xpcom, the interface between javascript and c++ code. since xpcom allows the user to do virtually anything, security is very important. among other things, add-ons should not be able to access variables that are supposed to be private. the sdk uses namespaces internally to ensure this. as always with code that is heavily reused, the sdk defines a helper function to create namespaces. it's defined in the module "core/namespace", and it's use is stra...
Two Types of Scripts - Archive of obsolete content
on the web, javascript executes in the context of a web page, and has access to that page's dom content. this enables you to call functions like: window.alert("hello there"); in an add-on's main scripts you can't do that, because the add-on code does not execute in the context of a page, and the dom is therefore not available. if you need to access the dom of a particular page, you need to use a content script. so there are two distinct sorts of javascript scripts you might include in your add-on and they have access to different sets of apis. in the sdk documentation we call one sort "add-on code" and the other sort "content scripts". add-on code this is the place where the main logic of your add-on is implemented. your add-on is implemented as a collection of one or more commonjs mod...
...ing apis defined by some of the sdk's modules such as page-mod and panel. content scripts may be supplied as literal strings or maintained in separate files and referenced by filename. if they are stored in separate files you should store them under the data directory under your add-on's root. to learn all about content scripts read the working with content scripts guide. api access for add-on code and content scripts the table below summarizes the apis that are available to each type of script. api add-on code content script the global objects defined in the core javascript language, such as math, array, and json. see the reference at mdn. ✔ ✔ the require() and exports globals defined by version 1.0 of the commonjs module speci...
...d exports to export functionality from your module. if require() is available, then so are the modules supplied in the sdk. ✔ ✘ the console global supplied by the sdk. ✔ ✔ globals defined by the html5 specification, such as window, document, and localstorage. ✘ ✔ the self global, used for communicating between content scripts and add-on code. see the guide to communicating with content scripts for more details. ✘ ✔ ...
Guides - Archive of obsolete content
modules learn about the module system used by the sdk (which is based on the commonjs specification), how sandboxes and compartments can be used to improve security, and about the built-in sdk module loader, known as cuddlefish. ...
...ors and prototypes, and about the helper functions provided by the sdk to simplify this. private properties learn how private properties can be implemented in javascript using prefixes, closures, and weakmaps, and how the sdk supports private properties by using namespaces (which are a generalization of weakmaps). content processes the sdk was designed to work in an environment where the code to manipulate web content runs in a different process from the main add-on code. this article highlights the main features of that design. testing the add-on sdk learn how to run the add-on sdk test suites. sdk infrastructure module structure of the sdk the sdk, and add-ons built using it, are of composed from reusable javascript modules. this explains what these modules are, how to ...
...ncluding the stability ratings for apis. program id the program id is a unique identifier for your add-on. this guide explains how it's created, what it's used for and how to define your own. firefox compatibility working out which firefox releases a given sdk release is compatible with, and dealing with compatibility problems. sdk idioms working with events write event-driven code using the the sdk's event emitting framework. content scripts guide an overview of content scripts, including: what they are, what they can do, how to load them, how to communicate with them. two types of scripts this article explains the differences between the apis available to your main add-on code and those available to content scripts. xul migration xul migration guide te...
context-menu - Archive of obsolete content
d pass their urls using the contentscriptfile property. see working with content scripts for more information. warning: unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. show an "edit page source" item when the user right-clicks a non-interactive part of the page: require("sdk/context-menu").item({ label: "edit page source", contentscript: 'self.on("click", function (node, data) {' + ' self.postmessage(document.url);' + '});', onmessage: function (pageurl) { editsource(p...
...ssociated with the menu item during creation. contentscriptfile the url of a content script or the array of such urls associated with the menu item during creation. events message if you listen to this event you can receive message events from content scripts associated with this menu item. when a content script posts a message using self.postmessage(), the message is delivered to the add-on code in the menu item's message event. arguments value : listeners are passed a single argument which is the message posted from the content script. the message can be any json-serializable value. menu a labeled menu item that expands into a submenu. methods additem(item) appends a menu item to the end of the menu. if the item is already contained in another menu or in the top-level context men...
... scripts associated with the menu during creation. contentscriptfile the url of a content script or the array of such urls associated with the menu during creation. events message if you listen to this event you can receive message events from content scripts associated with this menu item. when a content script posts a message using self.postmessage(), the message is delivered to the add-on code in the menu item's message event. arguments value : listeners are passed a single argument which is the message posted from the content script. the message can be any json-serializable value. separator a menu separator. separators can be contained only in menus, not in the top-level context menu. methods destroy() permanently removes the separator from its parent menu and frees its resourc...
l10n - Archive of obsolete content
note that you can't currently use localize strings appearing in content scripts or html files, but you can share the localized strings you want by assigning it's values to a json serializable object. globals functions get(identifier, count, placeholder1...n) this function takes a string parameter which it uses as an identifier to look up and return a localized string in the locale currently set for firefox. localized strings are supplied by the add-on developer in .properties files stored in the add-ons "locale" directory. ...
...oper in .properties files stored in the add-ons "locale" directory. the gettext tools uses "_" for the name of the function that retrieves localized strings. ...
...n a .properties file for the current locale containing an entry like: hello_string= hello! and the following code: var _ = require("sdk/l10n").get; console.log(_("hello_string")); the following output will be logged: info: hello! if this function can't find the string referenced by the identifier parameter, it returns the identifier itself. this enables you to write functional, localizable code without localizing any strings - just make the identifiers the default language: var _ = require("sdk/l10n").get; console.log(_("hello!")); however, this will make it more difficult to maintain your code if you have many localizations, because any changes to the identifier values break all your .properties files. if you're supplying different localizations for a string depending on the number ...
self - Archive of obsolete content
access data that is bundled with the add-on, and add-on metadata. note that the self module is completely different from the global self object accessible to content scripts, which is used by a content script to communicate with the add-on code. globals properties uri this property represents an add-on associated unique uri string. this uri can be used for apis which require a valid uri string, such as the passwords module. id this property is a printable string that is unique for each add-on. ...
... uri this property represents an add-on associated unique uri string. this uri can be used for apis which require a valid uri string, such as the passwords module. id this property is a printable string that is unique for each add-on. it comes from the id property set in the package.json file in the main package (i.e. the package in which you run jpm xpi). while not generally of use to add-on code directly, it can be used by internal api code to index local storage and other resources that are associated with a particular add-on. name this property contains the add-on's short name. it comes from the name property in the main package's package.json file. version this property contains the add-on's version string. it comes from the version property set in the package.json file in the mai...
...ful for data that can be displayed directly in a content frame. the url can be passed to a content frame constructor, such as the panel: var self = require("sdk/self"); var mypanel = require("sdk/panel").panel({ contenturl: self.data.url("myfile.html") }); mypanel.show(); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: var mypanel = require("sdk/panel").panel({ contenturl: "./myfile.html" }); mypanel.show(); parameters name : string the filename to be read, relative to the package's data directory. each package that uses the self module will see its own data directory. returns string : resource:// url pointing to the given location under data. ...
core/heritage - Archive of obsolete content
if (!(this instanceof dog)) return new dog(name); this.name = name; }; // to define methods you need to make a dance with a special 'prototype' // property of the constructor function. ...
...type); // if you want correct instanceof behavior you need to make a dance with // another special `constructor` property of the `prototype` object. object.defineproperty(pet.prototype, 'constructor', { value: pet }); // finally you can define some properties. pet.prototype.call = function(name) { return this.name === name ? this.bark() : ''; }; since sdk apis may be interacting with untrusted code an extra security measures are required to guarantee that documented behavior can't be changed at runtime. to do that we need to freeze constructor's prototype chain to make sure functions are frozen: object.freeze(dog.prototype); object.freeze(pet.prototype); note: also, this is not quite enough as object.prototype stays mutable & in fact we do little bit more in sdk to address that, but it's ...
...lize: function initialize(name) { this.name = name; }, type: 'dog', bark: function bark() { return 'ruff! ruff!' } }); note: we use term class to refer an exemplar constructs in a form of constructor functions with a proper prototype chain setup. constructors created using class function don't require new keyword (even though it can be used) for instantiation. also, idiomatic sdk code does not uses optional new keywords, but you're free to use it in your add-on code: var fluffy = dog('fluffy'); // instatiation fluffy instanceof dog // => true fluffy instanceof class // => true as you could notice from example above classes created via class function by default inherits from a class itself. also you could specify which class you want to inherit from by passing...
remote/child - Archive of obsolete content
the sdk/remote/child module is for these "child process modules". ...
...tent property that's the top-level dom window for the frame, and addeventlistener/removeeventlistener functions that enable you to listen to dom events dispatched by the frame. communicating with the parent process to communicate with the parent process, the process, frames, and frame objects in sdk/remote/child have a port object that you can use to receive messages from, and send messages to, code in the parent. see the documentation for sdk/remote/parent for more details. globals properties process a process object. frames a frames object. process a link to the main process. properties port an event emitter that sends and receives events from the main process. isremote a boolean property indicating whether this process is remote from the main process or not. frames a list ...
...patched by this content frame. this can include load and unload events from any content that is loaded in the frame. listeners are automatically removed when this frame is destroyed. removeeventlistener(event, listener, iscapturing) removes an event listener that was previously registered. properties port an event emitter that can be used to send and receive frame specific events to and from code in the main process. content the top level dom window currently displaying in this frame. istab a boolean property indicating whether this frame displays in one of the application's main browser tabs. events detach event emitted when this frame disconnects from the application. ...
cfx - Archive of obsolete content
or the specified package. called with no options this command will look for a file called package.json in the current directory. if package.json exists, cfx will load the corresponding add-on, load from the tests directory any modules that start with the word test- and run the unit tests they contain. note the hyphen after "test" in the module name. cfx test will include a module called "test-mycode.js", but will exclude modules called "test_mycode.js" or "testmycode.js". see the tutorial on unit testing and the reference documentation for the assert module for details. supported options as with cfx run you can use options to control which host application binary version to use, and to select a profile. you can also control which tests are run: you can test dependent packages, filter the...
... will run a number of test add-ons that are packaged with the sdk. this accepts the same options as cfx test. cfx testpkgs this will test all of the available commonjs packages. note that the number of tests run and their success depends on what application they are run with, and which binary is used. this accepts the same options as cfx test. cfx testex this will test all available example code. note that the number of tests run and their success depends on what application they are run with, and which binary is used. this accepts the same options as cfx test. cfx testall this will test everything: the cfx tool, all available commonjs packages, and all examples. this accepts the same options as cfx test. using --profiledir by default, cfx run and cfx test use a new profile each ti...
...on options can be used for all of the run, build, and test tools. if "default" is defined in the local.json cfx will use that configuration unless otherwise specified. passing static arguments you can use the cfx --static-args option to pass arbitrary data to your program. this may be especially useful if you run cfx from a script. the value of --static-args must be a json string. the object encoded by the json becomes the staticargs property of the system module. the default value of --static-args is "{}" (an empty object), so you don't have to worry about checking whether staticargs exists in system. for example, if your add-on looks like this: var system = require("sdk/system"); console.log(system.staticargs.foo); and you run cfx like this: cfx run --static-args="{ \"foo\": \"hel...
Add a Context Menu Item - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. to add items and submenus to the firefox context menu, use the context-menu module. here's an add-on that adds a new context menu item. the item is displayed whenever something in the page is selected. ...
...ay the item when something on the page is selected. if these simple contexts aren't enough, you can define more sophisticated contexts using scripts. contentscript this attaches a script to the item. in this case the script listens for the user to click on the item, then sends a message to the add-on containing the selected text. ...
...this is a url pointing to a 16x16 icon that's displayed at the left side of the context menu item. ...
Implementing the widget - Archive of obsolete content
get's content script and its two icons. inside the data subdirectory create another subdirectory widget. we'll keep the widget's files here. this hierarchy isn't mandatory; you could just keep them all under data. but it seems tidier this way. the widget's content script the widget's content script just listens for left- and right- mouse clicks and posts the corresponding message to the add-on code: this.addeventlistener('click', function(event) { if(event.button == 0 && event.shiftkey == false) self.port.emit('left-click'); if(event.button == 2 || (event.button == 0 && event.shiftkey == true)) self.port.emit('right-click'); event.preventdefault(); }, true); save this in your data/widget directory as widget.js. the widget's icons you can copy the widget's icons from her...
....shiftkey == true)) self.port.emit('right-click'); event.preventdefault(); }, true); save this in your data/widget directory as widget.js. the widget's icons you can copy the widget's icons from here: or, if you're feeling creative, you can make your own icons. either way, save them in your data/widget directory. ...
... toggleactivation() ? data.url('widget/pencil-on.png') : data.url('widget/pencil-off.png'); }); widget.port.on('right-click', function() { console.log('show annotation list'); }); } the annotator is inactive by default. it creates the widget and responds to messages from the widget's content script by toggling its activation state. since we don't have any code to display annotations yet, we just log the right-click events to the console. now from the annotator directory type cfx run. you should see the widget in the add-on bar: left- and right-clicks should produce the appropriate debug output, and a left-click should also change the widget icon to signal that it is active. next we'll add the code to create annotations. ...
Getting Started (jpm) - Archive of obsolete content
ill be used to create your add-on's package.json file. for now, just press enter to accept the default for each property. for more information on jpm init, see the jpm command reference. once you've supplied a value or accepted the default for these properties, you'll be shown the complete contents of "package.json" and asked to accept it. implementing the add-on now you can write the add-on's code. ...
...accepted the default for these properties, you'll be shown the complete contents of "package.json" and asked to accept it. implementing the add-on now you can write the add-on's code. unless you've changed the value of "entry point" ("main" in package.json), this goes in "index.js" file in the root of your add-on. this file was created for you in the previous step. ...
...it to initialize an empty add-on template jpm run to run a new instance of firefox with the add-on installed, so we can try it out jpm xpi to package the add-on into an xpi file for distribution these are the three main commands you'll use when developing sdk add-ons. there's comprehensive reference documentation covering all the commands you can use and all the options they take. the add-on code itself uses two sdk modules, action button and tabs. there's reference documentation for all the high-level and low-level apis in the sdk. what's next? to get a feel for some of the things you can do with the sdk apis, try working through some of the tutorials. ...
Modifying Web Pages Based on URL - Archive of obsolete content
rial you'll need to have learned the basics of jpm. to modify any pages that match a particular pattern (for example, "http://example.org/") as they are loaded, use page-mod module. to create a page-mod, you need to specify two things: one or more content scripts to run whose job is to interact with web content. one or more patterns to match urls for the pages you want to modify. ...
...mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscript: 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";' }); do as follows: create a new directory and navigate to it. run jpm init, accepting all the defaults open the file index.js and add the code above run jpm run open ietf.org in the browser window that opens. below is what you should see. specifying the match pattern match pattern uses match-pattern syntax. you can pass a single match-pattern string, or an array. keeping the content script in a separate file in the example above, we've supplied content script as a string. unless the script is extremely simple, maintain the sc...
...er window that opens. below is what you should see. specifying the match pattern match pattern uses match-pattern syntax. you can pass a single match-pattern string, or an array. keeping the content script in a separate file in the example above, we've supplied content script as a string. unless the script is extremely simple, maintain the script as a separate file though. this makes the code easier to maintain, debug, and review. to do this, you need to: save the script in add-on's data directory. use contentscriptfile option instead of contentscript and pass it script url which can be obtained using self.data.url("my-script.js"). from firefox 34 onwards, you can just use "./my-script.js" instead. for example, if we save the script above under the add-on's data directory in a f...
Bookmarks - Archive of obsolete content
(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method. for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it. specifying default_index as the index at which to insert the new folder places it at the end of the list. you can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksmenufolder to another folder attribute. creating a new bookmark to create a new bookmark, ...
...f a site and wish to find all bookmarks that link to it, you can use the nsinavbookmarksservice.getbookmarkidsforuri() method. var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var bookmarksarray = bmsvc.getbookmarkidsforuri(uri, {}); after executing this code, the array bookmarksarray contains the ids of all bookmarks that refer to the specified uri (in this case, "http://google.com"). manipulating existing items there are a number of convenient methods you can use to make changes to existing bookmarks and bookmark folders. this section covers some of them. the item title to change the title of a bookmark or bookmark folder, you use the nsinavbook...
...title to change the title of a bookmark or bookmark folder, you use the nsinavbookmarksservice.setitemtitle() method. bmsvc.setitemtitle(newbkmkid, "new title"); this sets the title of the item referenced by the id newbkmkid to "new title". you can fetch the current title of an item using the nsinavbookmarksservice.getitemtitle() method: var thistitle = bmsvc.getitemtitle(newbkmkid); this code will display an alert containing the title of the item referenced by the id newbkmkid. the item uri similarly, you can obtain the uri corresponding to a given bookmark item by calling the nsinavbookmarksservice.getbookmarkuri() method. var thisuri = bmsvc.getbookmarkuri(newbkmkid); assuming you've run all the code samples previous to this one, this will output "http://google.com". you can u...
Modules - Archive of obsolete content
some simple code to turn a javascript module into non-mozilla-specific code (e.g., if porting to the browser). the use of eval() will probably not be of concern because it is only being used on the exported_symbols array which should not depend on user input. function importmodule (thatobj) { thatobj = thatobj || window; var exported_symbols = [ // put the symbols here ]; // your code here... ...
...nto non-mozilla-specific code (e.g., if porting to the browser). the use of eval() will probably not be of concern because it is only being used on the exported_symbols array which should not depend on user input. function importmodule (thatobj) { thatobj = thatobj || window; var exported_symbols = [ // put the symbols here ]; // your code here... // at the end of your code: (assuming neither 'i' nor 'thatobj' is being exported!) for (var i=0; i < exported_symbols.length; i++) {thatobj[exported_symbols[i]] = eval(exported_symbols[i]);} } or for one-time-only usage of a module: (function (thatobj) { thatobj = thatobj || window; var exported_symbols = [ // put the symbols here ]; // your code here... ...
...of your code: (assuming neither 'i' nor 'thatobj' is being exported!) for (var i=0; i < exported_symbols.length; i++) {thatobj[exported_symbols[i]] = eval(exported_symbols[i]);} } or for one-time-only usage of a module: (function (thatobj) { thatobj = thatobj || window; var exported_symbols = [ // put the symbols here ]; // your code here... ...
Progress Listeners - Archive of obsolete content
note that onpageload does not fire for back button clicks. ...
...note that the browser uses a weak reference to your listener object, so make sure to keep an external reference to your object to ensure that it stays in memory. when used with a tabbrowser, you ca...
...hunderbird 3.3 / seamonkey 2.1), all events are optional. the tabbrowser only notifies you of the events for which you provide a callback. remember to change mylistener to a unique identifier. example: notification when the value in address bar changes a commonly asked question is how to get notified whenever the url in the address bar (also known as location bar) changes. using the following code, you will get notified when user navigates to another page (by clicking a link, using the back/forward button, by typing an address in the location bar, etc.) and also when user switches tabs. var myextension = { oldurl: null, init: function() { gbrowser.addprogresslistener(this); }, uninit: function() { gbrowser.removeprogresslistener(this); }, process...
Extension Versioning, Update and Compatibility - Archive of obsolete content
in h1, h2, h3, p and li tags you may use: b or strong for bolder text i or em for italicized text formatting in firefox 4 and later from firefox 4 the restrictions are relaxed somewhat. the following tags are interpreted normally: h1, h2 and h3 for general headings p, div, pre and blockquote for block formatting ul, ol, li, dl, dt and dd for lists b, i, em, strong, u, q, sub, sup and code for text formatting br and hr for line breaking the head, style and script tags and any of their contents are completely stripped. other tags aren't included in the result but do have their contents displayed, so the following snippet: <span><q>text</q></span> would be rendered exactly the same as: <q>text</q> sample file <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http:/...
...ons retrieving it. the mccoy tool should be used to sign the update rdf. the technical details of the signing mechanism are beyond the scope of this document however the basics are as follows: step 1 - done once, before you publish your add-on the target: adding updatekey in install.rdf the add-on author creates a public/private rsa cryptographic key pair. the public part of the key is der encoded and then base 64 encoded and added to the add-on's install.rdf as an updatekey entry. step 2 - done every time you change your "update.rdf" file the target: setting value to signature in update.rdf when the author creates the update rdf file a tool is used to sign it using the private part of the key. roughly speaking the update information is converted to a string, then hashed using a sha512...
...2 - done every time you change your "update.rdf" file the target: setting value to signature in update.rdf when the author creates the update rdf file a tool is used to sign it using the private part of the key. roughly speaking the update information is converted to a string, then hashed using a sha512 hashing algorithm and this hash is signed using the private key. the resultant data is der encoded then base 64 encoded for inclusion in the update.rdf as an signature entry. debugging and solving problems the update mechanism logs information to the console, and display various information which can help you to find problem. to enable the log: set the value of extensions.logging.enabled to true (using url about:config) run firefox from command with option -console if you encounter pr...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
you could also use the old style parameter block ({ "foo": aevent.target.href }) if you wanted - and didn't have an icon to use for the confirmation dialog. installtrigger.install is then called to install the item with the parameter block. return false; this last part is the most important - the install function must return false so that when...
...f you may be calling before you call installtrigger.install. this is not necessary as install calls updateenabled itself internally. furthermore, calling updateenabled may lead to problems if your distribution site is not in the user's whitelist, because firefox only displays the "installation blocked" message when install or installchrome are called, or when a xpi file is loaded. so, if you have code that looks like this: if (installtrigger.updateenabled()) installtrigger.install({"foo": "foo.xpi"}); ... and your site is not in the whitelist, when the user invokes that code, updateenabled will return false because your site isn't whitelisted, and since it was updateenabled that discovered this, not a call to install, there will be no notification to the user. thus you should only use up...
...s that code, updateenabled will return false because your site isn't whitelisted, and since it was updateenabled that discovered this, not a call to install, there will be no notification to the user. thus you should only use updateenabled to display content in the page to alert the user that software installation is disabled, or your site is not in the whitelist—do not place it in the install code path. (* by all means don't let this stop you from developing more ambitious install systems, i am providing this documentation only as a guide that i hope most extension distributors will use since it handles most cases well) ...
Jetpack Processes - Archive of obsolete content
perties are the primary means through which context can be provided for messages; for instance, if the handle is meant to represent a network request, an xmlhttprequest instance can be attached to the handle on the chrome process. because a handle's existence crosses process boundaries and cross-process garbage collection does not exist, the lifetime of a handle needs to be controlled manually by code. by default, a handle is rooted in the javascript interpreter's garbage collector, meaning that even if a process throws it away, it will not be garbage collected unless the other process explicitly does something to indicate that it is no longer needed. if that other process does not do something explicit and simply removes all references to it, the handle remains rooted yet unreachable in both ...
...see also nsijetpackservice nsijetpack ...
...nidump is available, the context.dumpid property will list the minidump id of the crash report that was collected. core:exception(error) when an exception occurs in a jetpack script and is not caught, this message is sent to the parent. the error object contains the following properties: filename, linenumber, and message. history see bug 556846 and bug 578821 for details. sample code for example code, check out the unit tests. see also nsijetpackservice nsijetpack ...
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. ...
... develop firefox extensions. the role of each technology firefox is largely built using four technologies: xul, css, javascript, and xpcom. extensions are also built using these four technologies. figure 1: role of each technology in firefox in addition to these technologies, extension development will require you to learn about how to confer privileges to overcome security restrictions on code that you write, and how to embed your code into the firefox ui. these issues are discussed in chapter 5. the minimum knowledge required in the interest of brevity, i will omit explanations of widely understood technologies, and focus instead on introducing new technologies you will need to understand in order to develop for firefox. i will assume that you have experience developing with dynamic...
... structure of the data, expressed through html or xml, and the display style, indicated by css, data can be reused better than it is when structural and stylistic markup are both embedded in html. there are three css specifications (level 1 through level 3), with progressively powerful features. the gecko rendering engine handles nearly all of css level 2 and some of css level 3. listing 2: css code sample body { color: black; background-color: white; } p { margin-bottom: 1em; text-indent: 1em; } javascript: the world's most misunderstood language javascript is a scripting language first developed in the 1990s, at which time it was created as a way to add dynamic features to web pages. because it was often used at first to display pop-up windows, marching text in status bars, or ...
Performance best practices in extensions - Archive of obsolete content
appearance of the user's desired content. load only what you need, when you need it don't load things during startup that are only needed if the user clicks a button, or if a given preference is enabled when it's not. if your extension has features that only work when the user has logged into a service, don't load the resources for those features until the user actually logs in. use javascript code modules you can create your own javascript code modules incorporating sets of features that are only needed under specific circumstances. this makes it easy to load chunks of your extension on the fly as needed, instead of loading everything all at once. while javascript modules can be extremely useful, and provide significant performance benefits, they should be used wisely. loading modules in...
... defer everything that you can most extensions have a load event listener in the main overlay that runs their startup functions. do as little as possible here. ...
...at are only needed under specific circumstances. this makes it easy to load chunks of your extension on the fly as needed, instead of loading everything all at once. while javascript modules can be extremely useful, and provide significant performance benefits, they should be used wisely. loading modules incurs a small cost, so breaking code up to an unnecessary degree can be counter-productive. code should be modularized to the extent that doing so increases clarity, and loading of large or expensive chunks of code fragments can be significantly deferred. defer everything that you can most extensions have a load event listener in the main overlay that runs their startup functions. do as little as possible here. the browser window is blocked while your add-on's load handler runs, so the mor...
Security best practices in extensions - Archive of obsolete content
ges. regardless of where the document comes from, you can further restrict what it can do by applying properties to the document holder, known as the docshell. frame.docshell.allowimages = false; frame.docshell.allowjavascript = false; frame.docshell.allowplugins = false; there are more examples listed in the document listed above in this section. in certain circumstances you may want to run code in your extension, but you would like to give it restricted privileges. one of the best ways to do this is to use components.utils.evalinsandbox(). note that objects passed into the sandbox are restricted, but objects that come back out from it are not. refer to the document to find out how to avoid such pitfalls. for more information, refer to the evalinsandbox section. the sidebar: a use case ...
...se case the sidebar in firefox is designed to hold both chrome (privileged) content and web (nonprivileged) content, the latter being in the form of web pages. these web pages can come from a server, or come from local html files bundled with the extension. for pages coming from the server, you need to take steps to ensure that the content can not call back into the web browser and run malicious code. the main way to do this is by creating an iframe or browser element in the sidebar, and loading your content there. give the element a type="content" attribute, which essentially sandboxes the code there and blocks callback rights into chrome. using eval() in an extension using the built-in javascript eval function is frowned upon in the context of extensions. while there are some legitimate u...
...ons use the greasemonkey compiler to bundle it in their extension for convenience. if you choose to do so, beware when making edits to the bundled files so as not to break the well thought out security architecture. third-party javascript in the context of web sites, using javascript written by others is very common. it is not unheard of in add-ons as well, and can provide a useful way to avoid code duplication and accelerate development. this article is about websites, but gives some insights into the general risks. when you do include other scripts, there are a number of things you can do to ensure their integrity and safety for users. the first is to always get it from a trusted source. another thing you should do is namespace it just in case other add-ons include it. for example, if you'...
Setting up an extension development environment - Archive of obsolete content
enables the use of the dump() statement to print to the standard console. see window.dump for more info. you can use nsiconsoleservice instead of dump() from a privileged script. javascript.options.strict = true. enables strict javascript warnings in the error console. note that since many people have this setting turned off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension. you can filter those with console2. devtools.chrome.enabled = true. this enables to run javascript code snippets in the chrome context of the scratchpad from the tools menu. don't forget to switch from content to browser as context. devtools.debugger.remote-enabled = true. this adds a "browser debugger" entry to the "web developer" submenu of the ...
...the devtools.chrome.enabled preference must also be set to true for the browser debugger to be enabled. devtools.debugger.prompt-connection = false. this prevents the browser debugger from prompting for connection permission every time. extensions.logging.enabled = true. ...
...ing the application.) nglayout.debug.disable_xul_fastload = true. for gecko 2.0+ (firefox 4.0+). see this bug for more information. although the bug has been closed, it is believed that this pref is still relevant. you might also want to set dom.report_all_js_exceptions = true. see exception logging in javascript for details. devtools.errorconsole.deprecation_warnings = true. detect deprecated code use. warning: never set nglayout.debug.disable_xul_fastload to true in a production environment; it exists solely to aid in debugging. in particular, add-ons should never change this preference. note: the error console is disabled by default starting in gecko 2.0. you can re-enable it by changing the devtools.errorconsole.enabled preference to true and restarting the browser. with this, jav...
Promises - Archive of obsolete content
e been deprecated. the following page contains examples of many promise-based replacement apis for common operations. these apis allow asynchronous operation to be achieved with a coding style similar to synchronous variants. the following examples make use of the task api, which harnesses generator functions to remove some of the syntactic clutter of raw promises, such that asynchronous promise code more closely resembles synchronous, procedural code. a task example like the following: components.utils.import("resource://gre/modules/task.jsm"); task.spawn(function* () { var response = yield request("login", { username: user, password: password }); if (response.messages) { try { yield publish({ username: user, messages: response.messages }); } cat...
...ostuffwith(path_1, path_2); }); sqlite first, it’s important to note that sqlite should be avoided in favor of simpler solutions, such as flat json files, under most circumstances. the io, memory, and cpu overhead added by sqlite is substantial, and in most cases outweighs the cost of dealing with flat files directly. for use cases which are not easily served by other options, or for legacy code which cannot easily be upgraded to non-relational models, the sqlite.jsm module provides a clean, promise-based interface to sqlite databases. representative example usage components.utils.import("resource://gre/modules/sqlite.jsm"); task.spawn(function* () { // open the connection. let db = yield sqlite.openconnection({ path: database_path }); try { // start a transaction...
...loaded. the contents of the file will be initially loaded into the json store’s data property. after any changes are made to this property, the save() method must be called to queue the changes to be written to disk. unless the flush() method is called, no writes will happen until a full second has elapsed between save() calls. the variable addon_id must be defined to the id of the add-on the code is being used in. this code makes use of the add-on manager helper defined above, though it can be adapted to work without it. components.utils.import("resource://gre/modules/deferredsave.jsm"); /** * handles the asynchronous reading and writing of add-on-specific json * data files. * * @param {string} the basename of the file. * @param {object} a json-compatible object which will be used...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
the file size comparison's aren't necessarily fair, because we're not comparing apples to apples-- we're comparing an old design using html, tables, and spacer gifs to a new design much richer in imagery and style. what made you decide to drop tables as a layout mechanism? it seems like most designers think that you have to have at least some tables for layout. i've been manually writing sample code for my own design prototypes for 4 or 5 years now. i used to pride myself in knowing how to reproduce any interface design down to a pixel-perfect level. a developer would tell me something wasn't possible, and i could prove otherwise every time. like other designers and html whizzes, i became a master at manipulating and troubleshooting tables, nesting them in intricate ways to produce any layou...
...t our stories exist in a database, separated from page templates and peripheral formatting. but writers, editors, and producers have been inserting stories into vignette for years sans closing paragraph (</p>) tags. unquoted attributes and uppercase html tags? we've got them in spades, and they're embedded in all past stories of the database. ...
...our engineer, aaron jones, actually ended up rebuilding the majority of our vignette templates from scratch. i ran into a steep learning curve, not with the web standards themselves, but with the quirky rendering behaviors and inconsistencies in various browsers. ...
Creating a dynamic status bar extension - Archive of obsolete content
l in the firefox status bar, by dynamically updating its content with information fetched from the web every few minutes. specifically, this sample displays a stock quote in the status bar, and, when you mouse over it, displays a tooltip containing more detailed information about the stock. concepts covered in the previous sample won't be reiterated here; instead, refer to the downloadable sample code or to the previous sample for further details. download the sample you can download a copy of this sample to look over, or to use as the basis for your own extension. or, if you've already got the code from the creating a status bar extension sample, you can follow this tutorial to update that existing code with new features. download the sample update the install manifest replace all occurrences...
...ils. update the chrome manifest the chrome manifest needs only a minor update from the previous sample; simply replace the id of the first sample, "status-bar-sample-1", with the name of the new sample, "stockwatcher". if you need to brush up, visit the chrome manifest section. ...
...lue" onclick="stockwatcher.refreshinformation()" /> </statusbar> </overlay> also, notice that the definition of the status bar panel now includes a new property, onclick, which references the javascript function that will be executed whenever the user clicks on the status bar panel. our extension will refresh the stock information display when the user clicks the panel. write the javascript code the work of fetching the stock quote and updating the status bar panel's display is handled by the javascript code in the file stockwatcher.js. unlike our previous sample, this one is implemented as an object. we do this because in future samples in this series, we're going to be doing things that are easier to do if our extension is implemented that way. we use the window.addeventlistener() dom ...
Source Navigator - Archive of obsolete content
note: this document is still in the draft state. i hope i can finish it within one day or two if i have more time. ;) --kennykaiyinyu 19:04, 10 june 2008 (pdt) what is source-navigator? (quoted from the internet) source-navigator is a source code analysis tool which lets users to edit, browse and build their projects. with it, you can edit your source code, display relationships between classes and functions and members, and display call trees. you can also build your projects, either with your own makefile, or by using source-navigator's build system to automatically generate a makefile. source-navigator works with the insight gui interface for gdb. more information can be found here --> http://sourcenav.sourceforge.net/ why worth a try? it's quite fast as compared to mxr. (i think...
...reside in -- i understand that the label here is not so self-explanatory...): <tt>~/moz1.9/mozilla</tt> (because i saved my source at ~/moz1.9/mozilla.) remember to ensure that "include subdirectories" and "build cross-reference database" are checked. then click "ok". the snavigator then begins to scan your source directories. this takes a few minutes. now you can enjoy searching the mozilla code in a faster speed. using source navigator (more later) opening a project open a terminal. type <tt>snavigator</tt> followed by striking enter. this shows the "source-navigator projects" dialog. choose the project file that you've just created and then click "open...". source navigator then loads the database and then display the following symbols window: searching a method by typing in the m...
... a terminal. type <tt>snavigator</tt> followed by striking enter. this shows the "source-navigator projects" dialog. choose the project file that you've just created and then click "open...". source navigator then loads the database and then display the following symbols window: searching a method by typing in the method name viewing the definition/declaration by highlighting the method in the code ... displaying a inheritance hierarchy ... searching a string ... ...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
zilla project. if you're wondering how microsoft used to support the np api, look for a file called plugin.ocx in your windows system directory. this 100k activex control contains the entire np api implementation and probably worked much like pluginhostctrl.dll does now. the sections below tell you how to fetch, build and use the pluginhostctrl.dll . get the source you need cvs to get the source code. assuming you have cvs somewhere in your path, type this from a command prompt: c:\> set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot c:\> set home=\temp c:\> cvs login (logging in to anonymous@cvs-mirror.mozilla.org) cvs password: anonymous c:\> cvs -z3 co mozilla/embedding/browser/activex/src/pluginhostctrl this fetches the source for the control into mozilla\embedding\browser\a...
...type this from a command prompt: c:\> set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot c:\> set home=\temp c:\> cvs login (logging in to anonymous@cvs-mirror.mozilla.org) cvs password: anonymous c:\> cvs -z3 co mozilla/embedding/browser/activex/src/pluginhostctrl this fetches the source for the control into mozilla\embedding\browser\activex\src\pluginhostctrl. you can also see the code online. build it it is quite simple to build the control locate the pluginhostctrl directory: open pluginhostctrl.dsp build "win32 debug" or another target open some of the test files under pluginhostctrl\tests in internet explorer to verify the control has built and registered correctly. the control currently reads plug-ins from your most current netscape 4.x and ie installations. there i...
...h="500" height="300"> <param name="type" value="video/quicktime"/> <param name="src" value="http://www.foobar.com/some_movie.mov"/> <!-- custom arguments --> <param name="loop" value="true"/> </object> the classid attribute tells ie to create an instance of the plug-in hosting control, the width and height specify the dimensions in pixels. you may optionally specify a codebase attribute if you have packaged the control into a cab file and wish for it to be installed automatically. the following <embed> attributes have <param> tag equivalents: <param name="type" ...> is equivalent to typespecifies the mime type of the plug-in. the control uses this value to determine which plug-in it should create to handle the content. <param name="src" ...> is equivalent to src...
Automated testing tips and tricks - Archive of obsolete content
todo: check example code in to the tree somewhere how to quit the browser on all platforms window.close() of the last open window does not quit the application on mac http://people.mozilla.com/~davel/scripts/ - look at quit.js and quit.xul install manifest file in appdir/chrome to map chrome://tests/content to directory containing quit.js and quit.xul example: content tests file:///users/davel/work/tests/ start app with command line flag -chrome chrome://tests/content/quit.xul how to create a new profile from the command line first, use the -createprofile command line flag to add a profile entry to profiles.ini and populate the new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profi...
... the -createprofile command line flag to add a profile entry to profiles.ini and populate the new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profile_dir}/testprofile" next, start firefox to populate the new profile directory with the rest of the default settings firefox-bin -p testprofile -chrome chrome://tests/content/quit.xul<code> the above process may exit before the profile is completely created. in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome pri...
...st script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentloaded event chromewindow.addeventlistener('domcontentloaded',callbackfunction,false); ...
Locked config settings - Archive of obsolete content
putting into place locked configuration settings this feature exists for mozilla and firefox, but not for thunderbird locked settings can be put into a mozilla.cfg file in the c:\program files\mozilla.org\mozilla directory. the mozilla.cfg file is an encoded file of javascript commands. the encoding is a simple "byte-shifting" with an offset of 13 (netscape 4 used a similar encoding, but with a of 7 instead). ...
... (netscape 4 used a similar encoding, but with a of 7 instead). this file also needs to be "called" from c:\program files\mozilla.org\mozilla\defaults\pref\all.js by appending the following line at the end: pref("general.config.filename", "mozilla.cfg"); note: newer versions of mozilla or firefox store the all.js file in greprefs rather than defaults\pref the moz-byteshift.pl script allows to encode...: moz-byteshift.pl -s 13 <mozilla.cfg.txt >mozilla.cfg ... and to decode mozilla.cfg files: moz-byteshift.pl -s -13 <mozilla.cfg >mozilla.cfg.txt example of an unencoded file: mozilla.cfg.txt. the lockpref command puts into place a locked preference, whereas the defaultpref command merely puts into a place a default value (which the user may override in his prefs.js file). note that the fil...
... moz-byteshift.pl script to work locally, there is also an online version available. 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. if you suspect syntax errors in your config file, you can display the exact error message by enclosing your code in a try-catch block: try { ... } catch(e) { displayerror("test", e); } clear text configuration if you don't care about encoding the mozilla.cfg file, append this config to all.js instead : pref("general.config.obscure_value", 0); pref("general.config.filename", "mozilla.cfg"); ...
Creating a Firefox sidebar extension - Archive of obsolete content
ts of xul, packaging and xpi's. it's preferable you have some basic knowledge of how xul works and how firefox handles extensions. see building an extension for more detailed information about structuring, packaging, and deploying extensions. packages extensions to firefox are installed with packages ("bundles"). an extension package usually contains a "content" provider, which contains the xul code and application logic. optionally locales and skins can be included. most additions are provided with a default tree structure, although not required it is recommended to use this structure. here the package for the sidebar is created, the files included are listed below. example 1. package structure emptysidebar \- chrome |- content |- locale | \- en-us \- skin create all folde...
...ptysidebar');" /> </broadcasterset> </overlay> the overlay file consists of three entries, the menu definition, shortcut keys and the broadcaster. the broadcaster serves two purposes. the first is it indirectly provides the arguments for the togglesidebar function. the second is it provides attributes to the menuitem, some of which are changed automatically when togglesidebar is called. see code_snippets/sidebar for more information. if the sidebar is not going to have a command-key, one can remove the openemptysidebar.commandkey and openemptysidebar.modifierskey keys from the dtd, remove the <keyset> from the firefoxoverlay.xul file. one must then set the key attribute of the menuitem to "". the extension needs to provide some special manifest files that control how it is installed an...
...idebar$ zip emptysidebar.xpi install.rdf chrome.manifest chrome/emptysidebar.jar open firefox and browse to the folder containing emptysidebar.xpi. click on the file and the extension installation window pops up. after a restart of firefox, the sidebar is installed. you can download the empty sidebar project to use as a basis for your own sidebars. the emptysidebar extension resources code snippets:sidebar building an extension creating applications with mozilla packaging firefox/thunderbird extensions creating a firefox 1 sidebar original document information author: j.c. wesdorp <jcwesdorp . at . occidopagus.nl> - may 30, 2005. updated for firefox 2 - dec 12, 2006. permission granted to migrate in jan 2006, including permission to relicense under the cc:by-sa. origin...
Getting Started - Archive of obsolete content
files. mozilla currently comes with two skins, classic and modern. looking in the directory you'll also notice that there are classic.jar and modern.jar files. for this tutorial we are going to use the classic skin as a base. extract classic.jar into \classic (\mozilla\chrome\classic), but make sure to keep the directory structure. remember if at any point you wish to revert back to the original code again, just extract this jar over top of what you've modified. now all of the css and images are extracted, but if you make some changes and run mozilla as it is, you will not see them because it's still set to look at the files in the jar files. to point mozilla at the correct files we need to open up \mozilla\chrome\installed-chrome.txt in a text editor. you should probably make a backup of thi...
...run mozilla as it is, you will not see them because it's still set to look at the files in the jar files. to point mozilla at the correct files we need to open up \mozilla\chrome\installed-chrome.txt in a text editor. you should probably make a backup of this file now, just in case you make a mistake. in the file you'll see a list. do a search for classic.jar</cde>. on every line that references <code>classic.jar we need to make some changes (there are about 5 lines). delete the bolded text: original skin,install,url,jar:resource:/chrome/classic.jar!/skin/classic/global/ modified skin,install,url,resource:/chrome/classic/skin/classic/global/ once you have made these modifications, save them and run mozilla. if mozilla runs fine, that means that it worked. if it doesn't appear as yo...
... in \myskin and call it preview.png (if it's a jpg or gif call it preview.jpg or preview.gif). make a copy of contents.rdf and place it in \myskin and open it up in your text editor. this file is a small xml database which is used to describe the skin. list all the skins being supplied by this theme <rdf:seq about="urn:mozilla:skin:root"> <rdf:li resource="urn:mozilla:skin:myskin/1.0" /> in the code search for the part listed above. change the blue part to whatever you want your theme called and then its version number. then scroll down to the next section. <rdf:description about="urn:mozilla:skin:myskin/1.0" chrome:displayname="my skin" chrome:accesskey="m" chrome:author="me" chrome:description="this is my custom skin for mozilla" chrome:name="myskin/1.0" chro...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
obsolete since gecko 4.0this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. warning: this technology is obsolete. no active maintainer has stepped forward, and the code broke in firefox 4. the code has been removed from the mozilla source tree. xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java is not that much different than doing so in c++. prerequisites java 1.4.2 or newer xulrunner 1.8.0.1 or newer embedding in order to embed mozilla in your java application, you will need to add the library mozillainterfaces.jar (located in xulrunner/sdk/lib folder) t...
... locprovider); } catch (filenotfoundexception e) { // this exception is thrown if gregrepathwithproperties cannot find a gre } catch (xpcomexception e) { // this exception is thrown if initembedding failed } locationprovider is a class provided by the java application. it implements the iappfilelocprovider interface, and tells xpcom where to find certain files and directories. if your code cannot find the gre and keeps throwing filenotfoundexceptions during the getgrepathwithproperties(...) call, check whether you already registered the gre on your system: gre registration the initembedding method kicks off the embedding process, allowing the java application to work with xpcom and mozilla. once the java application is done using mozilla, it needs to terminate the embedding proces...
....setwindowcreator(creator); in this example, we have a java class called windowcreator, which implements the nsiwindowcreator interface, and we want to register it with mozilla. to do so, we first get the service manager, through which we can get a reference to mozilla's window watcher. ...
Exception logging in JavaScript - Archive of obsolete content
in versions of firefox prior to firefox 3, all javascript exceptions were always logged into the error console if they remained unhandled at the time execution returned back into c++ code. as a result, if, for example, c++ code called a javascript component, which threw an exception, that exception would be logged to the console before control was returned to the c++ caller. this had the unintended consequence of logging "expected" errors at length into the console. javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller. these might be perfectly normal circumstances, but the exceptions were dutifully logged nonetheless. exception reporting in firefox 3 firefox 3 improves reporting of unhandled exceptions by establishing a set of rules tha...
...f unhandled exceptions by establishing a set of rules that determines whether or not an exception is worth reporting: any methods on interfaces annotated with the [function] attribute in idl (see, for example, nsidomeventlistener) that throw exceptions always report those exceptions into the error console. any exceptions that are generated by xpconnect -- that is, those exceptions whose result codes are defined in nsixpconnect.idl -- are always logged into the error console. the ns_nointerface error is never reported when returned by a javascript object's queryinterface() method on the nsisupports interface. the ns_nointerface error is never reported when returned by a javascript object's getinterface() method on the nsiinterfacerequestor interface. all other errors are reported when the...
...() method on the nsisupports interface. the ns_nointerface error is never reported when returned by a javascript object's getinterface() method on the nsiinterfacerequestor interface. all other errors are reported when the last javascript frame on the stack returns to a c++ caller without handling the exception. that last point deserves clarification. consider this call chain: here we see c++ code calling javascript, which calls back into c++, which then calls back into javascript. if the javascript in frame 4 throws an exception, the exception is returned as an error code to the c++ in frame 3. no exception will be logged to the error console in this case. that c++ may handle the error, generate a different error, or simply pass it straight back to the js in frame 2. if the javascript in ...
Layout System Overview - Archive of obsolete content
ion, stacking order). generally frames correspond to the content elements, though there is often a one-to-many correspondence between content elements and frames. layout creates frames for content based on either the specific html rules for an element or based on the css display type of the element. in the case of the html-specific elements, the frame types that correspond to the element are hard-coded, but in the more general case where the display type is needed, the layout system must determine that display type by using the style system. a content element is passed to the style system and a request is made to resolve the style for that element. this causes the style system to apply all style rules that correspond to the element and results in a resolved style context - the style data speci...
... elements. all layout happens in the context of a block, and all of the contents of a block are formatted into lines within that block. as the width of a block is changed, the contents of the lines must be reformatted. consider for example a large paragraph of text sitting in paragraph: <p> we need documentation for users, web developers, and developers working on mozilla. if you write your own code, document it. much of the existing code <b>isn’t very well documented</b>. in the process of figuring things out, try and document your discoveries. if you’d like to contribute, let us know. </p> there is one block that corresponds to the <p> element, and then a number of lines of text that correspond to the text. as the width of the block changes (due to the window being resized, for exa...
...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 the presentation shell and presentation context will be made by using the term presentation shell. the presentation shell is the root of the presentation, and as such it owns and manages a lot of layout objects that are used to create and maintain a presentation (note that the documen...
Style System Overview - Archive of obsolete content
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 ↙ ↘ nscsscolor — ...
...nherited structs act like reset ones in the descendants of any rule node for which the data are fully specified. style data cached in style context tree if a style struct for a context depends on the data in the parent context, we will cache that struct in the style context tree. this happens when properties are inherited or when percentage units are used in a way that is handled by the style code (rather than reflow). if the data are exactly the same as those of the parent, we copy the struct to the child style context and set a bit saying that it doesn't own the struct. (the context tree can be deep.) each rule node has a per-struct set of “none bits” that say that the rule node's set of rules (the rules on the path to the root) specify nothing non-inherited for the struct. style...
...ms). otherwise we'd have to walk rule tree and compare each rule node to every rule in the sheet (o(rules * rule-nodes)). when 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. w...
Gecko Coding Help Wanted - Archive of obsolete content
take a look through lxr, and you'll realize that mozilla's source code is a big place. huge, actually. overwhelmingly large. you could spend years in it and still get lost. you're up for some adventure, though, and you're set to take the plunge. but where? where's a good place to start? ...
... take a look through lxr, and you'll realize that mozilla's source code is a big place. huge, actually. overwhelmingly large. you could spend years in it and still get lost. you're up for some adventure, though, and you're set to take the plunge. but where? where's a good place to start? ...
...ugzilla can be deceptive, deceptively hard... or deceptively easy. so we've compiled a list of pointers —from the experts. there's plenty to do, and we sure could use the help. here are some fixes that are straightforward; they just need some time and attention: decomtamination convert weird, ugly and inefficient method signatures to more natural c++ method signatures. it's really improved code readability, reduced code size, and sped up performance. it's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. we've done a lot, but there's a lot more to do. roc is willing to work closely with anyone with reasonable c++ experience to get them started on this. just send him mail. not up for coding yet? join the gecko bugathon and help save gecko e...
Introducing the Audio API extension - Archive of obsolete content
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. deprecated since gecko 22 (firefox 22 / thunderbird 22 / seamonkey 2.19)this feature has been removed from the web standards. though some browsers may still support it, it is in the process of being dropped. avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. be aware that this feature may cease to work at any time. please note that this document describes a non-standard experimental api. this api has been deprecated since gecko 22, disabled since gecko 28, and removed from gecko 31. you should use the web audio api instead. reading audio streams th...
... should use the web audio api instead. reading audio streams the loadedmetadata event when the metadata of the media element is available, it triggers a loadedmetadata event. this event has the following attributes: mozchannels: number of channels mozsamplerate: sample rate per second mozframebufferlength: number of samples collected in all channels this information is needed later to decode the audio data stream. the following example extracts the data from an audio element: <!doctype html> <html> <head> <title>javascript metadata example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <script> function loadedmetadata() { channels = audio.mo...
...refore contains the raw samples of a period of time. those samples may or may not have been played yet at the time of the event and have not been adjusted for mute or volume settings on the media element. playing, pausing, and seeking the audio also affect the streaming of this raw audio data. the mozaudioavailable event has 2 attributes: framebuffer: framebuffer (i.e., an array) containing decoded audio sample data (i.e., floats) time: timestamp for these samples measured from the start in seconds the framebuffer contains an array of audio samples. it's important to note that the samples are not separated by channels; they are all delivered together. for example, for a two-channel signal: channel1-sample1 channel2-sample1 channel1-sample2 channel2-sample2 channel1-sample3 channel2-sam...
popChallengeResponse - Archive of obsolete content
rack. 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. deprecatedthis feature has been removed from the web standards. though some browsers may still support it, it is in the process of being dropped. avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. be aware that this feature may cease to work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. resultst...
...o work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. ...
...engeresponse("challengestring"); argument description "challengestring" a base-64 encoded cmmf popodeckeychallcontent message. the current implementation does not conform to that defined in the cmmf draft, and we intend to change this implementation to that defined in the cmc rfc.. see below for the current implementation. the resultstring will either be a base-64 encoded popodeckeyrespcontent message, or one of the following error strings: error string description "error:invalidparameter:xxx" the parameter xxx was an invalid value. "error:internalerror" the software encountered some internal error, such as out of memory challenge-response proof of possession expected input: popodeckeychallcontent ::= sequence of challeng...
Modularization techniques - Archive of obsolete content
the mechanism we're using is based on the principles laid down by com, so pretty much anything you know about com can be applied here, and any reference on com can provide you with more interesting and complex examples than the ones provided here. ...
...d = {0x221ffe10, 0xae3c, 0x11d1, {0xb6, 0x6c, 0x00, 0x80, 0x5f, 0x8a, 0x26, 0x76}}; why the b66c couplet gets broken up and grouped with the last set of bytes is probably a footnote somewhere. on windows you can use the programs uuidgen and guidgen, which ship with visual c++, to generate ids. a simple example it is recommended that you use xpidl to define your interfaces. this sample code should be updated to reflect this, but it gives you a good basic understanding of com from the c++ perspective. file nsisample.h nsisample.h defines an extremely simple interface and its interface id (iid). the important things to notice are that the interface inherits from nsisupports, and all member functions are pure virtual methods. #include "nsisupports.h" // {57ecad90-ae1a-11d1-b66c-00...
...// returns whether the dll can be unloaded now. extern "c" ns_export prbool nscanunload(); the implementation of nsgetfactory() in the simplest case is nearly identical to that of getsamplefactory() in our previous example. you only need to verify that the class id passed in is the correct one for the factory you implement. if your dll contains multiple factories, you'll need to add conditional code to determine which one to return. nscanunload() is an optional, but useful function. if implemented, it allows the nsrepository to free up memory by unloading dlls it is no longer using when freelibraries() is called. the implementation takes into consideration two things when deciding whether or not a dll can be unloaded: whether any of its factories are currently in use, and whether anyone has...
Prism - Archive of obsolete content
on in the tray or dock and to display pop-up notifications. customization: apps can be run using a shared browser runtime and customized using client-side script (similar to greasemonkey). custom stylesheets can be used to tweak the ui. architectural overview prism is a xulrunner application. in addition to the browser engine included in xulrunner, it consists of: web app bundle management: code for creating new web app bundles and loading existing bundles. shortcut creation ui: a dialog box lets the user specify attributes of the web app (name, uri, icon, shortcut locations). javascript api: an api that can be used by scripts inside the bundle to customize the application. we are refining this approach to make the api applicable in as many environments as possible (e.g. it might be ...
...extension directly in their web app. we would like to harmonize our api with those of similar projects such as adobe air and google gears. operating-system integration: binary components provided access to os-specific features like shortcut creation and dock/tray icons. we intend to propose these extensions for inclusion in future versions of xulrunner. firefox extension: a firefox extension, code-named "refractor", can be used to spin out new prism apps from inside the web browser. refractor adds a new menu item to call up the shortcut creation dialog for inside firefox. web apps can also point to a complete web app bundle or some elements of a web app (like higher resolution icons). refractor automatically takes this information into account. documentation ...
... files and webapp scripting, the host window can be modified. installer installing prism. view all... ...
PyDOM - Archive of obsolete content
globals and namespaces this is taken from a mail to the pyxpcom list - it should be expanded, but a copy-paste will do for now normal module semantics don't exist here. the globals are 'bound' to the global object (i.e., the window), instead of to a module's __dict__ as you expect in the python world. note that we don't actually 'import' anything here - the scripts and event handlers do not exist in a python module. the intent is to provide similar semantics to js. ...
... similar semantics to js. for example, when a top-level window has something like: <window ... script="foo = 1" ... an event handler like: <button onclick="print foo"/> should be able to reference 'foo' via globals as shown. note that you can stick arbitrary values on any dom object - this is what js calls 'expandos'. ...
...the default script type for all child elements in the window. xul use a script-type attribute on your elements. for example, <window script-type="application/x-python" .../> html <meta http-equiv="content-script-type" content="application/x-python" /> should work (but possibly doesn't - see bug 100924). but addeventlistener within a <script type="application/x-python"> block does. almost python code can not be secured - so it will only run from trusted sources. this means you can only have python code in chrome. content loaded from anywhere other than a chrome:// url can not host python. it should be obvious why you don't want to run http://evil.com/something_evil.py in your browser! inside chrome, you can use python via either html or xul. related topics pyxpcom: create and use xpcom compo...
Remotely debugging Firefox for Metro - Archive of obsolete content
prerequisites you will need: windows 8 (metro-style) firefox running in the touch-friendly "metro" mode on a windows 8 computer. firefox running in classic "desktop" mode on windows, mac os x, or linux, either on a separate computer or in a separate profile on the same computer. ...
.... press the "ok" button to continue. tip: if the remote connection times out, flip to the desktop via the desktop tile and check if windows firewall has thrown up an incoming connection permissions prompt. on the desktop next, the desktop shows you a dialog that looks something like this: this is asking whether you want to debug web content running in a browser tab, or to debug the browser code itself. you'll see one entry under "available remote tabs" for each open tab, and clicking it will attach the debugging tools to the web content hosted by that tab. if you want to debug your web content, you'll choose the relevant content tab. you'll see one entry under "available remote processes": this is the browser process itself. you'll choose this option if you want to debug the browser...
.... you'll see one entry under "available remote tabs" for each open tab, and clicking it will attach the debugging tools to the web content hosted by that tab. if you want to debug your web content, you'll choose the relevant content tab. you'll see one entry under "available remote processes": this is the browser process itself. you'll choose this option if you want to debug the browser's own code. let's choose to attach to the mozilla.org website. the toolbox will open in its own window, attached to the firefox for metro tab that's currently hosting mozilla.org: the toolbox, and the tools it hosts (including the console, debugger, style editor, profiler, etc.), work in just the same way as they do when attached to local content. ...
Actionscript Acceptance Tests - Archive of obsolete content
tp://docs.python.org/library/time.html for details) # e.g.: eastern standard time/eastern daylight time = ('est','edt') # write timezones as tuples, one to each line. ('est', 'edt') ('cst', 'cdt') ('mst', 'mdt') ('pst', 'pdt') testname.err this file is used when the test throws an uncatchable error. the first line must contain the expected error (without the extra debugger information). ...
...light time = ('est','edt') # write timezones as tuples, one to each line. ('est', 'edt') ('cst', 'cdt') ('mst', 'mdt') ('pst', 'pdt') testname.err this file is used when the test throws an uncatchable error. the first line must contain the expected error (without the extra debugger information). the exitcode is optional, but must be defined in this file if non-zero. verifyerror: error #1021 exitcode: 1 testname.exitcode file that specifies the expected exitcode. should just be an integer with nothing else. (note that if a .err file is defined, the .exitcode file will be ignored). in this example the .as test runs out of memory and so the expected exitcode is: 128 testname.out file that specifies expected output. this should only be used when it is not possible to generate the test usin...
...testname.abc_ for special cases where the .as source is not available (e.g. fuzzed files) it is possible to check in a .abc_ which will let the test harness run compiled files without source. ...
Venkman - Archive of obsolete content
it aims to provide a powerful javascript debugging environment for mozilla based browsers namely firefox, netscape 7.x/9.x and seamonkey. note that it is not included in the gecko-based browsers such as k-meleon, galeon and netscape 8.x. venkman has been provided as part of the mozilla install distribution since october 2001, as well as an extension package in xpi format. documentation venkman introduction an overview and some practical examples of using the javascript debugger in web development. using breakpoints in venkman this article describes breakpoints in javascript and how to use venkman to set and examine breakpoints. ...
...describes breakpoints in javascript and how to use venkman to set and examine breakpoints. learning the javascript debugger venkman written by svend tofte to the javascript programmers who are not familiar with other debugging tools. venkman faq answers to common questions on venkman. venkman internals notes on venkman source code. venkman development page older news and releases. view all... brief history in 1998, john bandhauer was in charge of creating the netscape 4.x javascript debugger. in order to keep things modular, he began by creating a mid-level javascript debugging api known as js/jsd. this api augments the existing javascript api, providing clients with a useful set of...
...e releases come with venkman pre-installed. on windows, it is an install option; choose advanced install. also available from firefox add-ons as an extension. nvu and kompozer javascript debugger extension version 0.9.84 is available from nvu's downloads page. we encourage you to use the latest available version 0.9.87.1 (or higher) with firefox instead. source code the source code for venkman may be found in mercurial at the following url: http://hg.mozilla.org/venkman/summary community view mozilla forums... mailing list newsgroup rss feed irc: #venkman on irc.mozilla.org report a bug in venkman if you find a problem with venkman, please follow directives mentioned at venkman faq sect...
Example Sticky Notes - Archive of obsolete content
* "this" in this context refers to the bou...
...ate(-7,12)"/> </svg:g> </svg:svg> <children/> </content> <implementation> <!-- here and futher cdata wrappers around javascript code are not mandatory but recommended. this way you protect yourselve from < and > signs breaking your xml layout. it also speeds up the parsing as the engine doesn't go through cdata sections but simply skip on them. --> <constructor><![cdata[ /** * the code below will be called one time only after * the binding is successfully prepared and bound. * "this" in this context refers to the bound element. */ // your code goes here ]]></constructor> <destructor><![cdata[ /** * the code below will be called one time only before * binding is unbound. you cannot cancel this event, * but you may accomplish some last minute clean up. * "this" in th...
...ng is successfully prepared and bound. * "this" in this context refers to the bound element. */ // your code goes here ]]></constructor> <destructor><![cdata[ /** * the code below will be called one time only before * binding is unbound. you cannot cancel this event, * but you may accomplish some last minute clean up. * "this" in this context refers to the bound element. */ // your code goes here ]]></destructor> <field name="priority"><![cdata[ /** * new "real" property for the bound element. * within this block the content is interpreted * as javascript code. the result of this code * evaluation (if any) will be used as initial value. */ "normal"; ]]></field> <property name="innertext"> <!-- new "virtual" property for the bound element. unlike <field> these ar...
reserved - Archive of obsolete content
« xul reference home reserved type: string this attribute applies to a command element. setting this attribute to "true" indicates that the command is reserved for chrome code and is not available for use in the content. this means that, to execute these commands, key events won't be passed to content, and event listeners registered for them in content will not be executed. currently, the content still receives these key events, even though it can't override them. in future releases, it won't receive them. see bug 1173061 for details. ...
...t will not be executed. currently, the content still receives these key events, even though it can't override them. in future releases, it won't receive them. see bug 1173061 for details. ...
...in future releases, the event handler will never be called for the given keyboard shortcut. ...
Writing to Files - Archive of obsolete content
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. to write to a file, an output stream is used. an output stream is an object which can be used to write bytes, strings and other values to a file. to create an output stream, use nsiscriptableio.newoutputstream(). this method has a number of options to specify text or binary wr...
...see file errors for a list of errors that might occur. the newoutputstream method takes two arguments in this example. the first argument is the file to write to, and the second is a set of flags which control the writing. in this case, the 'text' flag is used which indicates that you will be writing text to the file. when writing text files, characters are writing using a chosen character set, encoded automatically. the default character set is 'utf-8' but this can be changed using an additional, yet optional, argument to the newoutputstream method. see below for more details about this. creating and appending to files a number of flags control whether a new file is created when writing or whether data is appended to an existing file. these flags should be included in addition to the 'text' o...
..., "utf-16"); this third argument is not needed to write using utf-8. as utf-8 can store all characters, you will usually always use this default. for a list of supported character encodings, see supported character sets. the files can be written using the writestring method whichever character encoding is used. the difference is handled internally so you don't need to write any other part of the code differently. writing binary data in addition to text, binary values may be written to a file either as bytes or as numbers. a number of methods are available which may be used for this. if you are going to write to a binary file instead of text, specify the 'binary' flag in place of the 'text' flag when creating the stream with nsiscriptableio.newoutputstream(). var stream = io.newoutputstream(fi...
International characters in XUL JavaScript - Archive of obsolete content
ded from xul files. this means that such script files can use any character from virtually any language of the world. for example, they can contain a line: var text = "ein schönes beispiel eines mehrsprachigen textes: 日本語"; this mixes german and japanese characters. earlier versions always interpreted js files loaded from xul as iso-8859-1 (latin-1), in both local and remote cases. unicode escapes, as discussed below, have always worked. how the character encoding is determined in gecko 1.8 and later when the javascript file is loaded from a chrome:// url, a byte order mark (fixme: )(bom) is used to determine the character encoding of the script. otherwise, the character encoding will be the same as the one used by the xul file (which can be specified using an encoding attribute ...
...will use utf-8, which can represent virtually all characters in the world. if the script file is loaded via http, the http header can contain a character encoding declaration as part of the content-type header, for example: content-type: application/javascript; charset=utf-8 if no charset parameter is specified, the same rules as above apply. ...
...tp, the http header can contain a character encoding declaration as part of the content-type header, for example: content-type: application/javascript; charset=utf-8 if no charset parameter is specified, the same rules as above apply. cross-version compatibility if you want the same code to work in both gecko 1.8 and earlier versions, you must limit yourself to ascii. however, you can use unicode escapes – the earlier example rewritten using them would be: var text = "ein sch\u00f6nes beispiel eines mehrsprachigen textes: \u65e5\u672c\u8a9e"; an alternative might be to use property files via nsistringbundle or the xul <stringbundle> element; this would allow for localization of the xul. this can not be done in xul files loaded from the web, only in privileged code, e.g. in extensions...
Providing Command-Line Options - Archive of obsolete content
extensions and xul applications can modify the way command line parameters are handled by writing a component that implements the nsicommandlinehandler interface and registering it in a category. see also: xulrunner:commandline overview the code below is an example of writing a javascript xpcom component to handle command line parameters. you can learn more about how the command line is interpreted by looking at the documentation for the nsicommandline interface. ...
...n more about how the command line is interpreted by looking at the documentation for the nsicommandline interface. example the below example component implements two command line parameters: firefox.exe -myapp opens a chrome window for my application. firefox.exe -viewapp url opens a chrome window for my application and passes it an nsiuri object. ...
... * @param achromeurispec a str...
Filtering - Archive of obsolete content
e("predicate", "http://www.xulplanet.com/rdf/country"); } triple.setattribute("object", country); cond.appendchild(triple); } else if (triple) { cond.removechild(triple); } document.getelementbyid("photoslist").builder.rebuild(); } the 'country' argument to the applyfilter function holds the value to filter by. if this is set, we add a filter, otherwise we remove it. the code is fairly straightforward. a new <triple> element is created and the object attribute is set to the value to filter by. for example, the resulting triple for the netherlands might be: <triple subject="?photo" predicate="http://www.xulplanet.com/rdf/country" object="http://www.daml.org/2001/09/countries/iso#nl"/> this triple is then appended to the query. the triple is given an i...
...l be parsed again and the data examined for new results. you can view a complete example of this in action. a menulist is used to allow one to select either a specific country, or select all to show all of the photos. when a choice is made, the applyfilter function as shown above is called and the template content gets rebuilt with the desired filter applied. in this example, the menulist is hard-coded to contain the items that we know are in the datasource. next, we'll look at also generating this list using a template. generating a filter menu templates may be used to generate any type of content. it is common to use a template to generate the items on a menu or in a listbox or tree. the syntax is the same regardless of what type of content is being created. in the previous example, we ha...
...o contain the items that we know are in the datasource. next, we'll look at also generating this list using a template. generating a filter menu templates may be used to generate any type of content. it is common to use a template to generate the items on a menu or in a listbox or tree. the syntax is the same regardless of what type of content is being created. in the previous example, we hard-coded a menulist with the list of countries, but we could also generate this list from the datasource. the same datasource may used for both the photos list and the menulist. even though the same datasource is used, it will only be loaded once and both templates will be notified when the data has loaded. we will need to add some information to the datasource in order to specify the list of countries t...
Special Condition Tests - Archive of obsolete content
rule parent="vbox"> <action> <groupbox uri="?"> <caption label="?name"/> </groupbox> </action> </rule> <rule> <action> <label uri="?" value="?name"/> </action> </rule> </template> </vbox> previously, an assign element was used to assign the tagname of the result to a variable, which was then compared in a rule condition. the code above accomplishes the same effect except that it using the parent matching mechanism. note the parent attribute on the rule element, set to the value vbox. this causes the rule to match only content that would be inserted in a vbox element. as the outer element is a vbox, this will match for all results in the first iteration of the template. however, for the next iteration, that is, the next le...
...nt is a vbox, this will match for all results in the first iteration of the template. however, for the next iteration, that is, the next level of children, the content would instead be inserted into the groupbox generated from the previous iteration. this does not match the first rule, so the content from the second rule is generated instead. the end effect is the same output, however, the source code is simpler. this technique is useful when you know that the content will be different at each level. if this is not the case, you will still need to use other types of conditions to handle this case. rdf parent matching for rdf sources, you can use the same technique. to do this kind of matching, you again place a parent attribute on the rule, set to the tag to match. for instance, we might use t...
...since the iscontainer attribute is set to true, the rule will match as long as the member value or child of the starting node is an rdf container. we could also have left the rules in the original order and set the iscontainer on the...
Template Builder Interface - Archive of obsolete content
an element into a xul document, the element is checked to see if it has a datasources attribute. if so, a template builder will be created for the element and attached to the element. if the element is a <tree> element and has the flags attribute set to "dont-build-content", a tree builder will be created. otherwise, a content builder will be created. both types of builder share much of the same code except for how they generate output to be displayed. both types of builders implement the nsixultemplatebuilder interface, while the tree builder also implements the nsixultreebuilder interface. the builder associated with an element is accessible via the element's 'builder' property both for content builders and for tree builders. an element that does not have a builder will have this property s...
...s often used if you modify the datasource or modify the rules. for rdf datasources, the builder's refresh method, however, will reload the datasources. it will not rebuild the template, but we'll see in a later section why this is not usually necessary. to summarize, the refresh method reloads the data, whereas the rebuild method reconstructs the content. the builder is accessible to unprivileged code, so the rebuild and refresh methods may be called by remote code. changing the datasource you can modify the datasource that is used for a template by setting the value of the datasources attribute on the root element. changing this attribute causes the new datasource to be retrieved and the template to be rebuilt. the rdf datasource associated with the template can be retrieved using the element...
...urce is retrieved using the rdf service's getdatasource method. after adding a datasource, the tree builder's rebuild method is invoked to rebuild the template with the new data. this doesn't happen automatically when you add the datasource, which is useful, since you will often want to add or remove other datasources at the same time. the composite datasource can only be accessed from privileged code, regardless of what datasources it contains. fortunately in this situation, you can just set the datasources attribute (or the corresponding property) to the datasources that you want. for instance: var tree = document.getelementbyid("thetree"); tree.datasources = "template-guide-photos5.rdf template-guide-streets.rdf"; this will also change the datasources used. in this case, the template will ...
Tree Widget Changes - Archive of obsolete content
e column in the tree. a tree will have one of these objects for each column (each treecol element) in the tree. the columns are grouped into a list which implements the nsitreecolumns interface. both the nsitreecolumn and nsitreecolumns interfaces can be found at layout/xul/base/src/tree/public/nsitreecolumns.idl. the column objects are created automatically, so you don't have to write any extra code. you can get the columns object which implements the nsitreecolumns interface for a tree using the tree's columns property. from there you can get specific columns, the current sort column, and position and size info about the columns. for the most part these objects are readonly; you can modify the columns by just adjusting the treecol attributes directly. the tree and view methods no longer ta...
... nscomptr<nsiatom> atom; acol->getatom(getter_addrefs(atom)); if (atom = kmycol) ... one feature that has been added is restorenaturalorder which may be used to restore the original order of the columns before the user moved them around. tree.columns.restorenaturalor...
...e.treeboxobject.getpagelength(). the invalidateprimarycell(row) method has been removed, instead use nsitreeboxobject.invalidatecell() like this invalidatecell(row, tree.columns.getprimarycolumn()). this may be used to redraw a cell after it or its data has been changed. the nsitreeview.cycleheader() method has been changed, cycleheader(colid, element) is now just cycleheader(column), since the code can get the element from the column object. the constants below have been changed, and their integer values are different: nsitreeview.indropbefore -> nsitreeview.drop_before (-1) nsitreeview.indropon -> nsitreeview.drop_on (0) nsitreeview.indropafter -> nsitreeview.drop_after (1) nsitreeview.progressnormal -> nsitreev...
Adding Buttons - Archive of obsolete content
bove. others will be discussed later. some examples of buttons example 1 : source view <button label="normal"/> <button label="disabled" disabled="true"/> the examples above will generate the buttons in the image. the first button is a normal button. the second button is disabled so it appears greyed out. we'll start by creating a simple find button for the find files utility. ...
...code below shows how to do this. <button id="find-button" label="find"/> note: firefox does not allow you to open chrome windows from web pages, so the view links in the tutorial will open in normal browser windows. due to this, the buttons will appear to stretch across the window. you can add align="start" to the window tag to prevent the stretching. the findfile.xul example let's add this code to the file findfile.xul that we created in the previous section. the code needs to be inserted in-between the window tags. ...
...rom web pages, so the view links in the tutorial will open in normal browser windows. due to this, the buttons will appear to stretch across the window. you can add align="start" to the window tag to prevent the stretching. the findfile.xul example let's add this code to the file findfile.xul that we created in the previous section. the code needs to be inserted in-between the window tags. ...
Adding Methods to XBL-defined Elements - Archive of obsolete content
="num1"/> <parameter name="num2"/> <body> if (num1 &lt;= num2) return num2; else return num1; </body> </method> this function, getmaximum, returns the largest of the values, each passed as a parameter to the method. note that the less-than symbol has to be escaped because otherwise it would look like the start of a tag. you can also use a cdata section to escape the entire block of code. you can call the method by using code such as element.getmaximum(5, 10) where element is a reference to an element defined by the xbl containing the getmaximum method. (the bound element.) the parameter tag allows you to define parameters for a method. because mozilla uses javascript as its scripting language, and javascript is a non-typed language, you do not need to specify the types of the p...
...ows you to define parameters for a method. because mozilla uses javascript as its scripting language, and javascript is a non-typed language, you do not need to specify the types of the parameters. however, in the future, other languages may be used with xbl. methods are only available to call after the page is rendered, which may cause problems if using createelement. for example, the following code will probably fail: var element = document.createelement("my_element"); element.getmaximum() // this will fail by the way, it is safe to call methods from the constructor, other methods on the object and event handlers. accessing the anonymous content there may be times when you want to modify some aspect of the elements defined in the content element, either from a method body or elsewhere. ...
...ntent> </binding> to refer to each button, you can use the getanonymousnodes() function, passing it a reference to the element the binding is bound to as the parameter. in the returned array, the first button is stored in the first array element (getanonymousnodes(element)[0]), the second button is stored in the second array element and the third button is stored in the third array element. for code inside a binding method, you can pass 'this' as the parameter to getanonymousnodes(). the next example can be used to create text with a label. the method 'showtitle' can be used to show or hide the label. it works by getting a reference to the title element using the anonymous array and changing the visibility of it. xul: <box id="num" class="labeledbutton" title="number of things:" value="52...
Adding Properties to XBL-defined Elements - Archive of obsolete content
e elements you create. you can also add methods that can be called. that way, all you need is to get a reference to the element (using document.getelementbyid or a similar function) and then get or set the additional properties and call the methods on it. there are three types of items you can add. fields are used to hold a simple value. properties can also be used to hold a value but may have code execute when an attempt is made to retrieve or modify the value. methods are functions which may be executed. all three are defined within an implementation element, which should be a child of the binding element. within the implementation, you define individual field, property, and method elements, one for each one that you want. the general syntax is as follows: <binding id="element-name"> ...
... you may want the value to be calculated dynamically as it's asked for. for example, if you want a property that holds the current time, you would want to have its value generated as needed. in these cases, you need to use a property tag instead of a field tag. its syntax is similar but has additional features. onget attribute and onset attribute you can use the onget and onset attributes to have code execute when the property is retrieved or modified. add each to the property element and set its value to a script which either gets or sets the value of the property. for example, you could assign a script to the value of onget to calculate the current time. whenever a script attempts to access the value of the property, the onget script will be called to retrieve the value. the script should re...
...r"> <getter> return this.getattribute('number'); </getter> <setter> var v = parseint(val,10); if (!isnan(v)) { this.setattribute('number', '' + v); } </setter> </property> the property in this example will only be able to hold integer values. if other characters are entered, they are stripped off. if there are no digits, the value is not changed. this is done in the code inside the setter element. the real value of the property is stored in the number attribute. you can use either syntax for creating get and set handlers. readonly attribute you can make a field or property read-only by adding a readonly attribute to the field tag or property tag and setting it to true. attempting to set the value of a read-only property will fail. note: the readonly attribute d...
Additional Install Features - Archive of obsolete content
et, such as having a particular library installed. in addition to the install object, a file object is also available during an installation script. it provides some functions which can be used to examine and modify files on disk. you can use these to move, copy or delete files before or after the files are installed. for example, you might want to make a backup of some files first. the following code will make a copy of the file "/bin/grep" and put it in the directory "/main". var binfolder = getfolder("file:///","bin"); var grep = getfolder(binfolder, "grep"); var mainfolder = getfolder("file:///", "main"); file.copy(grep, mainfolder); the first line will retrieve a reference to the /bin directory. the text 'file:///' is a special string which means the root of the filesystem. from ...
...at might conflict with your package out of the way. handling errors you will likely want to handle errors gracefully. this will occur if a file or directory cannot be found, there is insufficient disk space or for a number of other reasons. you can use the getlasterror() function to determine whether an error occured. if it returns success, no error occured. otherwise, the number will be an error code which indicates the type of error that occured. you can call this function at any point during the installation script to determine whether an error occured during the last operation. if an error occurs, you will likely want to abort the installation. you may also want to display an error message to the user. for example, you might put the following as the last section of your script: if (getlast...
...any point during the installation script to determine whether an error occured during the last operation. if an error occurs, you will likely want to abort the installation. you may also want to display an error message to the user. for example, you might put the following as the last section of your script: if (getlasterror() == success) { performinstall(); } else { cancelinstall(); } error codes that could be returned by getlasterror() are listed in the mozilla source file nsinstall.h. during installation, a log file is created that contains the operations that are performed. it will also show any errors that occured. the log file can be found in the file 'install.log' in the mozilla installation directory. a block of text will be added to this file for each installation that occurs. th...
Creating Dialogs - Archive of obsolete content
ge. this means it will not work on remote sites; for those, use window.open() instead. the dialog element the dialog element should be used in place of the window element when creating a dialog. it provides the useful ability to construct up to four buttons along the bottom of the dialog forok,cancel, and so on. you do not need to include the xul for each button; however, you do need to supply code to perform the appropriate tasks when the user presses each button. this mechanism is necessary because different platforms have a specific order in which the buttons appear. example dialog source view <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog id="donothing" title="dialog example" xmlns="http://www.mozilla.org/keymaster/gat...
...u wish in a dialog. the dialog element has some additional attributes that windows do not have. the buttons attribute is used to specify which buttons should appear in the dialog. the following values may be used, seperated by commas: accept - an ok button cancel - a cancel button help - a help button disclosure - a disclosure button, which is used for showing more information you can set code to execute when the buttons are pressed using the ondialogaccept, ondialogcancel, ondialoghelp and ondialogdisclosure attributes. if you try the example above, you will find that the dook() function is called when the ok button is pressed and the docancel() function is called when the cancel button is pressed. the two functions dook() and docancel() both return true, which indicates that the dia...
... next, we'll see how to open file dialogs. « previousnext » ...
Manifest Files - Archive of obsolete content
might not have sufficient permissions to write into it. note: starting in gecko 2.0, only the file named chrome.manifest is read automatically; if you need to read multiple manifest files, use the manifest command in that file to import additional manifests. use manifest flags to configure the scenarios in which the secondary manifest is imported. if you just want to try testing privileged xul code in the firefox browser, you can do this easily by just using a manifest with only one line in it: create a new directory somewhere. for example, on a windows machine, you might use c:\testfiles create a new ascii1 file called test.manifest in the chrome directory. it doesn't actually matter what the file is called as long as it has the .manifest extension. ( 1. doesn't work with utf-8 with bom...
...o package up all the files every time you change them. however, when distributing an application or extension, you will want to package them into an archive to avoid having to install lots of smaller files. the xpcnativewrappers=yes part at the end of the manifest line is a flag that may optionally be used. in javascript, it is possible for a web page to override built-in functions with their own code. if the xpcnativewrappers flag is specified, it indicates that scripts running in a privileged context don't call these overridden versions, but the original built-in versions instead. otherwise, if an extension attempted to call the modified versions, it would likely not work properly, or worse, create a security hole. this flag was added to prevent this problem and should always be used for new...
... applications if you are creating applications for older versions of mozilla software, that is, before firefox 1.5 or mozilla 1.8, the process is a bit more involved. the following describes how to set up a package for earlier versions. this section may be skipped if you are writing new extensions or xul applications. note: this older process does also apply to the new seamonkey 1.0 though. the codebase there has not yet adopted the "manifest" format. <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <rdf:seq about="urn:mozilla:package:root"> <rdf:li resource="urn:mozilla:package:myapplication"/> </rdf:seq> <rdf:description about="urn:mozilla:package:myapplication" chrome:d...
Tree Box Objects - Archive of obsolete content
atecell() to redraw only a single cell invalidatecolumn() to redraw a column invalidaterange() to redraw a range of rows invalidate() to redraw the entire tree. note that redrawing does not occur until the calling script ends since mozilla does not redraw in the background. note: it is not necessary to run tree.boxobject.queryinterface(components.interfaces.nsitreeboxobject) as shown in the code examples on this page because: let boxobject = tree.treeboxobject; note: is equivalent to: let boxobject = tree.boxobject; boxobject.queryinterface("components.interfaces.nsitreeboxobject"); scrolling the tree you can also scroll the tree using four different methods, similar to those available for listboxes. the scrolltorow() function may be used to scroll to a particular row. here is a s...
...separate column object exists, which can be queried for column data. the following line is used so that the example above will work in all versions. if (column.value && typeof column.value != "string") { column.value = column.value.id; } if the column is a string, we are running on mozilla 1.7 or earlier, but for later versions we get the column id from the column object. if you are writing code for multiple versions, you should check for this as above. the last argument to getcellat() is the child type which is filled in with a string depending on what part of the cell the coordinate is at. if you move the mouse around in the previous example, you might notice the label change between 'text' and 'cell'. the value 'text' indicates the area where the text would be drawn and the value 'ce...
...ext would be drawn and the value 'cell' indicates the area around the text, for example, the margin on the left side where the open and close twisties are normally drawn. if there was a twisty, however, the value would be 'twisty' instead. this is convenient since you could determine whether the user clicked on a twisty instead of another part of the row. in fact, this is what the underlying tree code does when the user double clicks the twisty. the final value that may be returned is 'image' if there is an image in the tree cell and the coordinate corresponds to a location where the image is. of course, in many cases you may not care what part of the cell the coordinate is on and just want the row and column. to go in reverse and get the coordinates of a specific cell, use the getcoordsforce...
XBL Inheritance - Archive of obsolete content
any binding can be extended with another. ...
...any binding can be extended with another. ...
...e tree). to extend an existing binding, add an extends attribute on to the binding tag. for example, the following binding creates a textbox which adds the text 'http://www' to the beginning of its value when the f4 key is pressed. example 1 : source <binding id="textboxwithhttp" extends="chrome://global/content/bindings/textbox.xml#textbox"> <handlers> <handler event="keypress" keycode="vk_f4"> this.value="http://www"+value; </handler> </handlers> </binding> the xbl here extends from the xul textbox element. the url given in the extends attribute above is the url of the textbox binding. this means that we inherit all of the content and behavior provided by the textbox binding. in addition, we add a handler which responds to the keypress event. autocompleting textbo...
Using Visual Studio as your XUL IDE - Archive of obsolete content
can use the normal xml-editor for writing xul. go to tools > options... > text editor > file extension and add the extension "xul" with "xml editor". as you are already there, you can do the same for "xbl". 2. using xml schemas for validation and intellisense visual studio needs the xml schema for xul files. there is a very nice schema created by mihailo lalevic. you can download it at xulschema.codeplex.com under the downloads tab. you should be able to use the schema in other ide's too. there is also project that provides xml schema for install manifest files (install.rdf) - installrdfschema.codeplex.com - from the same author as a xul schema. the codeplex-page provides some instructions for installing the schema, but there is an easier way. if you already have a xml or xul file opened, vis...
...here.is.only.xul. 3. xbl if you are writing your own elements in xbl, you can download a xbl schema from mozilla.doslash.org/xblschema. grab the xsd version and add it in the same way, you added the xul schema. to combine both, you can also add your own xbl elements to the xul schema to get autocompletion-support and validation for those in your xul files. mihailo posted some instructions in this codeplex discussion. 4. visual assist and file extensions since version 10.5, visual assist supports javascript and xml. as it does not work out of the box with unknown file extensions (like .xul, .xbl and .jsm), you have to do some registry tricks, so that va knows how to treat these file types. all va options can be found at: hkey_current_user\software\whole tomato\visual assist x\ find the folde...
...orks it can't detect where the dtd file is really located and thus will give you errors wherever you use the entities that are declared in this file. 5.2 text preprocessor the mozilla build system includes a text preprocessor. as preprocessor directives are not valid xml, visual studio will mark them as errors in your xul files. 5.3 javascript related you will get validation errors for javascript code whenever using the keywords "const" and "let". these keywords are mozilla-specific at the moment. vs just supports ecmascript 3rd edition and thus doesn't know these keywords. ...
XUL element attributes - Archive of obsolete content
the same domain as the document. dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the elements are placed left to right or top to bottom in the order they appear in the xul code. reverse for scales, the scale's values are ordered from right to left (for horizontal scales) or from bottom to top (for vertical scales). for other elements, they are placed right to left or bottom to top. this is reverse of the order in which they appear in the xul code. empty type: boolean set to true if the element is a container that contains no children. this will be set...
...ement as normal. observes type: id set to an id of a broadcaster element that is being observed by the element. if an attribute changes in the broadcaster it is also changed in the observer. ordinal type: string (representing an integer) an integer which specifies the position of the element within its parent. by default, elements appear in the order they appear in the xul code. the ordinal attribute can be used to change the order. note the default ordinal for elements is 1. you can retrieve the displayed order by using the properties of the boxobject of the container. orient type: one of the values below used to specify whether the children of the element are oriented horizontally or vertically. the default value depends on the element. you can also use the -...
.... style type: css inline style css style rules to be applied to the element. syntax is as in the html style attribute. it is preferred to put style rules in style sheets. template type: id for template generated elements, this attribute may optionally be placed on the root node (the element with the datasources attribute) to refer to a template that exists elsewhere in the xul code. this template attribute should be set to the id of the template element. this might be used to share a single template between multiple trees or menus. if this attribute is not specified, there should be a template element directly inside the node. tooltip type: id should be set to the value of the id of the tooltip or panel element that should be used as a tooltip window when the mouse...
command - Archive of obsolete content
it will be called no matter how it is invoked by the user. ...
...ion has the advantage that the command will be sent to the part of the ui which will respond to it. typically, this will be the currently focused element. like a broadcaster, commands forward attributes to other elements. more information is available in the xul tutorial. ...
...ept for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. oncommand type: script code this event handler is called when the command is activated. this occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. reserved type: string this attribute applies to a command element. setting this attribute to "true" indicates that the command is reserved for chrome code and is not available for use in the content. this means that, to execute...
prefwindow - Archive of obsolete content
or type: color string specify background color of the window's titlebar when it is inactive (background). moreover this hides separator between titlebar and window contents. this affects only on mac os x. lastselected type: string set this to the id of the last selected pane. it will be opened by default the next time the preferences dialog is opened. onbeforeaccept type: script code the code in this attribute is called when the ok button is pressed or the acceptdialog method is called. returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ondialogaccept type: script code the code in this attribute is called when the accept button is pressed, or when the acceptdialog method is called. if the handler returns true, t...
...ed. returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ondialogaccept type: script code the code in this attribute is called when the accept button is pressed, or when the acceptdialog method is called. if the handler returns true, the dialog will indeed go away, but if it returns false it will not. ondialogcancel type: script code the code in this attribute is called when the "cancel" button is pressed or when the canceldialog method is called. if the routine returns true, the dialog will indeed go away, but if it returns false it will not. ...
...called. if the handler returns true, the dialog will indeed go away, but if it returns false it will not. ondialogcancel type: script code the code in this attribute is called when the "cancel" button is pressed or when the canceldialog method is called. if the routine returns true, the dialog will indeed go away, but if it returns false it will not. ondialogdisclosure type: script code the code in this attribute is called when the "disclosure" button is pressed. ondialoghelp type: script code the code in this attribute is called when the "help" button is pressed. prefwindow.onload type: script code when a window finishes loading, it calls this event handler on the prefwindow element. title type: string the text to appear in the title bar of the window...
tabbrowser - Archive of obsolete content
be enabled or depending on the user preference general.autoscroll. contentcontextmenu type: id the id of a menupopup element serving as the context menu for the content area in the tabbrowser. contenttooltip type: id the id of a tooltip element to be used for the content area in the tabbrowser. onbookmarkgroup not in firefox type: script code this code executes when the user chooses the "bookmark this group of tabs" command. onnewtab not in firefox type: script code this script will be called when the new tab button is clicked. tabmodalpromptshowing type: integer the number of tab modal prompts currently attached to the current tab. properties browsers type: nodelist of browser elements holds a list of the bro...
... page with the specified url. the rest of the parameters are optional. the row of tabs will appear if needed. firefox 3.6 note the second form of this method was added in firefox 3.6; it allows you to specify the parameters by name, in any order. it also adds the relatedtocurrent parameter; firefox uses this to decide whether the new tab should be inserted next to the current tab. see code snippets: tabbed browser for examples. see preprocessing post data for preparing postdata out of a string. addtabsprogresslistener( listener ) return type: no return value add a progress listener to the browser which will monitor loaded documents in all tabs in the tabbed browser. the progress listener should be based on the nsiwebprogresslistener interface with an additional "browser" ar...
...s( atabs ) return type: no return value makes all tabs in the atabs array visible, and all other tabs hidden. stop() return type: no return value equivalent to pressing the stop button, this method stops the currently loading document. unpintab( tabelement ) return type: no return value unpins the specified tab element, making it no longer an app tab. related code snippets: tabbed browser ...
window - Archive of obsolete content
maximized windows). note: when a window is minimized, the sizemode attribute is not updated. this is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. setting this attribute does not change the window state. use window.maximize(), window.restore(), or window.minimize() to change the window state. to get the window state from javascript code, use window.windowstate. listen to the sizemodechange event dispatched to the dom window to get notified when the window state changes. title type: string the text to appear in the title bar of the window. width type: string (representing an integer) the preferred width of the element. the value should not include a unit as all values are in pixels. the actual displayed width may...
...a doctype declaration may silently fail to load and the only error message will be an undefined entity error on the next xul element. related elements prefwindow, dialog, dialogheader related topics user notes to change the icon to a window's title bar check this page on window icons. to add a favicon to the address bar and browser tab (ie dialog is not a popup) then use the following code snippet to use the html namespace and link. <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> <!-- icon from chrome --> <html:link rel="icon" href="chrome://myextension/content/path/to/favicon.png"/> <!-- from a remote site --> <html:link rel="icon" href="http://www.mozilla.org/favicon.ico"/> since firefox 3.6 the above ...
...t to use the html namespace and link. <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> <!-- icon from chrome --> <html:link rel="icon" href="chrome://myextension/content/path/to/favicon.png"/> <!-- from a remote site --> <html:link rel="icon" href="http://www.mozilla.org/favicon.ico"/> since firefox 3.6 the above listed code does not work correctly - it produces the following message: "warning: xul box for box element contained an inline link child, forcing all its children to be wrapped in a block". if this code is placed between window tags it messes up all other controls on the window. if it is placed between box tags, window controls are rendered fine, but still there is this error message. the problem can be sol...
XULRunner 1.9.1 Release Notes - Archive of obsolete content
current version the current version of xulrunner is 1.9.1.19, matching firefox 3.5.19 detailed release notes can be found here. ...
...ation will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application. on microsoft windows xp, all xul applications may wind up being grouped together in the taskbar. frequently asked questions why is installing xulrunner so painful? why isn't there a nice installer? because nobody has written that code yet! additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner for more information. where is the source ...
... yet! additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner for more information. where is the source code? here. where is the sdk? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask question...
Debugging a XULRunner Application - Archive of obsolete content
.nsiconsoleservice) .logstringmessage(str); } for more information about the error console see the error console and browser console article. browser debugger as of gecko 44, it is no longer possible to start the devtools server from xul apps. see bug 1244163. starting with xulrunner 24, you should use the firefox browser debugger to debug your xulrunner apps. ...
...lowing code to your xul app: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); // don't specify a window type parameter below if "navigator:browser" // is suitable for your app. ...
...enkman overlay): function toopenwindowbytype(intype, uri) { var winopts = "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar"; window.open(uri, "_blank", winopts); } i can't see my pages, functions ... if your pages are not in the loaded script window, uncheck the menu item "debug\exclude browser files" and find them in open windows tab when opening a js file in venkman, the code is unformatted and i get the following error in the jsconsole... security error: content at x-jsd:source?location=chrome%3a%2f%2fvenkman%2fcontent%2fvenkman-overlay.js&instance=12 may not load or link to chrome://venkman/skin/venkman-source.css. note the "new in firefox 3" attribute "contentaccessible" on https://developer.mozilla.org/en/chrome_registration so as per http://markmail.org/messag...
application/http-index-format specification - Archive of obsolete content
note that more digits are possible in the future) and data is separated from number by a colon and a space. the syntax of data is defined by the syntax spec for every number type. if a number is encountered that a parser does not understand the parser is required to ignore that line. there is no line length limit. all lines must be terminated by a carriage return followed by a line feed. number codes 100 a human readable comment line. machine parsers should ignore this data. this data is not intended for display to the end user and is only meant as a comment to make the file format clear to a human interpreter. 101 pre formatted human readable information line. this data is intended for the end user of the file format data if there is one. this data should be presented to the user when...
...ta 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 should be presented to the user when they are viewing data drawn from the file. this data should be parsed as html. 200 defines the field names for the 201 file index code. a valid 200 line consists of one or more white space separated tokens that describe the name or purpose of the associated column of data. tokens may not contain spaces. any illegal characters must be escaped via the url escaping syntax defined by rfc 1738. note that multiple 200 lines override previous 200 lines. 201 data whose definition stems from a prior 200 line. a valid 201 line consists...
...tered before a 200 line should be ignored. 300 a url pointing to the directory represented by the index if there is one. a valid path token must be url escaped. valid 200 tokens note that all tokens are case insensitive. filename the name of file that can be used to retrieve the file when combined with the full path provided by the 300 line. white space and 8 bit characters must be url encoded. content-length base 10 digits representing the size of the file in bytes. only digits are legal. last-modified rfc 1123 date format url encoded. content-type mime content type. whitespace and 8-bit characters must be url-encoded. the mime-type for a directory can be given as application/http-index-format. file-type one of the following keywords to represent a special status for a fi...
External resources for plugin creation - Archive of obsolete content
action provided. framework: firebreath project home page project history description (from the project creators): firebreath is a cross-platform browser plugin framework written in c++. plugins created with firebreath work on all major browsers, including firefox 3.0 and later. platforms supported include windows, linux, and mac os x (intel). feature highlights include thread safety checks, unicode support (with std::wstring), activex support, built-in drawing model negotiation for mac, automatic type conversion (including javascript arrays and objects), advanced security features, and more. supported development environments are visual studio on windows, xcode on mac, and gcc on linux. all platforms rely on cmake for easy cross-platform builds. project: nixysa project home page descriptio...
...matic type conversion (including javascript arrays and objects), advanced security features, and more. supported development environments are visual studio on windows, xcode on mac, and gcc on linux. all platforms rely on cmake for easy cross-platform builds. project: nixysa project home page description (from the home page): nixysa is a framework written in python to automatically generate glue code for npapi plugins (plugins for browsers such as google chrome or firefox), letting you easily expose c++ classes to javascript from a simple idl representation. nixysa was originally conceived for the needs of o3d, but is flexible enough to support a wide range of use cases. project: juce project home page description (from the home page): juce (jules' utility class extensions) is an all-encompas...
...oject home page description (from the home page): juce (jules' utility class extensions) is an all-encompassing c++ class library for developing cross-platform applications. it contains pretty much everything you're likely to need to create most applications, and is particularly good for creating highly-specialised uis and for handling graphics and sound. supported development environments are xcode, visual studio, gcc (and probably any other modern c++ compiler) browser plugins can be built as npapi (mac/windows), or activex (windows). project: qtbrowserplugin project home page description (from the home page): the qtbrowserplugin solution makes it easy to write browser plugins that can be used in mozilla firefox, safari, opera, google chrome, qtwebkit and any other web browser that support...
Monitoring plugins - Archive of obsolete content
ore information on the observer service here and here. ...
...o see that the arriving notification's topic is the correct one. this is useful in cases where your class is registered to receive notifications for more than one topic with the observer service. ...
... var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice...
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
thunderbird and sunbird (previous versions worked only in firefox). if you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension localizing an extension download the sample you can download this article's sample code so you can look at it side-by-side with the article, or to use it as a basis for your own extension. download the sample updating the install manifest the first step is to revise the extension's install manifest to indicate that it can be installed in thunderbird and sunbird. this is done by adding new <targetapplication> tags to the install.rdf file, like this: <!-- describe the thunderbi...
... <em:targetapplication> <description> <em:id> {718e30fb-e89b-41dd-9da7-e25a45638b28}</em:id> <em:minversion>0.2</em:minversion> <em:maxversion>0.4.*</em:maxversion> </description> </em:targetapplication> these two blocks indicate that the extension supports thunderbird versions 1.5 through 2.0.0.x, sunbird versions 0.2 through 0.4.x. after inserting this code, you can successfully install the extension into any (or all) of firefox, thunderbird, and sunbird, but you won't see any effect in thunderbird and sunbird. that's because there's nothing telling those two applications what to do with the chrome provided by the extension. that's where the chrome manifest comes into play. update the chrome manifest remember way back in the first article in this se...
...se there's nothing telling those two applications what to do with the chrome provided by the extension. that's where the chrome manifest comes into play. update the chrome manifest remember way back in the first article in this series when we created our chrome manifest, which we haven't touched since? it's time to touch it. as you may (or may not) recall, that file tells the application what xul code your extension's interface needs to overlay onto. for firefox, we overlaid onto browser.xul, which describes a firefox browser window. we need to add lines to the manifest for thunderbird and sunbird, like this: # thunderbird overlay chrome://messenger/content/messenger.xul chrome://stockwatcher2/content/stockwatcher2.xul # sunbird overlay chrome://calendar/content/calendar.xul chrome://stockwa...
Using workers in extensions - Archive of obsolete content
ating an extension to support multiple mozilla applications download the sample you may download the complete example: download the example. how this differs from previous versions this version of the stock ticker extension moves the xmlhttprequest call that fetches updated stock information into a worker thread, which then passes that information back to the main body of the extension's code to update the display in the status bar. this demonstrates not only how to use workers in an extension, but also how to perform xmlhttprequest in a worker, and how workers and main thread code can pass data back and forth. the worker the worker thread's job in this example is to issue the xmlhttprequest calls that fetch the updated stock information. that's all it does. every 10 minutes, it cal...
...it starts by setting up an interval handler (in lines 26-28) that calls refreshinformation() every 10 minutes. then it sets the worker's onmessage event handler to a function which looks at the event passed into it, and does one of two things: if there is a data field on the event, the stock symbol being tracked is set to the upper case version of that value. thi...
...function() { // empty message just means 'refresh'. this.worker.postmessage(""); }, the onworkermessage() method this method is called when the worker posts a message back to the main thread. its job is to update the ticker information that's currently displayed in the status bar, as well as to update the tooltip that appears while the mouse cursor is hovering over the ticker. this code is essentially identical to what's done in the previous version, except that it's done in response to an event instead of within the refreshinformation() method. a note about chromeworkers requires gecko 2.0(firefox 4 / thunderbird 3.3 / seamonkey 2.1) gecko 2.0 added the new chromeworker object, which provides a special chrome-only worker that can be used by applications and extensio...
-ms-filter - Archive of obsolete content
' [ <ident-token> '.' ]* [ <ident-token> | <function-token> <any-value> ')' ] <-ms-filter-function-legacy> = <ident-token> | <function-token> <any-value> ')' the <string> contains the list of filters, transitions, and procedural surfaces. refer to the filters and transitions reference for details. examples the following example shows how to use the -ms-filter attribute in internet explorer 8. ...
...wing example shows how to use the -ms-filter attribute in internet explorer 8. code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_8.htm -ms-filter: 'progid:dximagetransform.microsoft.motionblur(strength=50), progid:dximagetransform.microsoft.basicimage(mirror=1)'; the following example shows how to use an inline style sheet to set the filter on an image. ...
...//samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_h.htm <img style="filter:progid:dximagetransform.microsoft.motionblur(strength=50) progid:dximagetransform.microsoft.basicimage(mirror=1)" src="/workshop/samples/author/dhtml/graphics/cone.jpg" height="80px" width="80px" alt="cone"> the following example shows how to use scripting to set the filter on an image. code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_s.htm <body> <p>click the image to start the filter.</p> // call the function. <div id="filterfrom" style="position: absolute; width: 200px; height: 250px; background-color: white; filter: revealtrans()"> <img id="imagefrom" style="position...
Debug - Archive of obsolete content
ions of the debug object display strings in the visual studio output window at run time. to debug internet explorer scripts, you must have a script debugger installed and the script must run in debug mode. internet explorer 8 and later versions include the javascript debugger. if the script is not being debugged, the debug methods and properties have no effect. constants async callback status codes contant description value debug.ms_async_callback_status_assign_delegate the synchronous work item assigned a callback or continuation to be run by an asynchronous operation. 0 debug.ms_async_callback_status_join the synchronous work item satisfied part of a join asynchronous operation. 1 debug.ms_async_callback_status_chooseany the synch...
...onous operation. 1 debug.ms_async_callback_status_chooseany the synchronous work item satisfied a choice asynchronous operation. 2 debug.ms_async_callback_status_cancel the synchronous work item was canceled. 3 debug.ms_async_callback_status_error the synchronous work item caused an error in an asynchronous operation. 4 async operation status codes contant description value debug.ms_async_op_status_success the asynchronous operation was successful. 1 debug.ms_async_op_status_canceled the asynchronous operation was canceled. 2 debug.ms_async_op_status_error the asynchronous operation resulted in an error. 3 properties debug.debuggerenabled determines whether debugging i...
...ful. 1 debug.ms_async_op_status_canceled the asynchronous operation was canceled. 2 debug.ms_async_op_status_error the asynchronous operation resulted in an error. 3 properties debug.debuggerenabled determines whether debugging is enabled for the script context. debugging may be enabled or disabled whether or not a debugger is attached. debug.setnonusercodeexceptions determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled. functions debug.mstraceasynccallbackcompleted indicates that the callback stack associated with a previously specified asynchronous operation has completed. debug.mstraceasynccallbackstarting associates the callback stack with a previously specified asynchronous operation.
Error.number - Archive of obsolete content
orted in internet explorer. the error.number property returns or sets the numeric value associated with a specific error. the error object's default property is number. syntax object .number [= errornumber] parameters object any instance of the error object. errornumber an integer representing an error. remarks an error number is a 32-bit value. the upper 16-bit word is the facility code, and the lower word is the error code. to determine the error code, use the & (bitwise and) operator to combine the number property with the hexadecimal number 0xffff. example the following example causes an exception to be thrown and displays the error code that is derived from the error number. try { // cause an error. var x = y; } catch(e) { document.write ("error co...
...ine the number property with the hexadecimal number 0xffff. example the following example causes an exception to be thrown and displays the error code that is derived from the error number. try { // cause an error. var x = y; } catch(e) { document.write ("error code: "); document.write (e.number & 0xffff) document.write ("<br />"); document.write ("facility code: ") document.write(e.number>>16 & 0x1fff) document.write ("<br />"); document.write ("error message: ") document.write (e.message) } example the output of this code is as follows. ...
...an error. var x = y; } catch(e) { document.write ("error code: "); document.write (e.number & 0xffff) document.write ("<br />"); document.write ("facility code: ") document.write(e.number>>16 & 0x1fff) document.write ("<br />"); document.write ("error message: ") document.write (e.message) } example the output of this code is as follows. error code: 5009 facility code: 10 error message: 'y' is undefined requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards. also supported in store apps (windows 8 and windows phone 8.1). applies to: error objec...
GetObject - Archive of obsolete content
ject function is not supported in internet explorer 9 standards mode, internet explorer 10 standards mode, internet explorer 11 standards mode, and windows store apps or later. use the getobject function to access an automation object from a file. assign the object returned by getobject to the object variable. for example: var cadobject; cadobject = getobject("c:\\cad\\schema.cad"); when this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated. if pathname is a zero-length string (""), getobject returns a new object instance of the specified type. if the pathnameargument is omitted, getobject returns a currently active object of the specified type. if no object of the specified type exists, an error occurs. ...
...le. to do so, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. for information on how to create this string, see the documentation for the application that created the object. for example, in a drawing application you might have multiple layers to a drawing stored in a file. you could use the following code to activate a layer within a drawing called schema.cad: var layerobject = getobject("c:\\cad\\schema.cad!layer3"); if you do not specify the object's class, automation determines which application to start and which object to activate, based on the file name you provide. some files, however, may support more than one class of object. for example, a drawing might support three different types o...
...all of which are part of the same file. to specify which object in a file you want to activate, use the optional class argument. for example: var myobject; myobject = getobject("c:\\drawings\\sample.drw", "figment.drawing"); in the preceding example, figment is the name of a drawing application and drawing is one of the object types it supports. once an object is activated, you reference it in code using the object variable you defined. in the preceding example, you access properties and methods of the new object using the object variable myobject. for example: myobject.line(9, 90); myobject.inserttext(9, 100, "hello, world."); myobject.saveas("c:\\drawings\\sample.drw"); note: use the getobject function when there is a current instance of the object, or if you want to create the object...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
in august 2014, the ecmascript 2015 draft specification was feature frozen and went through a stabilization and bug fixing period. ...
...mitive] (firefox 44) new promise object promise (firefox 24, enabled by default in firefox 29) new proxy object proxy (firefox 18) preventextensions() trap (firefox 22) isextensible() trap (firefox 31) getprototypeof() and setprototypeof() traps (firefox 49) new reflect object reflect (firefox 42) additions to the regexp object regexp sticky (y) flag (firefox 38) regexp unicode (u) flag (firefox 46) generic regexp.prototype.tostring (firefox 39) regexp.prototype[@@match]() (firefox 49) regexp.prototype[@@replace]() (firefox 49) regexp.prototype[@@search]() (firefox 49) regexp.prototype[@@split]() (firefox 49) get regexp[@@species] (firefox 49) additions to the string object string.fromcodepoint() (firefox 29) string.prototype.codepointat() (firefox 29) stri...
...ns to the string object string.fromcodepoint() (firefox 29) string.prototype.codepointat() (firefox 29) string.prototype.startswith(), string.prototype.endswith() (firefox 17) string.prototype.includes() (firefox 40) (formerly string.prototype.contains() (firefox 17)) string.prototype.repeat() (firefox 24) string.prototype.normalize() (firefox 31) string.raw() (firefox 34) \u{xxxxxx} unicode code point escapes (firefox 40) new symbol object symbol (firefox 36) symbol.iterator (firefox 36) symbol.for() - global symbol registry (firefox 36) symbol.match (firefox 40) symbol.species (firefox 41) symbol.toprimitive (firefox 44) symbol.prototype[@@toprimitive] (firefox 44) symbol.replace (firefox 49) symbol.search (firefox 49) symbol.split (firefox 49) symbol.hasinstance (fi...
JavaObject - Archive of obsolete content
created by any java method which returns an object type. in addition, you can explicitly construct a javaobject using the object's java constructor with the packages keyword: new packages.javaclass(parameterlist) javaclassis the fully-specified name of the object's java class. parameters parameterlist an optional list of parameters, specified by the constructor of the java class. description the javaobject object is an instance of a java class that is created in or passed to javascript. javaobject is a wrapper for the instance; all references to the class instance are made through the javaobject. ...
...e java class. description the javaobject object is an instance of a java class that is created in or passed to javascript. javaobject is a wrapper for the instance; all references to the class instance are made through the javaobject. any java data brought into javascript is converted to javascript data types. when the javaobject is passed back to java, it is unwrapped and can be used by java code. see the core javascript 1.5 guide for more information about data type conversions. properties inherits public data members from the java class of which it is an instance as properties. it also inherits public data members from any superclass as properties. methods inherits public methods from the java class of which it is an instance. the javaobject also inherits methods from java.lang.obje...
...s public data members from the java class of which it is an instance as properties. it also inherits public data members from any superclass as properties. methods inherits public methods from the java class of which it is an instance. the javaobject also inherits methods from java.lang.object and any other superclass. ...
Sharp variables in JavaScript - Archive of obsolete content
ug 566700, firefox 12. form sharp variables have the form of a sharp sign (#) immediately followed by one or more digits. the number represented by the digits serves as the variable's unique identifier, but leading 0s are ignored. scope sharp variables are only in scope in the statement in which they are defined. usage to create a sharp variable, simply assign an object to it in a line of code using an equal sign. you cannot assign primitives (including strings) to sharp variables. make sure you don't put in any spaces before the equal sign though. #1 = {}; // this doesn't do much since the sharp variable is out of scope immediately after a = #2 = {}; // slightly more useful since we retain a reference to the new object to reference the sharp variable, simply append another s...
...al sign though. #1 = {}; // this doesn't do much since the sharp variable is out of scope immediately after a = #2 = {}; // slightly more useful since we retain a reference to the new object to reference the sharp variable, simply append another sharp (#) to the end of the variable name. this acts as a reference to initial variable. you can use this to create objects in a single line of code that would otherwise take multiple lines of code. examples multiple references var a = { foo:#1=[], bar:#1# }; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" you can avoid using sharp variables by breaking the declaration up into multiple lines. var a = { foo:[], bar:undefined }; a.bar = a.foo; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); ...
... a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" you can avoid using sharp variables by breaking the declaration up into multiple lines. var a = { foo:[], bar:undefined }; a.bar = a.foo; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" cyclic references sharp variables can be used to create a circularly linked list in one line of code. var a = #1 = { val:1, next:{val:2, next:#1#} }; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; // true again, you can eliminate the need for sharp variables by using two lines instead of one for the declaration. var a = {val:1, next:{val:2, next:undefined} }; a.next.next = a; a.val; // 1 a.next.val; //...
Reference - Archive of obsolete content
in this reference: special:search?search=javascript1.2&go=go. how should they be revised? --maian 23:43, 21 september 2005 (pdt) i think we need a new section in the reference that specifies the differences between versions, collecting this information into a single location rather than leaving it scattered haphazardly throughout the reference as it currently is. once that is done, the various code samples should be updated to reflect current practices and code if they cannot be written in a "version-neutral" manner. do you think this makes sense? -- dria 04:27, 22 september 2005 (pdt) those examples are not "bad examples" per se. they are there specifically to show the differences between the two versions. i was wondering what should be done about those examples, since they would no long...
... 2005 (pdt) (more coding style questions) --maian 04:06, 31 aug 2005 (pdt) i'd say, just make a note here about decisions you make. it would be best to have all examples to use the same style. --nickolay 05:37, 31 aug 2005 (pdt) gonna follow mozilla's coding guides here: http://www.mozilla.org/hacking/mozil...de.html#visual --maian 00:30, 20 september 2005 (pdt) btoa() and atob() base64 encode and decode functions this documentation is missing the base64 encode (btoa) and decode (atob) functions. anyone know why this has been left out? danbeck 07:02, 22 september 2005 (pdt) afaict , base64-related functionality is not a part of the javascript engine, but a dom feature (probably non-standard). --nickolay 08:31, 22 september 2005 (pdt) what's funny is that this talk page shows up fir...
...od to download content/packages of content off of devmo for 'local' browsing/viewing/printing, yet. it is in the "nice to have" category for us here, however i am unaware of anyone feverishly working on it. (there are some other priorities ahead of that, imho). if downloading the stuff is your priority you are free to field ideas/concept to the devmo mailing list for discussion, and then actually code it (or find someone to do so). thanks for your thoughts --callek 15:05, 13 january 2006 (pst) notification when reorganization is finished leandro (localiser for the portuguese wiki) would like to be emailed when the js reference reorganization has been finished. his user page is here: http://developer.mozilla.org/pt/docs...%c3%aas_xavier -- dria 08:19, 24 february 2006 (pst) object and fun...
XUL Parser in Python - Archive of obsolete content
values of those attributes, and you just have to ask for them if you want them. for example, you could easily adapt this to: return the id values of all the elements take elements on the command line and only spell them out build new chrome subdirectories (i.e. new "packages") on the fly using search and replace. as i adapt the script in these ways and try to further generalize the actual code as i get time, i will make it available here. in the explanation section below, i try to say a little something about how this script works. it's really just a wrapper around python's xmllib xml parser, but i had to sort of fool around with it. python's support for xml (and potential with xul) is extensive, and so it's more a matter of choosing an approach and hooking things up than anything else...
...time, i will make it available here. in the explanation section below, i try to say a little something about how this script works. it's really just a wrapper around python's xmllib xml parser, but i had to sort of fool around with it. python's support for xml (and potential with xul) is extensive, and so it's more a matter of choosing an approach and hooking things up than anything else. source code the source code for the xul parser is available. it only runs as a hard-coded script right now, so if you want to use it you have to go in and changes some of the stuff like chrome_dir and which information you want out. it also, i'm afraid, only works on the win32 platform, where the <tt>dir</tt> command it depends on gets you your xul files. again, you can easily use <tt>ls</tt> instead, as i...
...ser from their own scripts and use it more flexibly: >>> import xultool >>> myxp = xulparser() >>> chrome_dir = 'd:\src\mozilla\xpfe' >>> res = myxp.parsexul(chrome_dir, 'window', 'id') where something like the above would write out all the xul window ids in the build. something like that, anyway. results the results from the script are written to a file called res.html. this is another hard-coded thing i have to open up. if you want to test this script you should change the filename "res.html" specified in the fourth line and compare different results files. note also that i wrote the build number into the header myself, and haven't figured out yet how to get that written automatically. i guess you could get a modify date from the files as you open them. how the script works as i said ...
Introduction to game development for the Web - Game development
other information locally so it doesn't have to be downloaded every time it's needed. also useful to help make your game playable even when the user isn't connected to the web (such as when they're stuck on an airplane for hours on end). javascript javascript, the programming language used on the web, is blazing fast in modern browsers and getting faster all the time. use its power to write the code for your game, or look at using technologies like emscripten or asm.js to easily port your existing games. pointer lock api the pointer lock api lets you lock the mouse or other pointing device within your game's interface so that instead of absolute cursor positioning you receive coordinate deltas that give you more precise measurements of what the user is doing, and prevent the user from acci...
...hat scale smoothly regardless of the size or resolution of the user's display. typed arrays javascript typed arrays give you access to raw binary data from within javascript; this lets you manipulate gl textures, game data, or anything else, even if it's not in a native javascript format. web audio api this api for controlling the playback, synthesis, and manipulation of audio from javascript code lets you create awesome sound effects as well as play and manipulate music in real time. webgl lets you create high-performance, hardware-accelerated 3d (and 2d) graphics from web content. this is a web-supported implementation of opengl es 2.0. webrtc the webrtc (real-time communications) api gives you the power to control audio and video data, including teleconferencing and transmitting oth...
...sers. want your players to be able to talk to each other while blowing up monsters? this is the api for you. websockets the websocket api lets you connect your app or site to a server to transmit data back and forth in real-time. perfect for multiplayer gaming action, chat services, and so forth. web workers workers give you the ability to spawn background threads running their own javascript code, to take advantage of modern, multi-core processors. xmlhttprequest and file api the combination of xmlhttprequest and the file api lets you send and receive any kind of data you want (don't let the "xml" throw you!) from a web server. this is a great way to do anything from downloading new game levels and artwork to transmitting non-real-time game status information back and forth. ...
Game distribution - Game development
ways in which you can distribute your newly created game into the wild. this includes hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store. benefits of html5 over native building games with html5 gives you extra advantages, such as: multiplatform bliss the technology itself is multiplatform, so you can write the code once and target multiple devices. this can range from low-end smartphones or tablets, through laptops and desktop computers, to smart tvs, watches or even a fridge if it can handle a modern enough browser. you don't need to have separate teams to work on the same title targeting different platforms with only one code base to worry about. you can spend more time and money on promotion and monetiz...
...lets, through laptops and desktop computers, to smart tvs, watches or even a fridge if it can handle a modern enough browser. you don't need to have separate teams to work on the same title targeting different platforms with only one code base to worry about. you can spend more time and money on promotion and monetization. instant updates you don't have to wait several days to have your game's code updated. if your user finds a bug, you can quickly fix it, update the system and refresh the game on your server to provide players with the updated code almost instantly. direct link distribution and instant play you don't have to tell people to search for your game in an app store with html5 games. you can just send them a direct url to access the game, which they can then click to play the g...
...your game should be unique enough to be quickly promoted later on, but also catchy enough, so people don't forget it. self-hosting if you are a front-end developer, you may already know what to do. an html5 game is just another website. you can upload it to a remote server, grab a catchy domain name, and host it yourself. if you want to make money out of game dev, you should secure your source code one way or another against people who could easily take it and sell it as their own. you can concatenate and minify the code to make it smaller and uglify it so it's a lot harder to reverse engineer your game. another good measure to take is to provide an online demo if you're planning on packaging it and selling it in a closed store like itunes or steam. if you're working on a side project just...
3D games on the Web - Game development
.js babylon.js is one of the most popular 3d game engines used by developers. as with any other 3d library, it provides built-in functions to help you implement common 3d functionality more quickly. see the building up a basic demo with babylon.js subpage for the basics of using babylon.js, including setting up a development environment, structuring the necessary html, and writing the javascript code. building up a basic demo with playcanvas playcanvas is a popular 3d webgl game engine open-sourced on github, with an editor available online and good documentation. see the building up a basic demo with playcanvas subpage for higher-level details, and further articles showing how to create demos using the playcanvas library, and the online editor. building up a basic demo with three.js thre...
...n github, with an editor available online and good documentation. see the building up a basic demo with playcanvas subpage for higher-level details, and further articles showing how to create demos using the playcanvas library, and the online editor. building up a basic demo with three.js three.js, like any other library, gives you a huge advantage: instead of writing hundreds of lines of webgl code to build anything interesting you can use built-in helper functions to do it a lot easier and faster. see the building up a basic demo with three.js subpage for the step-by-step process of creating the demo. other tools both unity and unreal can export your game to webgl with asm.js, so you're free to use their tools and techniques to build games that will be exported to the web. where to go...
...port your game to webgl with asm.js, so you're free to use their tools and techniques to build games that will be exported to the web. where to go next with this article we just scratched the surface of what's possible with currently available technologies. you can build immersive, beautiful and fast 3d games on the web using webgl, and the libraries and frameworks build on top of it. source code you can find all the source code for this series demos on github. apis canvas api webgl api frameworks three.js whitestorm.js (based on three.js) playcanvas babylon.js a-frame tutorials building up a basic demo with three.js building up a basic demo with whitestorm.js building up a basic demo with playcanvas building up a basic demo with babylon.js building up a basic demo...
Desktop gamepad controls - Game development
previous overview: control mechanisms next now we'll look at adding something extra — support for gamepad controls, via the gamepad api. it brings a console-like experience to your web games. the gamepad api gives you the ability to connect a gamepad to your computer and detect pressed buttons directly from the javascript code thanks to the browsers implementing such feature. an api exposes all the information you need to hook up your game's logic and successfully control the user interface and gameplay. api status, browser and hardware support the gamepad api is still in working draft status, although browser support is already quite good — around 63% global coverage, according to caniuse.com. the list of supported devices is also quite extensive — most popular gamep...
...ecking out if gamepadbuttonpressedhandler(3) is pressed, you could do a more descriptive check: gamepadbuttonpressedhandler('dpad-right'). you can see a live demo in action — try connecting your gamepad and pressing the buttons. phaser approach let's move on to the final gamepad api implementation in the captain rogers: battle at andromeda game we created with phaser. this is pure javascript code however too, so can be used in any other project no matter what framework was used. first off, we'll create a small library that will take care of handling the input for us. here's the gamepadapi object, which contains useful variables and functions: var gamepadapi = { active: false, controller: {}, connect: function(event) {}, disconnect: function(event) {}, update: functio...
...plementation we now know what the gamepadapi object looks like and what variables and functions it contain, so let's learn how all this is actually used in the game. to indicate that the gamepad controller is active we can show the user some custom text on the game's main menu screen. the textgamepad object holds the text saying a gamepad has been connected, and is hidden by default. here's the code we've prepared in the create() function that is executed once when the new state is created: create() { // ... var message = 'gamepad connected! press y for controls'; var textgamepad = this.add.text(message, ...); textgamepad.visible = false; } in the update() function, which is executed every frame, we can wait until the controller is actually connected, so the proper text can...
Efficient animation for web games - Game development
starttime = timestamp; } else { progress = timestamp - starttime; } // do animation ... if (progress < animationlength) { requestanimationframe(doanimation); } } // start animation requestanimationframe(doanimation); you will note that we set starttime to -1 at the beginning, when we could just as easily have set the time using the date() object and avoided the extra code in the animation callback. we do this so that any setup or processes that happen between the start of the animation and the callback being processed do not affect the start of the animation, and so that all the animations we start before the frame is processed are synchronised. to save battery life, it is best to only draw when there are things going on, so that would mean calling requestanimati...
... still being playable on low-end devices (such as a firefox os geeksphone keon). it would have been good to use as much third party software as possible, but most of what we tried was either too complicated for simple use-cases, or had performance issues on mobile. how this conclusion was reached, however, is more important than the conclusion itself. to begin with, the priority was to write the code quickly to iterate on gameplay (and we’d certainly recommend doing this). we assumed that our own, naive code was making the game slower than we would like. to an extent, this was true: we found plenty to optimise in our own code, but it got to the point where we knew what we were doing ought to perform quite well, and it still wasn’t quite there. at this point, we turned to the firefox javas...
...er than we would like. to an extent, this was true: we found plenty to optimise in our own code, but it got to the point where we knew what we were doing ought to perform quite well, and it still wasn’t quite there. at this point, we turned to the firefox javascript profiler, and this told us almost exactly what low-hanging-fruit was left to address to improve performance. as it turned out, the code from some of the things mentioned above; the animation code had some corner cases where redraws were happening several times per frame, and some of the animations caused firefox to need to redraw everything (they were fine in other browsers, as it happens — that particular issue is now fixed). some of the third party code we were using was poorly optimised. a take-away to help combat poor ani...
Square tilemaps implementation: Scrolling maps - Game development
ing this. only a section of the map will be rendered. if the map is bigger than the viewport, we can obviously only display a part of it at a time, whereas non-scrolling maps are usually rendered wholly. to handle these issues, we need to slightly modify the rendering algorithm. let's imagine that we have the camera pointing at (5,10). that means that the first tile would be 0x0. in the demo code, the starting point is stored at startcol and startrow. it's convenient to also pre-calculate the last tile to be rendered. var startcol = math.floor(this.camera.x / map.tsize); var endcol = startcol + (this.camera.width / map.tsize); var startrow = math.floor(this.camera.y / map.tsize); var endrow = startrow + (this.camera.height / map.tsize); once we have the first tile, we ne...
... there's another demo available, that shows how to make the camera follow a character. ...
... there's another demo available, that shows how to make the camera follow a character. ...
Square tilemaps implementation: Static maps - Game development
drawimage() with these values: context.drawimage(atlasimage, 192, 0, 64, 64, 128, 320, 64, 64); in order to support atlases with multiple rows and columns, you would need to know how many rows and columns there are to be able to compute the source x and y. the tilemap data structure to store that map data, we can use a plain object or a custom class. for the sake of simplicity, in the example code a plain object has been used. it contains the basic map properties: cols: the width of the map, in columns. rows: the height of the map, in rows. tsize: the tile size, in pixels. tiles: a 1-dimensional array containing the visual grid. gettile(): a helper method that gets the tile index in a certain position. tiles contains the actual visual map data. we are representing the tiles with i...
... ...
... ...
Finishing up - Game development
« previous this is the 10th and final step of the gamedev canvas tutorial. you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson10.html. there's always room for improvements in any game we write. for example, we can offer more than one life to the player. they could make a mistake or two and still be able to finish the game. we could also improve our code rendering. giving the player some lives implementing lives is quite straightforward. ...
...nd still be able to finish the game. we could also improve our code rendering. giving the player some lives implementing lives is quite straightforward. let's first add a variable to store the number of lives in the same place where we declared our other variables: var lives = 3; drawing the life counter looks almost the same as drawing the score counter — add the following function to your code, below the drawscore() function: function drawlives() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("lives: "+lives, canvas.width-65, 20); } instead of ending the game immediately, we will decrease the number of lives until they are no longer available. we can also reset the ball and the paddle positions when the player begins with their next life. so, in the dr...
... the draw() function is now getting executed again and again within a requestanimationframe() loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the framerate back to the browser. it will sync the framerate accordingly and render the shapes only when needed. this produces a more efficient, smoother animation loop than the older setinterval() method. compare your code that's all — the final version of the game is ready and set to go ! exercise: change the number of lives and the angle the ball bounces off the paddle. game over - for now! you've finished all the lessons - congratulations! by this point, you should now know the basics of canvas manipulation and the logic behind simple 2d games. now it's a good time to learn some frameworks and continue...
Mouse controls - Game development
the game itself is actually finished, so let's work on polishing it up. we have already added keyboard controls, but we could easily add mouse controls too. listening for mouse movement listening for mouse movement is even easier than listening for key presses: all we need is the listener for the mousemove event. ...
... the mousemove event. add the following line in the same place as the other event listeners, just below the keyup event: document.addeventlistener("mousemove", mousemovehandler, false); anchoring the paddle movement to the mouse movement we can update the paddle position based on the pointer coordinates — the following handler function will do exactly that. ...
...and the paddlex position (anchored on the left edge of the paddle) is set to the relativex value minus half the width of the paddle, so that the movement will actually be relative to the middle of the paddle. the paddle will now follow the position of the mouse cursor, but since we're restricting the movement to the size of the canvas, it won't disappear completely off either side. compare your code this is the latest state of the code to compare against: exercise: adjust the boundaries of the paddle movement, so the whole paddle will be visible on both edges of the canvas instead of only half of it. next steps now we've got a complete game we'll finish our series of lessons with some more small tweaks — finishing up. « previousnext » ...
Collision detection - Game development
« previousnext » this is the 10th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson10.html. now onto the next challenge — the collision detection between the ball and the bricks. luckily enough we can use the physics engine to check collisions not only between single objects (like the ball and the paddle), but also between an object and the group. brick/ball collision detection the physics engine makes everything a lot easier — we just need to add two simple pieces of code. first, add a new line inside your update() function that checks for collision detection between ball and bricks, as shown below: function update() { game.physics.arcade.collid...
... game.physics.arcade.collide(ball, paddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } the ball's position is calculated against the positions of all the bricks in the group. the third, optional parameter is the function executed when a collision occurs — ballhitbrick(). create this new function as the bottom of your code, just before the closing </script> tag, as follows: function ballhitbrick(ball, brick) { brick.kill(); } and that's it! reload your code and you should see the new collision detection working just as required. thanks to phaser there are two parameters passed to the function — the first one is the ball, which we explicitly defined in the collide method, and the second one is the single b...
...nd one is the single brick from the bricks group that the ball is colliding with. inside the function we remove the brick in question from the screen simply by running the kill() method on it. you would expect to have to write a lot more calculations of your own to implement collision detection when using pure javascript. that's the beauty of using the framework — you can leave a lot of boring code to phaser, and focus on the most fun and interesting parts of making a game. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we can hit the bricks and remove them, which is a nice addition to the gameplay already. it would be even better to count the destroyed bricks increment the score ...
Game over - Game development
« previousnext » this is the 8th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson08.html. to make the game more interesting we can introduce the ability to lose — if you don't hit the ball before it reaches the bottom edge of the screen it will be game over. how to lose to provide the ability to lose, we will disable the ball's collision with the bottom edge of the screen. ...
...e as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson08.html. to make the game more interesting we can introduce the ability to lose — if you don't hit the ball before it reaches the bottom edge of the screen it will be game over. how to lose to provide the ability to lose, we will disable the ball's collision with the bottom edge of the screen. add the code below inside the create() function; just after you define the ball's attributes is fine: game.physics.arcade.checkcollision.down = false; this will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it. we need a way to detect this and act accordingly. add the following lines just be...
...w the previous new one: ball.checkworldbounds = true; ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event. when you click on the resulting alert, the page will be reloaded so you can play again. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now the basic gameplay is in place let's make it more interesting by introducing bricks to smash — it's time to build the brick field. « previousnext » ...
Randomizing gameplay - Game development
our game appears to be completed, but if you look close enough you'll notice that the ball is bouncing off the paddle at the same angle throughout the whole game. this means that every game is quite similar. to fix this and improve playability we should make the rebound angles more random, and in this article we'll look at how. ...
...game is quite similar. to fix this and improve playability we should make the rebound angles more random, and in this article we'll look at how. making rebounds more random we can change the ball's velocity depending on the exact spot it hits the paddle, by modifying the x velocity each time the ballhitpaddle() function is run using a line along the lines of the below. add this new line to your code now, and try it out. function ballhitpaddle(ball, paddle) { ball.animations.play('wobble'); ball.body.velocity.x = -1*5*(paddle.x-ball.x); } it's a little bit of magic — the new velocity is higher, the larger the distance between the center of the paddle and the place where the ball hits it. also, the direction (left or right) is determined by that value — if the ball hits the left ...
...l hits the left side of the paddle it will bounce left, whereas hitting the right side will bounce it to the right. it ended up that way because of a little bit of experimentation with the given values, you can do your own experimentation and see what happens. it's not completely random of course, but it does make the gameplay a bit more unpredictable and therefore more interesting. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: summary you've finished all the lessons — congratulations! by this point you would have learnt the basics of phaser and the logic behind simple 2d games. exercises to follow you can do a lot more in the game — add whatever you feel would be best to make it more fu...
Scaling - Game development
scaling refers to how the game canvas will scale on different screen sizes. we can make the game scale to fit on any screen size automatically during the preload stage, so we don't have to worry about it later. the phaser scale object there's a special scale object available in phaser with a few handy methods and properties available. ...
... of the screen, but we can live with that. resize — creates the canvas with the same size as the available width and height, so you have to place the objects inside your game dynamically; this is more of an advanced mode. user_scale — allows you to have custom dynamic scaling, calculating the size, scale and ratio on your own; again, this is more of an advanced mode the other two lines of code in the preload() function are responsible for aligning the canvas element horizontally and vertically, so it is always centered on screen regardless of size. adding a custom canvas background colour we can also add a custom background color to our canvas, so it won't stay black. the stage object has a backgroundcolor property for this purpose, which we can set using css color definition syntax.
...s centered on screen regardless of size. adding a custom canvas background colour we can also add a custom background color to our canvas, so it won't stay black. the stage object has a backgroundcolor property for this purpose, which we can set using css color definition syntax. add the following line below the other three you added earlier: game.stage.backgroundcolor = '#eee'; compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now we've set up the scaling for our game, let's continue to the third lesson and work out how to load the assets and print them on screen. « previousnext » ...
Win the game - Game development
« previousnext » this is the 12th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson12.html. implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win. ...
... « previousnext » this is the 12th step out of 16 of the gamedev phaser tutorial. you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson12.html. implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win. ...
...++; } } if (count_alive == 0) { alert('you won the game, congratulations!'); location.reload(); } } we loop through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method. if there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps both losing and winning are implemented, so the core gameplay of our game is finished. now let's add something extra — we'll give the player three lives instead of one. « previousnext » ...
Visual-js game engine - Game development
editor style . or you can use visual-js source editor. visual-js source editor (2d part only) is new and better way .in future visual staff will be better (real time simulator will be implemented).for now this place is good for coding . visual-js works direct with project files , no need for build . add->new game object (form dialog for define type of new game object ) add->quick code (make your work faster - add usually code blocks) resources - explorer view for images and audios , you can drag or edit also need to execute node build_resources for creating resources object for engine. inserting new code will be always at current line selected intro editor . save on drop menu or better with ctrl+s before testing in browsers. adding new script explanation : after adding ...
...en starter/run.js and you will found line : sys.script.load("scripts/new_script.js") ctrl+s use from menu run->choose browser for testing . - important safari not working at the moment chrome , firefox , opera tutorial - pencil (animation path) : how to use pencil tool to create path object . path object can be saved intro localhost , you can collect object and put it direct source code . file location : starter/templates/paths.js templetes are made from visual-js core also . see source code : paths.js see the pen visual js - pencil by visualjs game engine (@zlatnaspirala) on codepen. online demo examples at : https://jsfiddle.net/user/zlatnaspirala/fiddles/ demo slot mashine basic demo at : https://jsfiddle.net/zlatnaspirala/7d0d8v6d/ help about new 2d part - i...
...tures : tile's background draw for images (alias sprite - but for now there's no sprite and frame by frame animation methods). small engine config . some option in aspect view like npm install ... npm install typescript npm i clean-webpack-plugin --save-dev npm i html-webpack-plugin --save-dev possible fix : npm i webpack --save-dev npm i extract-text-webpack-plugin --save-dev fix code format : tslint -c tslint.json 'src/**/*.ts' --fix download project link : download link from bitbucket. ...
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
in computer science, a boolean is a logical data type that can have only the values true or false. for example, in javascript, boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). below is some javascript pseudocode (it's not truly executable code) demonstrating this concept. ...
... is a logical data type that can have only the values true or false. for example, in javascript, boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). below is some javascript pseudocode (it's not truly executable code) demonstrating this concept. ...
...t truly executable code) demonstrating this concept. /* javascript if statement */ if (boolean conditional) { // code to execute if the conditional is true } if (boolean conditional) { console.log("boolean conditional resolved to true"); } else { console.log("boolean conditional resolved to false"); } /* javascript for loop */ for (control variable; boolean conditional; counter) { // code to execute repeatedly if the conditional is true } for (var i=0; i < 4; i++) { console.log("i print only when the boolean conditional is true"); } the boolean value is named after english mathematician george boole, who pioneered the field of mathematical logic. learn more general knowledge boolean on wikipedia technical reference the javascript global object: boolean javascript d...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
the control flow is the order in which the computer executes statements in a script. code is run in order from the first line in the file to the last line, unless the computer runs across the (extremely frequent) structures that change the control flow, such as conditionals and loops. for example, imagine a script used to validate user data from a webpage form. the script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in. ...
...uns across the (extremely frequent) structures that change the control flow, such as conditionals and loops. for example, imagine a script used to validate user data from a webpage form. the script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in. to do this, the script uses a conditional structure or if...else, so that different code executes depending on whether the form is complete or not: if (field==empty) { promptuser(); } else { submitform(); } a typical script in javascript or php (and the like) includes many control structures, including conditionals, loops and functions. parts of a script may also be set to execute when events occur. for example, the above excerpt might be inside a function that runs when ...
...es many control structures, including conditionals, loops and functions. parts of a script may also be set to execute when events occur. for example, the above excerpt might be inside a function that runs when the user clicks the submit button for the form. the function could also include a loop, which iterates through all of the fields in the form, checking each one in turn. looking back at the code in the if and else sections, the lines promptuser and submitform could also be calls to other functions in the script. as you can see, control structures can dictate complex flows of processing even with only a few lines of code. control flow means that when you read a script, you must not only read from start to finish but also look at program structure and how it affects order of execution. l...
Cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
more than just data confidentiality, cryptography also tackles identification, authentication, non-repudiation, and data integrity. ...
...more than just data confidentiality, cryptography also tackles identification, authentication, non-repudiation, and data integrity. ...
...more than just data confidentiality, cryptography also tackles identification, authentication, non-repudiation, and data integrity. ...
Identifier - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, there is no way to convert identifiers to strings, but sometimes it is possible to parse strings into identifiers. ...
...in javascript, there is no way to convert identifiers to strings, but sometimes it is possible to parse strings into identifiers. ...
...in javascript, there is no way to convert identifiers to strings, but sometimes it is possible to parse strings into identifiers. ...
PHP - MDN Web Docs Glossary: Definitions of Web-related terms
php (a recursive initialism for php: hypertext preprocessor) is an open-source server-side scripting language that can be embedded into html to build web applications and dynamic websites. ...
... php (a recursive initialism for php: hypertext preprocessor) is an open-source server-side scripting language that can be embedded into html to build web applications and dynamic websites. ...
... php (a recursive initialism for php: hypertext preprocessor) is an open-source server-side scripting language that can be embedded into html to build web applications and dynamic websites. ...
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
a packet, or network packet, is a formatted chunk of data sent over a network. the maincomponents of a network packet are the user data and control information. the user data is known as the payload. the control information is the information for delivering the payload. it consists of network addresses for the source and destination, sequencing information, and error detection codes and is generally found in packet headers and footer. a packet contains: hop limit a hop occurs when a packet is passed from one network to the next network. it is a field that is decreases by one each time a packet goes through, once it reaches 0 it has failed and the packet is discarded. over time the number packets can cause traversing within closed circuits, the number of pa ckets circulati...
...work. it is a field that is decreases by one each time a packet goes through, once it reaches 0 it has failed and the packet is discarded. over time the number packets can cause traversing within closed circuits, the number of pa ckets circulating would build up and then ultimately lead to the networking in failing. ...
...when received at the destination, the checksum is recalculated, and compared with the one in the packet. priority this field indicates which packet should have higher priority over the others. ...
SCM - MDN Web Docs Glossary: Definitions of Web-related terms
some scm systems include cvs, svn, git. ...
... some scm systems include cvs, svn, git. ...
... some scm systems include cvs, svn, git. ...
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) semantics in javascript in javascript, consider a function that takes a string parameter, and returns an <li> element with that string as its textcontent. would you need to look at the code to understand what the function did if it was called build('peach'), or createliwithcontent('peach')? semantics in css in css, consider styling a list with li elements representing different types of fruits. would you know what part of the dom is being selected with div > ul > li, or .fruits__item? semantics in html in html, for example, the <h1> element is a se...
...u could make any element look like a top level heading. consider the following: <span style="font-size: 32px; margin: 21px 0;">is this a top level heading?</span> this will render it to look like a top level heading, but it has no semantic value, so it will not get any extra benefits as described above. it is therefore a good idea to use the right html element for the right job. html should be coded to represent the data that will be populated and not based on its default presentation styling. presentation (how it should look), is the sole responsibility of css. some of the benefits from writing semantic markup are as follows: search engines will consider its contents as important keywords to influence the page's search rankings (see seo) screen readers can use it as a signpost to help...
...ault presentation styling. presentation (how it should look), is the sole responsibility of css. ...
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
a loop is a sequence of instructions that is continually repeated until a certain condition is met in computer programming. an example would be the process of getting an item of data and changing it, and then making sure some condition is checked such as, if a counter has reached a prescribed number. examples for loop syntax: for (statement 1; statement 2; statement 3){ execute code block } statement 1 is executed once before the code block is run. statement 2 defines the condition needed to execute the code block. statement 3 is executed every time the code block is run. example: for(var i = 0; i < 10; i++){ console.log(i) } //this loop will print numbers 0-9, will stop when condition is met (i = 10) for the above example, the syntax is as follows: statement 1 se...
...is executed every time the code block is run. example: for(var i = 0; i < 10; i++){ console.log(i) } //this loop will print numbers 0-9, will stop when condition is met (i = 10) for the above example, the syntax is as follows: statement 1 sets the variable for the loop (var i = 0). statement 2 sets the loop condition (i < 10). statement 3 increases the value of i (i++) each time the code block is run. while loop syntax: while (condition){ execute code block } the code block will continue to loop as long as the condition is true. ...
...the value of i (i++) each time the code block is run. while loop syntax: while (condition){ execute code block } the code block will continue to loop as long as the condition is true. example: var i = 0; while(i < 5){ console.log(i) i++ } //this loop will print number 0-4, will stop when condition becomes false (i >=5) for the above example, the syntax is as follows: the code block will continue to run as long as the variable (i) is less than 5. ...
MDN Web Docs Glossary: Definitions of Web-related terms
canvas card sorting carddav caret cdn certificate authority certified challenge-response authentication character character encoding character set chrome cia cipher cipher suite ciphertext class client hints closure cms code splitting codec compile compile time computer programming conditional constant constructor continuous media control flow cookie copyleft cors cors-safelisted request header cors-safelisted response header crawler crlf cross axis cross-si...
...ject parse parser pdf perceived performance percent-encoding php pixel placeholder names plaintext png polyfill polymorphism pop3 port prefetch preflight request prerender presto primitive privileged privileged code progressive enhancement progressive web apps promise property property (css) property (javascript) protocol prototype prototype-based programming proxy server pseudo-class pseudo-element pseudocode public-key cryptography python q quality ...
...e to first byte time to interactive tld tofu transmission control protocol (tcp) transport layer security (tls) tree shaking trident truthy ttl turn type type coercion type conversion u udp (user datagram protocol) ui undefined unicode uri url urn usenet user agent utf-8 ux v validator value variable vendor prefix viewport visual viewport voip w w3c wai wcag web performance web server web standards webassembly ...
Mobile accessibility - Learn web development
swiping up and left in a smooth motion. if you have more than one home screen, you can move between them by swiping two fingers left and right. for a more complete list of talkback gestures, see use talkback gestures. unlocking the phone when talkback is turned on, unlocking the phone is a bit different. you can do a two-finger swipe up from the bottom of the lock screen. if you've set a passcode or pattern for unlocking your device, you will then be taken to the relevant entry screen to enter it. you can also explore by touch to find the unlock button at the bottom middle of the screen, and then double-tap. global and local menus talkback allows you to access global and local context menus, wherever you have navigated to on the device. the former provides global options relating to th...
...hrough a page. tap with two fingers to perform a context-relevant action — for example, taking a photo while in the camera app. to turn it off again, navigate back to settings > general > accessibility > voiceover using the above gestures, and toggle the voiceover slider back to off. unlock phone to unlock the phone, you need to press the home button (or swipe) as normal. if you have a passcode set, you can select each number by swiping/sliding (as explained above) and then double-tapping to enter each number when you've found the right one. using the rotor when voiceover is turned on, you have a navigation feature called the rotor available to you, which allows you to quickly choose from a number of common useful options. to use it: twist two fingers around on the screen like you ...
...e. try our simple-button-example.html example (see it running live) to see what we mean. alternatively, mouse-specific events such as mousedown and mouseup create problems — their event handlers cannot be invoked using non-mouse controls. if you try to control our simple-box-drag.html (see example live) example with a keyboard or touch, you'll see the problem. ...
Backgrounds and borders - Learn web development
acts just like an image and is also set by using the background-image property. you can read more about the different types of gradients and things you can do with them on the mdn page for the <gradient> data type. a fun way to play with gradients is to use one of the many css gradient generators available on the web, such as this one. you can create a gradient then copy and paste out the source code that generates it. try some different gradients in the example below. in the two boxes respectively, we have a linear gradient that is stretched over the whole box, and a radial gradient with a set size, which therefore repeats. multiple background images it is also possible to have multiple background images — you specify multiple background-image values in a single property value, separa...
...ssible to have multiple background images — you specify multiple background-image values in a single property value, separating each one with a comma. when you do this you may end up with background images overlapping each other. the backgrounds will layer with the last listed background image at the bottom of the stack, and each previous image stacking on top of the one that follows it in the code. note: gradients can be happily mixed with regular background images. the other background-* properties can also have comma-separated values in the same way as background-image: background-image: url(image1.png), url(image2.png), url(image3.png), url(image4.png); background-repeat: no-repeat, repeat-x, repeat; background-position: 10px 20px, top right; each value of the different propertie...
...ally do what you want in many cases. the local value fixes the background to the element it is set on, so when you scroll the element, the background scrolls with it. the background-attachment property only has an effect when there is content to scroll, so we've made a demo to demonstrate the differences between the three values — have a look at background-attachment.html (also see the source code here). using the background shorthand property as i mentioned at the beginning of this lesson, you will often see backgrounds specified using the background property. this shorthand lets you set all of the different properties at once. if using multiple backgrounds, you need to specify all of the properties for the first background, then add your next background after a comma. in the example b...
Creating fancy letterheaded paper - Learn web development
s in this module. objective: to test comprehension of css box model, and other box-related features such as implementing backgrounds. starting point to get this assessment started, you should: make local copies of the html and css — save them as index.html and style.css in a new directory. save local copies of the top, bottom and logo images in the same directory as your code files. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html and fill in the css into one of these online editors. if the online editor you are using doesn't have a separate css panel, feel free to put it in a <style> element in the head of the document. note: if you get stuck, then ask us for help — see the assessment or further help secti...
...s will apply the first one, then override it with the second one. feel free to create your own graphics for the assessment if you wish. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for creating fancy letterheaded paper". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example...
...y letterheaded paper". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
CSS values and units - Learn web development
a simple and understandable way of specifying color. there are a number of these keywords, some of which have fairly entertaining names! you can see a full list on the page for the <color> value. try playing with different color values in the live examples below, to get more of an idea how they work. hexadecimal rgb values the next type of color value you are likely to encounter is hexadecimal codes. each hex value consists of a hash/pound symbol (#) followed by six hexadecimal numbers, each of which can take one of 16 values between 0 and f (which represents 15) — so 0123456789abcdef. each pair of values represents one of the channels — red, green and blue — and allows us to specify any of the 256 available values for each (16 x 16 = 256.) these values are a bit more complex and les...
... with and without alpha channel values. try changing the above example's rgba() functions to rgb() and see if the colors still work! which style you use is up to you, but separating out non-transparent and transparent color definitions to use the different functions gives (very) slightly better browser support and can act as a visual indicator of where transparent colors are being defined in your code. hsl and hsla values slightly less well-supported than rgb is the hsl color model (not supported on old versions of ie), which was implemented after much interest from designers. instead of red, green, and blue values, the hsl() function accepts hue, saturation, and lightness values, which are used to distinguish between the 16.7 million colors, but in a different way: hue: the base shade o...
...here you use strings in css, for example when specifying generated content. in this case the value is quoted to demonstrate that it is a string. in the below example we use unquoted color keywords along with a quoted generated content string. functions the final type of value we will take a look at is the group of values known as functions. in programming, a function is a reusable section of code that can be run multiple times to complete a repetitive task with minimum effort on the part of both the developer and the computer. functions are usually associated with languages like javascript, python, or c++, but they do exist in css too, as property values. we've already seen functions in action in the colors section — rgb(), hsl(), etc. the value used to return an image from a file — u...
Beginner's guide to media queries - Learn web development
teps and css building blocks.) objective: to understand how to use media queries, and the most common approach for using them to create responsive designs. media query basics the simplest media query syntax looks like this: @media media-type and (media-feature-rule) { /* css rules go here */ } it consists of: a media type, which tells the browser what kind of media this code is for (e.g. print, or screen). a media expression, which is a rule, or test that must be passed for the contained css to be applied. a set of css rules that will be applied if the test passes and the media type is correct. media types the possible types of media you can specify are: all print screen speech the following media query will only set the body to 12pt if the page is print...
...view wider until you can see that the line lengths are becoming quite long, and we have space for the navigation to display in a horizontal line. this is where we'll add our first media query. we'll use ems, as this will mean that if the user has increased their text size, the breakpoint will happen at a similar line-length but wider viewport, than someone with a smaller text size. add the below code into the bottom of your step1.html css. @media screen and (min-width: 40em) { article { display: grid; grid-template-columns: 3fr 1fr; column-gap: 20px; } nav ul { display: flex; } nav li { flex: 1; } } this css gives us a two-column layout inside the article, of the article content and related information in the aside element. ...
...idebar to also form a new column. inside a media query we'll make the main element into a two column grid. we then need to remove the margin-bottom on the article in order that the two sidebars align with each other, and we'll add a border to the top of the footer. typically these small tweaks are the kind of thing you will do to make the design look good at each breakpoint. again, add the below code into the bottom of your step1.html css. @media screen and (min-width: 70em) { main { display: grid; grid-template-columns: 3fr 1fr; column-gap: 20px; } article { margin-bottom: 0; } footer { border-top: 1px solid #ccc; margin-top: 2em; } } open step 3 in the browser, or view the source. if you look at the final example ...
Test your skills: Media Queries and Responsive Design - Learn web development
this aim of this task is to get you working with responsive web design with a practical task. everything you need to know to complete this task was covered in the guide to media queries, and the other layout lessons in this section. note: due to the need to test your design in multiple screen sizes we do not have an interactive editor for this task. download the code and work locally, or 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. your task download the starting point. open this in your browser and you will find a wireframed site which will load in a mobile device in a readable manner. you can drag your window smaller or use the responsi...
...te the desktop layout, enjoy experimenting. you could also add a second breakpoint perhaps creating a layout that would work well on a tablet in portrait mode. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for responsive web design assessment". details of what you have already tried, and what you would li...
...eb design assessment". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
Using your new knowledge - Learn web development
new-found knowledge. starting point you can work in the live editor below, or you can download the starting point to work with in your own editor. this is a single page with the html, plus the starting point css in the head of the document. if you prefer you could move this css to a separate file when you create the example on your local computer. alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. working with css the following live example shows a biography, which has been styled using css. the css properties that i have used are as follows — each one links to its property page on mdn, which will give you more examples...
... afterwards try looking up some properties not mentioned on this page in the mdn css reference and get adventurous! remember that there is no wrong answer here — at this stage in your learning you can afford to have a bit of fun. assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for css first steps". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed...
... for css first steps". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. what's next? congratulations on finishing this first module. you should now have a good general understanding of css, and be able to understand much of what is happening in a stylesheet. in the next module, css building blocks, we will go on to look at a number of key areas in depth. pre...
Typesetting a community school homepage - Learn web development
; we'll let you off in this instance. fonts: first of all, download a couple of free-to-use fonts. because this is a college, the fonts should be chosen to give the page a fairly serious, formal, trustworthy feel — a serif site-wide font for the general text body, coupled with sans-serif or slab serif for the headings might be nice. use a suitable service to generate bulletproof @font-face code for these two fonts. apply your body font to the whole page, and your heading font to your headings. general text styling: give the page a site-wide font-size of 10px. give your headings and other element types appropriate font-sizes defined using a suitable relative unit. give your body text a suitable line-height. center your top level heading on the page. give your headings a little ...
...be a bit taller so that it doesn't look silly on the side of the page; also remember that you need to make this one a vertical nav menu. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for typesetting a community school homepage". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the e...
...nity school homepage". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. previous overview: styling text in this module fundamental text and font styling styling lists styling links web fonts typesetting a community school homepage ...
The HTML5 input types - Learn web development
e="email" multiple> on some devices — notably, touch devices with dynamic keyboards like smart phones — a different virtual keypad might be presented that is more suitable for entering email addresses, including the @ key. see the firefox for android keyboard screenshot below for an example: note: you can find examples of the basic text input types at basic input examples (see the source code also). this is another good reason for using these newer input types — improving the user experience for users of these devices. client-side validation as you can see above, email, along with other newer input types, provides built-in client-side error validation — performed by the browser before the data gets sent to the server. it is a helpful aid to guide users to fill out a form accur...
...ue is restricted to any value between 0 and 1 inclusive, and whose increase and decrease buttons change its value by 0.01. <input type="number" name="change" id="pennies" min="0" max="1" step="0.01"> the number input type makes sense when the range of valid values is limited, for example a person's age or height. if the range is too large for incremental increases to make sense (such as usa zip codes, which range from 00001 to 99999), the tel type might be a better option; it provides the numeric keypad while forgoing the number's spinner ui feature. note: number inputs are not supported in versions of internet explorer below 10. slider controls another way to pick a number is to use a slider. you see these quite often on sites like housebuying sites where you want to set a maximum prop...
...ortant. a slider is created using the <input> with its type attribute set to the value range. the slider-thumb can be moved via mouse or touch, or with the arrows of the keypad. it's important to properly configure your slider. to that end, it's highly recommended that you set the min, max, and step attributes which set the minimum, maximum and increment values, respectively. let's look at the code behind the above example, so you can see how its done. first of all, the basic html: <label for="price">choose a maximum house price: </label> <input type="range" name="price" id="price" min="50000" max="500000" step="100" value="250000"> <output class="price-output" for="price"></output> this example creates a slider whose value may range between 50000 and 500000, which increments/decrements b...
Styling web forms - Learn web development
organizing your assets this is where the fun begins! before we start coding, we need three additional assets: the postcard background — download this image and save it in the same directory as your working html file. a typewriter font: the "secret typewriter" font from fontsquirrel.com — download the ttf file into the same directory as above. a handdrawn fon...
...ind some font files (at the time of writing, two .woff files and two .woff2 files; they might vary in the future.) copy these files into a directory called fonts, in the same directory as before. we are using two different files for each font to maximise browser compatibility; see our web fonts article for a lot more information. the css now we can dig into the css for the example. add all the code blocks shown below inside the <style> element, one after another. overall layout first, we prepare by defining our @font-face rules, and all the basic styles set on the <body> and <form> elements. if the fontsquirrel output was different to what we described above, you can find the correct @font-face blocks inside your downloaded webfont kit, in the stylesheet.css file (you'll need to replace t...
... 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: styling basics. summary as you can see, as long as we want to build forms with just text fields and buttons, it's easy to style them using css. in the next ...
Test your skills: Styling basics - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. styling basics 1 our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. ...
...e kind of layout technique to make the inputs and labels line up neatly. download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for styling basics 1 skill test". details of what you have already tried, and what you would like us...
... basics 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
What will your website look like? - Learn web development
what should your website actually do? a website can do basically anything, but, for your first try, you should keep things simple. we'll start by creating a simple webpage with a heading, an image, and a few paragraphs. ...
...e and interact with the website. choosing your assets at this point, it's good to start putting together the content that will eventually appear on your webpage. text you should still have your paragraphs and title from earlier. keep these close by. theme color to choose a color, go to the color picker and find a color you like. when you click on a color, you'll see a strange six-character code like #660066. that's called a hex code (short for hexadecimal), and represents your color. copy the code down somewhere safe for now. images to choose an image, go to google images and search for something suitable. when you find the image you want, click on the image to get an enlarged view of it. right-click the image (ctrl + click on a mac), choose save image as..., and choose a safe p...
...choose a font: go to google fonts and scroll down the list until you find one you like. you can also use the controls on the right to further filter the results. click the "plus" (add to) icon next to the font you want. click the "* family selected" button in the panel at the bottom of the page ("*" depends on how many fonts you selected). in the popup box, you can see and copy the lines of code google gives you into your text editor to save for later. previous overview: getting started with the web next in this module installing basic software what will your website look like? dealing with files html basics css basics javascript basics publishing your website how the web works ...
Use JavaScript within a webpage - Learn web development
arn how to trigger javascript in your html file, and learn the most important best practices for keeping javascript accessible. about javascript javascript is a programming language mostly used client-side to make webpages interactive. you can create amazing webpages without javascript, but javascript opens up a whole new level of possibilities. in this article we're going over the html code you need to make javascript take effect. if you want to learn javascript itself, you can start with our javascript basics article. if you already know something about javascript or if you have a background with other programming languages, we suggest you jump directly into our javascript guide. how to trigger javascript from html within a browser, javascript doesn't do anything by itself. you ...
...ascript itself, you can start with our javascript basics article. if you already know something about javascript or if you have a background with other programming languages, we suggest you jump directly into our javascript guide. how to trigger javascript from html within a browser, javascript doesn't do anything by itself. you run javascript from inside your html webpages. to call javascript code from within html, you need the <script> element. there are two ways to use script, depending on whether you're linking to an external script or embedding a script right in your webpage. linking an external script usually, you'll be writing scripts in their own .js files. if you want to execute a .js script from your webpage, just use <script> with an src attribute pointing to the script file, u...
...o an external script or embedding a script right in your webpage. linking an external script usually, you'll be writing scripts in their own .js files. if you want to execute a .js script from your webpage, just use <script> with an src attribute pointing to the script file, using its url: <script src="path/to/my/script.js"></script> writing javascript within html you may also add javascript code between <script> tags rather than providing an src attribute. <script> window.addeventlistener('load', function () { console.log('this function is executed once the page is fully loaded'); }); </script> that's convenient when you just need a small bit of javascript, but if you keep javascript in separate files you'll find it easier to focus on your work write self-sufficient html write s...
Creating hyperlinks - Learn web development
ying on keyboard controls or touchscreens to navigate web pages will have difficulty accessing title information. if a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text. active learning: creating your own example link create an html document using your local code editor and our getting started template. inside the html body, add one or more paragraphs or other types of content you already know about. change some of the content into links. include title attributes. block level links as mentioned before, almost any content can be made into a link, even block-level elements. if you have an image you want to make into a link, use the <a> element and r...
... from the description above, you might think that it's a good idea to just use absolute links all the time because they don't break when a page is moved like relative links. however, you should use relative links wherever possible when linking to other locations within the same website. when you link to another website, you'll need to use an absolute link. for a start, it's easier to scan your code — relative urls are generally shorter than absolute urls, which makes reading code much easier. second, it's more efficient to use relative urls wherever possible. when you use an absolute url, the browser starts by looking up the real location of the server on the domain name system (dns), see how the web works for more information). then it goes to that server and finds the file that's being...
...e for the new email). each field and its value is specified as a query term. here's an example that includes a cc, bcc, subject and body: <a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=the%20subject%20of%20the%20email&body=the%20body%20of%20the%20email"> send mail with cc, bcc, subject and body </a> note: the values of each field must be url-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. also note the use of the question mark (?) to separate the main url from the field values, and ampersands (&) to separate each field in the mailto: url. this is standard url query notation. read the get method to understand what url query notation is more commonly...
Marking up a letter - Learn web development
the head? metadata in html, html text fundamentals, creating hyperlinks, and advanced text formatting. objective: test basic and advanced html text formatting, use of hyperlinks, and use of html <head>. starting point to begin, get the raw text you need to mark up, and the the css to style the html. create a new .html file using your text editor or use an online tool such as codepen, jsfiddle, or glitch to complete the tasks. note: if you get stuck, then ask us for help. see the assessment or further help section at the bottom of this page. project brief for this project, your task is to mark up a letter that needs to be hosted on a university intranet. the letter is a response from a research fellow to a prospective phd student concerning their application to the un...
... you don't need to know any css to do this assignment. you just need to put the provided css inside an html element. example the following screenshot shows an example of what the letter might look like after being marked up. assessment or further help if you would like your work assessed, or if you get stuck and want to ask for help: put your work in an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for marking up a letter". details of what you have already tried, and what you would like us to do (if you are stuck and need help, or if you want an assessment). a link to the example you want e...
...d for marking up a letter". details of what you have already tried, and what you would like us to do (if you are stuck and need help, or if you want an assessment). a link to the example you want evaluated or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good habit to develop. it's very hard to help someone with a coding problem without seeing their code. a link to the actual task or assessment page, so we can read the exact wording of the relevant question(s). previous overview: introduction to html next in this module getting started with html what’s in the head? metadata in html html text fundamentals creating hyperlinks advanced text formatting document and website structure debugging html marking up a letter s...
Structuring a page of content - Learn web development
resent a prospective layout design in markup. starting point to get this assessment started, you should go and grab the zip file containing all the starting assets. the zip file contains: the html you need to add structural markup to. css to style your markup. images that are used on the page. create the example on your local computer, or alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief for this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. it needs to have: a header spanning th...
... block diagram of the page layout, and write on the elements you think should wrap each block. this is extremely helpful. example the following screenshot shows an example of what the homepage might look like after being marked up. assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for structuring a page of content". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you...
...ng a page of content". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. previous overview: introduction to html in this module getting started with html what’s in the head? metadata in html html text fundamentals creating hyperlinks advanced text formatting document and website structure debugging html marking up a letter structuring a page of ...
Introduction to HTML - Learn web development
content). you should have a basic work environment set up (as detailed in installing basic software), and understand how to create and manage files (as detailed in dealing with files). both are parts of our getting started with the web complete beginner's module. note: if you are working on a computer/tablet/other devices that doesn't let you create your own files, you can try out (most of) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles, which will take you through all the basic theory of html and provide ample opportunity for you to test out some skills. getting started with html covers the absolute basics of html, to get you started — we define elements, attributes, and other important terms, and show where...
.... this article shows the syntax required to make a link and discusses best practices for links. advanced text formatting there are many other elements in html for formatting text that we didn't get to in the html text fundamentals article. the elements here are less well-known, but still useful to know about. in this article, you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more. document and website structure as well as defining individual parts of your page (such as "a paragraph" or "an image"), html is also used to define areas of your website (such as "the header," "the navigation menu," or "the main content column.") this article looks into how to plan a basic website structure and ho...
...uch as "a paragraph" or "an image"), html is also used to define areas of your website (such as "the header," "the navigation menu," or "the main content column.") this article looks into how to plan a basic website structure and how to write the html to represent this structure. debugging html writing html is fine, but what if something goes wrong, and you can't work out where the error in the code is? this article will introduce you to some tools that can help. assessments the following assessments will test your understanding of the html basics covered in the guides above. marking up a letter we all learn to write a letter sooner or later; it is also a useful example to test out text formatting skills. in this assessment, you'll be given a letter to mark up. structuring a page of ...
Mozilla splash page - Learn web development
s easily. adding a logo to the header inside the <header> element, add an <img> element that will embed the small version of the firefox logo in the header. adding a video to the main article content just inside the <article> element (right below the opening tag), embed the youtube video found at https://www.youtube.com/watch?v=ojcncvb1olg, using the appropriate youtube tools to generate the code. the video should be 400px wide. adding responsive images to the further info links inside the <div> with the class of further-info you will find four <a> elements — each one linking to an interesting mozilla-related page. to complete this section you'll need to insert an <img> element inside each one containing appropriate src, alt, srcset and sizes attributes. in each case (except one — ...
...age if the viewport is 600px wide or less, and the large landscape image otherwise. example the following screenshots show what the splash page should look like after being correctly marked up, on a wide and narrow screen display. 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. glitch is probably better for this example, as it allows you upload assets like images, whereas some of the other tools don't. write a post asking for assessment and/or help at the mdn discourse forum. add the "learning" tag to your post so we are able to more easily find it. your post should include: a descriptive title such as "assessment wanted for mozilla splas...
... a descriptive title such as "assessment wanted for mozilla splash page". details of what you would like us to do — for example what you have already tried, if you are stuck and need help,. a link to the example you want assessed or need help with, in an online editor. this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. previous overview: multimedia and embedding in this module images in html video and audio content from <object> to <iframe> — other embedding technologies adding vector graphics to the web responsive images mozilla splash page ...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
t exist in an html page and read out the contents to the user. because tables are not the right tool for layout, and the markup is more complex than with css layout techniques, the screenreaders' output will be confusing to their users. tables produce tag soup: as mentioned above, table layouts generally involve more complex markup structures than proper layout techniques. this can result in the code being harder to write, maintain, and debug. tables are not automatically responsive: when you use proper layout containers (such as <header>, <section>, <article>, or <div>), their width defaults to 100% of their parent element. tables on the other hand are sized according to their content by default, so extra measures are needed to get table layout styling to effectively work across a variety o...
... live also). adding headers with <th> elements now let's turn our attention to table headers — special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "person" and "age" cells in the first example shown in this article). to illustrate why they are useful, have a look at the following table example. ...
...an to improve this table. first, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. the html contains the same animals example as you saw above. next, use colspan to make "animals", "hippopotamus", and "crocodile" span across two columns. finally, use rowspan to make "horse" and "chicken" span across two rows. save and open your code in a browser to see the improvement. note: you can find our finished example at animals-table-fixed.html on github (see it live also). providing common styling to columns there is one last feature we'll tell you about in this article before we move on. html has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. th...
Assessment: Structuring planet data - Learn web development
ing the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. an html data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below. the finished table should look like this: you can also see the example live here (no looking at the source code — don't cheat!) steps to complete the following steps describe what you need to do to complete the table example. all the data you'll need is contained in the planets-data.txt file. if you have trouble visualising the data, look at the live example above, or try drawing a diagram. open your copy of blank-template.html, and start the table off by giving it an outer container, a table hea...
...ame row headings (e.g. saturn) are a little tricky to sort out — you need to make sure each one spans the correct number of rows and columns. one way of associating headers with their rows/columns is a lot easier than the other way. assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for structuring planet data". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want ...
...ucturing planet data". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. previous overview: tables in this module html table basics html table advanced features and accessibility structuring planet data ...
Test your skills: Loops - Learn web development
this aim of this skill test is to assess whether you've understood our looping code article. note: you can try out solutions for the tasks below by downloading the code, putting it in an online tool such as codepen, jsfiddle, or glitch, then working on the tasks. we didn't provide live editable versions of these tasks because of the risk of creating infinite loops and crashing the assessment page! if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the p...
...should use a type of loop that you've not used in the previous two tasks. download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yourself, or use the starting point files linked to in the above sections. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for loops 1 skill test". details of what you have already tried, and what you would like us to do, e...
...r loops 1 skill test". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
React interactivity: Editing, filtering, conditional rendering - Learn web development
lse); next, we're going to rethink the <todo /> component — from now on, we want it to display one of two possible “templates", rather than the single template it's used so far: the "view" template, when we are just viewing a todo; this is what we’ve used in rest of the tutorial so far. the "editing" template, when we are editing a todo. we're about to create this. ...
... the case of our <todo /> component, our condition is "is this task being edited?" change the return statement inside todo() so that it reads like so: return <li classname="todo">{isediting ? editingtemplate : viewtemplate}</li>; your browser should render all your tasks just like before. to see the editing template, you will have to change the default isediting state from false to true in your code for now; we will look at making the edit button toggle this in the next section! toggling the <todo /> templates at long last, we are ready to make our final core feature interactive. to start with, we want to call setediting() with a value of true when a user presses the "edit" button in our viewtemplate, so that we can switch templates. update the "edit" button in the viewtemplate like so: ...
...nclick handler to the "cancel" button in the editingtemplate, but this time we'll set isediting to false so that it switches us back to the view template. update the "cancel" button in the edittemplate like so: <button type="button" classname="btn todo-cancel" onclick={() => setediting(false)} > cancel <span classname="visually-hidden">renaming {props.name}</span> </button> with this code in place, you should be able to press the "edit" and "cancel" buttons in your todo items to toggle between templates. the next step is to actually make the editing functionality work. editing from the ui much of what we're about to do will mirror the work we did in form.js: as the user types in our new input field, we need to track the text they enter; once they submit the form, we need to...
Creating our first Vue component - Learn web development
: client-side javascript frameworks next now it's time to dive deeper into vue, and create our own custom component — we'll start by creating a component to represent each item in the todo list. along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props, and saving data state. note: if you need to check your code against our version, you can find a finished version of the sample vue app code in our todo-vue repository. for a running live version, see https://mdn.github.io/todo-vue/dist/. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage t...
...tive: to learn how to create a vue component, render it inside another component, pass data into it using props, and save its state. creating a todoitem component let's create our first component, which will display a single todo item. we'll use this to build our list of todos. in your moz-todo-vue/src/components directory, create a new file named todoitem.vue. open the file in your code editor. create the component's template section by adding <template></template> to the top of the file. create a <script></script> section below your template section. inside the <script> tags, add a default exported object export default {}, which is your component object. your file should now look like this: <template> </template> <script> export default {}; </script> we can now begin t...
...m label="my todo item" :done="true"></to-do-item> </li> </ul> </div> </template> try changing true to false and back again, reloading your app in between to see how the state changes. giving todos a unique id great! we now have a working checkbox where we can set the state programmatically. however, we can currently only add one todolist component to the page because the id is hardcoded. this would result in errors with assistive technology since the id is needed to correctly map labels to their checkboxes. to fix this, we can programmatically set the id in the component data. we can use the lodash package's uniqueid() method to help keep the index unique. this package exports a function that takes in a string and appends a unique integer to the end of the prefix. this will be...
Focus management with Vue refs - Learn web development
tton by pressing enter. the checkbox will be replaced with our edit component, but the focus outline will be gone. this behavior can be jarring. in addition, what happens when you press tab again varies depending on the browser you're using. similarly, if you save or cancel your edit, focus will disappear again as you move back to the non-edit view. to give users a better experience, we'll add code to control the focus so that it gets set to the edit field when the edit form is shown. we'll also want to put focus back on the "edit" button when a user cancels or saves their edit. in order to set focus, we need to understand a little bit more about how vue works internally. virtual dom and refs vue, like some other frameworks, uses a virtual dom (vdom) to manage elements. this means that vu...
...er apis (like document.getelementbyid) when using frameworks, because it results in the vdom and real dom going out of sync. instead, if you need to access the underlying dom nodes (like when setting focus), you can use vue refs. for custom vue components, you can also use refs to directly access the internal structure of a child component, however this should be done with caution as it can make code harder to reason about and understand. to use a ref in a component, you add a ref attribute to the element that you want to access, with a string identifier for the value of the attribute. it's important to note that a ref needs to be unique within a component. no two elements rendered at the same time should have the same ref. adding a ref to our app so, let's attach a ref to our "edit" butto...
... your list, focus should be moved up to the list heading. this should provide a reasonable focus experience for all of our users. summary so that's it for focus management, and for our app! congratulations for working your way through all our vue tutorials. in the next article we'll round things off with some further resources to take your vue learning further. note: if you need to check your code against our version, you can find a finished version of the sample vue app code in our todo-vue repository. for a running live version, see https://mdn.github.io/todo-vue/dist/. 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 li...
Cross browser testing - Learn web development
this module focuses on testing web projects across different browsers. we look at identifying your target audience (e.g. what users, browsers, and devices do you most need to worry about?), how to go about doing testing, the main issues that you'll face with different types of code and how to mitigate them, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use the tools detailed here. guides introduction to cross browser testing this ...
...make sure are tested), lo-fi testing strategies (get yourself a range of devices and some virtual machines and do ad-hoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups. handling common html and css problems with the scene set, we'll now look specifically at the common cross-browser problems you will come across in html and css code, and what tools can be used to prevent problems from happening, or fix problems that occur. this includes linting code, handing css prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more. handling common javascript problems now we'll look at common cross-browser javascript problems and how to fix them...
...eatures working in older browsers, and more. handling common accessibility problems next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues. implementing feature detection feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers. this article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports. introduction to automated testing manua...
Learn web development
ools, and then consider digging into client-side javascript frameworks, and server-side website programming. note: our glossary provides terminology definitions. besides, if you have a specific question about web development, our common questions section may have something to help you. random glossary entry semantics in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) topics covered the following is a list of all the topics we cover in the mdn learning area. getting started with the web provides a practical introduction to web development for complete beginners. html — structuring ...
...ools and testing this topic covers the tools developers use to facilitate their work, such as cross-browser testing tools, linters, formatters, transformation tools, version control systems, deployment tools, and client-side javascript frameworks. server-side website programming even if you are concentrating on client-side web development, it is still useful to know how servers and server-side code features work. this topic provides a general introduction to how the server-side works and detailed tutorials showing how to build up a server-side app using two popular frameworks: django (python) and express (node.js). getting our code examples the code examples you'll encounter in the learning area are all available on github. if you want to copy them all to your computer, the easiest way i...
... if you prefer to copy the repo in a more flexible way that allows for automatic updates, you can follow the more complex instructions: install git on your machine. ...
Browser chrome tests
as all tests, they won't work in a build with tests disabled (--disable-tests). ...
.../mach mochitest -f browser browser/base/content/test/ or without mach test_path=<path_to_the_tests> make -c <objdir> mochitest-browser-chrome to run tests in debugger the following should work ./mach mochitest -f browser --debugger gdb browser/base/content/test/ run ./mach help mochitest-browser for more options. writing browser chrome tests browser chrome tests are snippets of javascript code that run in the browser window's global scope. a simple test would look like this: function test() { ok(gbrowser, "gbrowser exists"); is(gbrowser.tabs.length, 1, "browser has 1 tab"); } the test() function is invoked by the test harness when the test is run. the test file can contain other functions, they will be ignored unless invoked by test(). gbrowser is set in browser.js and is a...
...ss invoked by test(). gbrowser is set in browser.js and is a tabbrowser element (the tabbrowser with id="content" in browser.xul). note: be careful when naming your functions and variables. since the test files are executed in the same scope as the browser window, conflicting variable names could cause trouble while running the tests. you should attempt to reduce the side effects of the testing code and "clean up" after yourself, to avoid influencing other tests. the comparison functions are identical to those supported by mochitests, see how the comparison functions work in the mochitest documentation for more details. the eventutils helper functions are available on the eventutils object defined in the global scope. the test file name must be prefixed with "browser_", and must have a fil...
What to do and what not to do in Bugzilla
ic websites that result from bad coding practices already determined to be “tech evangelism” cases by the module owner or peer, or problems that result from the use of proprietary technology, should be be moved to the tech evangelism product rather than being resolved as invalid. resolving bugs as fixed resolve a bug as fixed if the bug has been fixed by a checkin into the mozilla mercurial code repository. bugs which can no longer be reproduced should be marked worksforme instead of fixed if they can't be linked to a single checkin. resolving bugs as wontfix bugs should not be marked wontfix by the normal bug triager. the decision to mark a bug wontfix is reserved for module owners or module peers. verifying bugs only resolved bugs can be verified. to verify a bug, you will need to ...
... more than a few days do not qualify for the blocker severity. the exceptions to this rule are platform-specific or compiler-specific bugs. basically, anything that prevents builds from building, running, or being used for dogfood (able to use bugzilla, tinderbox, lxr, etc.) is a blocker. bug reports about crashes, hangs, data-loss, or severe security exploits (e.g. remote execution of arbitrary code) get the critical severity. priority/target milestone as stated in the bugzilla etiquette, you must not change the target milestone and priority fields. these fields are reserved for the developers. this also applies to bugs with target milestones in the past. reassigning bugs if a bug belongs to a different product or component it should be reassigned. when performing bug reassignments, keep...
...ones in the past. reassigning bugs if a bug belongs to a different product or component it should be reassigned. when performing bug reassignments, keep the following things in mind: always remember to check the reassign to default owner and qa contact radio button under the comment textbox. mozilla applications like the application suite, thunderbird, or firefox share most of their program code and all of the backend code including things like network connectivity (ftp, http, imap) and html rendering. make sure that you also test thunderbird or firefox bugs with the application suite and move the bug to one of the core products, if the bug also exists in the application suite. if you don't know where a bug belongs, don't touch it! for example, don't move bugs into the js engine compone...
Creating a Language Pack
you still need to specify which application you're localizing (e.g., for firefox, that's browser, thunderbird would be mail). configure step you need to prepare the build directory, which is done with ./mach configure you only need to run this if the version number of firefox changes. windows: replace make with mozmake in the commands below! creating a langpack we will now merge the ...
...dist the xpi file can be found in the directory win32/xpi on windows, linux-i686/xpi or linux-x86_64 on linux or mac/xpi on mac. open the xpi file contained in this directory with firefox to see your work. you have to set your selected language still. you can either use the locale switcher extension, or set it in about:config. add the preference intl.locale.requested and set it to your language code, in this case, x-testing, or add it in front of the current setting, seperated with a comma. before gecko 59 you had to set the preference general.useragent.locale to your language code. l10n binary repack for apps currently in development, you need to get the right strings for the build you use. best is to create an installer there. first, we get the en-us builds. there is a target to get thos...
...t $ make unpack again, for 64-bit mac, append moz_pkg_platform=mac to this command. at the end of the process, you should see the following success message. ... done unpacking let's check which revision the binary was built from. $ make ident fx_revision 237dccbcb967 buildid 20091126033851 you can now go back to your source hg clone. $ cd ../../../mozilla-aurora and update the source code to this revision. $ hg update -r 237dccbcb967 3 files updated, 0 files merged, 0 files removed, 0 files unresolved the source code has been updated to the revision the binary was built from. let's go to the build directory again and continue the repacking. $ cd ../obj-firefox-build/browser/locales we will now merge the localized files from x-testing locale with the en-us files from the orig...
Creating reftest-based unit tests
he "<blockquote>" element did not cause any indentation at all. if a regression test harness has false failures, it makes the harness not trustworthy and the harness will not be used. running reftest-based unit tests note: mach is a python2 script. if your use python3 as default you must edit the first line of mach. ...
...reating your first reftest. step 1 for now you must check out and build the browser in order to run the tests. see the build documentation for details on doing that. sorry about this, but the released builds and the nightly builds are built with the "--disable-tests" option and reftest will not work - see bug 369809. step 2 open a terminal window. create a directory (inside firefox's source code tree) and make that your current directory (i.e. move to that directory). step 3 create a file named foo.html with the following: <html><head><title>reftest0001</title> <body><strong>hello!</strong></body> </html> step 4 create a file named bar.html with the following: <html><head><title>reftest0001</title> <body><b>hello!</b></body> </html> step 5 create a file named reftest.list...
...if you built a debug version of the browser, there can be a lot of extra console output. the reftest.list file can be named...
Debugging Table Reflow
look there especially how the maxelementsize (mes) and desired size are propagated. block reflow another way to debug the reflow process is implemented inside nsblockframe.cpp. ...
...& astate) it first shows the block id and address and then the computed width and height from the htmlreflowstate. debug_table_strategy editor's note: the following examples are not shown correctly due to the wiki's technical constraint. ...
...aint types are known: enoconstraint = 0, epixelconstraint = 1, // pixel width epercentconstraint = 2, // percent width eproportionconstraint = 3, // 1*, 2*, etc. cols attribute assigns 1* e0proportionconstraint = 4 // 0*, means to force to min width after this follows the width information for each column: widths=-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 the table code knows ten different width's: #define num_widths 10 #define num_major_widths 3 // min, des, fix #define min_con 0 // minimum width required of the content + padding #define des_con 1 // desired width of the content + padding #define fix 2 // fixed width either from the content or cell, col, etc. + padding #define min_adj 3 // minimum width + padding d...
Debugging
debugging a project as large as mozilla can be a daunting task. fortunately, over the years, mozilla developers have come up with not just technologies and features to help you debug code, but have devised tips and techniques that can help too. also available are assorted tools that you can use when debugging. documentation topics debugging on top of the mozilla platform debugging javascript code how to debug javascript code, with a focus on debugging code in the mozilla project itself. debugging a xulrunner application tips and suggestions that will help you debug your xulrunner based application. debugging update problems learn how to debug update problems in mozilla-based applications. debugging the mozilla platform ...
...firefox with vmware workstation how to setup record and replay debugging on firefox, to help debug intermittent mochitest failures. detecting defects in firefox with coverity coverity is a static analysis system that can detect defects in firefox. gecko logging using old-school logging to try to track down what's going on. debugging specific parts of the mozilla codebase debugging opengl if you're working on code that involves opengl calls, and need to debug it, you can turn on a special opengl debugging mode. debugging frame reflow and debugging table reflow notes on debugging issues in gecko's layout engine. miscellaneous debugging safari some tips for debugging safari debugging chrome some tips...
...the gecko profiler extension. debugging a hang on os x collecting "samples" to attach to a bug. remote debugging core dumps and examples of remote debugging. useful if a developer can't reproduce your crash. http logging how to log http network traffic for debugging purposes. debugging tools tools assorted tools that will help you debug your code or web site. nserror lookup useful for when your code gets a complicated numeric error code and you can't figure out what it means. download a debug build recent automatically compiled debug builds are available. note that these are replaced frequently by our tinderboxes. the debug builds have "-debug" at the end of their file names. related topics perform...
Experimental features in Firefox
s on the status of this feature, see bug 1639607. release channel version added enabled by default? nightly 78 yes developer edition 78 yes beta 78 yes release 78 no preference name network.preload css display stray control characters in css as hex boxes this feature renders control characters (unicode category cc) other than tab (u+0009), line feed (u+000a), form feed (u+000c), and carriage return (u+000d) as a hexbox when they are not expected. see bug 1099557 for more details. release channel version added enabled by default? nightly 43 yes developer edition 43 no beta 43 no release 43 no preference n...
...ion 33 no beta 33 no release 33 no preference name media.track.enabled dom document property: autoplaypolicy the document property autoplaypolicy returns a string indicating how the browser handles requests to automatically play media (either using the autoplay property on a media element or by attempting to trigger playback from javascript code. the spec for this api is still being written. the value changes over time depending on what the user is doing, their preferences, and the state of the browser in general. potential values include allowed (autoplay is currently permitted), allowed-muted (autoplay is allowed but only with no—or muted—audio), and disallowed (autoplay is not allowed at this time). see bug 1506289 for more detail...
...before letting them go through to beta and release. the features below are the current crop of experimental developer tool features. color scheme simulation adds an option to simulate different color schemes allowing to test @prefers-color-scheme media queries. using this media query lets your style sheet specify whether it prefers a light or dark user interface. this feature lets you test your code without having to change settings in your browser (or operating system, if the browser follows a system-wide color scheme setting). see bug 1550804 and bug 1137699 for more details. release channel version added enabled by default? nightly 72 no developer edition 72 no beta 72 no release 72 no preference nam...
Index
found 172 pages: # page tags and summary 1 firefox firefox, landing, mozilla here you can learn about how to contribute to the firefox project and you will also find links to information about the construction of firefox add-ons, using the developer tools in firefox, and other topics. 3 building firefox with rust code build documentation, gecko, build, rust in may 2015 the rust programming language reached its 1.0 stability milestone, and various experiments with writing parts of gecko in rust began. rust code first shipped in august 2016 with the release of firefox 48. it became a requirement for building gecko in february 2017 with firefox 54. 8 experimental features in firefox experimental, firefox, preferences, featu...
... other personalizations that a user has made or installed into their copy of firefox. you can find details about profiles on mozilla's end-user support site. 168 performance best practices for firefox front-end engineers best practices, developing firefox, developing mozilla, firefox, front-end, mozilla, performance this guide will help firefox developers working on front-end code produce code which is as performant as possible—not just on its own, but in terms of its impact on other parts of firefox. always keep in mind the side effects your changes may have, from blocking other tasks to interfering with other user interface elements. 169 privacy privacy, security this document lists privacy-related documentation. 170 storage access polic...
... ...
Overview of Mozilla embedding APIs
classes are available from the xpcom dll. they provide some basic functionality which should be leveraged when building new xpcom components. nscomptr<interface-type> these are templatized smart pointers which transparently deal with xpcom reference counting issues. see the nscomptr user's manual for more information. ...
... ns_initembedding this function initializes the gecko embedding support. this must be the first function call made into gecko. ...
...verview: most of gecko's functionality is exposed through the nswebbrowser component. the webbrowser provides a simple mechanism for other applications to leverage gecko functionality. each instance of a webbrowser encapsulates a full featured html content area. the embedding application receives notifications from gecko through a set of callback interfaces it may choose to implement. below is a code snippet which an embedding application can use to create and initialize a webbrowser: nsresult rv; nscomptr<nsibasewindow> basewindow; nscomptr<nsiwebbrowser> webbrowser; // create a nswebbrowser instance... webbrowser = do_createinstance(ns_webbrowser_contractid, &rv); if (ns_failed(rv)) return rv; // give the webbrowser a pointer to the embedding comp...
HTML parser threading
html parser threading the html parser parses data received from the network off the main thread. (there's currently one parser thread serving all parser instances.) data received from document.write() is parsed on the main thread. main objects nshtml5parser contains the code for dealing with data from document.write(). (for historical reasons, it also contains unrelated fragment parsing code that should be refactored into a separate class in due course.) nshtml5streamparser contains the code for dealing with data from the network. nshtml5parser owns nshtml5streamparser. script-created parsers (i.e. parsers created using document.open()) don't have an nshtml5streamparser instance. nshtml5parser has one tokenizer/tree builder pair for parsing data from document.write(). it also has anoth...
...ta to completion. nshtml5streamparser has one tokenizer/tree builder pair for parsing data from the network. additionally, each nshtml5parser has an associated nshtml5treeopexecutor that turns the output (tree operations; discussed later) of the portable parser core into actions performed on the gecko dom. initialization an nshtml5parser is constructed without an nshtml5streamparser due to legacy code structure around parser creation. if the parser is not script-created, nshtml5parser::markasnotscriptcreated() is called to create an nshtml5streamparser for the nshtml5parser. due to legacy interface design oddities, an nshtml5parser is initialized by calling nshtml5parser::parse(nsiuri*, nsirequestobserver*, void*, nsdtdmode). that method call doesn't yet cause anything to be parsed, though. ac...
...fe to release except from the main thread. the runnables use nshtml5refptr<nshtml5streamparser>. nshtml5refptr sends runnables back to the main thread to call release on nshtml5streamparser on the main thread. normal (non-speculative) parsing initially, dodataavailable performs character encoding sniffing on the data if an encoding wasn't declared on the enclosing protocol (http) level. once a unicode decoder has been set up, dodataavailable passes the byte data to the decoder whose output is accumulated into a linked list of nshtml5owningutf16buffer objects. nshtml5owningutf16buffer objects are then passed to the tokenizer in sequence by the parseavailabledata() method. the tokenizer calls into the tree builder which outputs nshtml5treeoperation objects (tree ops) into a queue. each tree op r...
Implementing QueryInterface
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 can write this function for you (though it pains me to recommend macros), e.g.
...he corresponding queryinterface implementation, plus an addref and a release. calling an inherited queryinterface sometimes you are just adding one or two new interfaces to an implementation that already supports many other interfaces. in such cases, you'll probably want to call through to the underlying implementation, after you've tested for the particular iids that you care about. this saves code-space and reduces complexity. the differences are highlighted in the following code. class nsmyimplmentation : public nsbaseimplementation, public nsix, public nsiy { ... }; ns_imethodimp nsmyimplementation::queryinterface( refnsiid aiid, void** ainstanceptr ) /* i just add the interfaces |nsix| and |nsiy|. my base class |nsbaseimplementation| provides all the rest. */ {...
... maybe my base class can. status = nsbaseimplementation::queryinterface(aiid, &foundinterface); else { ns_addref(foundinterface); status = ns_ok; } *ainstanceptr = foundinterface; return status; } note that if the base implementation's queryinterface finds an appropriate interface, your queryinterface must not addref it. this is reflected in the code above. this technique works because nsbaseimplementation is already a complete class that could have been used on its own. this technique is less appropriate when you derive from several complete classes; but it can still be used if you are sensitive to the order, e.g., // ... nsresult status; if ( !foundinterface ) { // ok, ask |nsbase1imp| first, because i want _it...
Infallible memory allocation
there's ongoing work to implement infallible memory allocators. these are memory allocation routines that never return null; that is, they always successfully return the requested block of memory. this is in contrast to a traditional, fallible memory allocator that can return null indicating that the request failed. currently, while code is transitioned to be compatible with infallible memory allocators, you have to explicitly decide whether to use infallible allocation or not. eventually, however, the generic memory allocators (malloc() and realloc()) will become infallible. how can memory allocation be infallible? the term "infallible" means that your memory allocation request is guaranteed to succeed: your code can never see a failed request, and so doesn't need to check for failure. i...
...infallible? ...
...ne, the situation is different. under extreme memory conditions, it's possible that the allocation will fail; however, the allocation routine will not, in this scenario, return to your code. instead, the application will terminate. this should be rare, because the memory management system will do everything it can to find the memory you've asked for. choosing a memory allocator as you write new code that needs to allocate memory, there are some simple rules to follow to help you decide whether to use a fallible or an infallible memory allocator: if you're allocating what may be a large chunk of memory, you should allocate the memory fallibly (using malloc() for example), and check the result to be sure it's not null. you should do this for large memory allocations because in extremely low...
FileUtils.jsm
the fileutils.jsm javascript code module offers utility routines dealing with files. ...
... the fileutils.jsm javascript code module offers utility routines dealing with files. ...
...note: starting in gecko 6 the stream is opened with the defer_open nsifileoutputstream behavior flag constant; this means the file is not actually opened until the first time it's accessed. closesafefileoutputstream() closes a safe file output stream. void closesafefileoutputstream( nsifileoutputstream stream ); parameters stream the stream to close. see also nsifileoutputstream code snippets and examples ...
FxAccountsOAuthClient.jsm
fxaccountsoauthclient(object options); method overview launchwebflow(); teardown(); attributes parameters object returns the set of parameters that initialized the firefox accounts oauth flow. oncomplete function gets called when the firefox accounts oauth flow successfully completes. first and only argument is an object that has "state" and "code" properties. constructor fxaccountsoauthclient() creates and returns a new fxaccountsoauthclient object. fxaccountsoauthclient fxaccountsoauthclient( object options object parameters string client_id string state string oauth_uri string content_uri [optional] string scope [optional] string action [optional] string authorizationendpoint ); par...
... the methods described in this article. methods launchwebflow() opens a new tab at the firefox accounts oauth authorization url. registers a webchannel listener and sets up a callback if needed. parameters none teardown() call this function to manually release all channels and callbacks that are in use by this client. ...
... none examples using the fxaccountsoauthclient chrome code let parameters = { oauth_uri: oauth_server_endpoint, client_id: oauth_client_id, content_uri: content_server_url, state: oauth_state } let client = new fxaccountsoauthclient({ parameters: parameters }); client.oncomplete = function (tokendata) { // tokendata consists of two properties: "tokendata.state" and "tokendata.code" }; client.launchwebflow(); ...
JNI.jsm
the most common use for this module is in add-ons and other works on firefox for android (fennec). with this module, all of the android sdk functions that firefox has permissions for are at your fingertips. ...
...the most common use for this module is in add-ons and other works on firefox for android (fennec). with this module, all of the android sdk functions that firefox has permissions for are at your fingertips. ...
...sstr_dirextstorepath = jni.readstring(my_jenv, javastr_dirextstorepath); // "/mnt/sdcard" var jsstr_dirpicsname = jni.readstring(my_jenv, environment.directory_pictures); // "pictures" var jsstr_dirpics = os.path.join(jsstr_dirextstorepath, jsstr_dirpicsname); // "/mnt/sdcard/pictures" } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } example 2 blah blah blah code here ...
OSFile.jsm
what are the relationships with the html5 file api? none, really. the file api is designed for high-level, highly-restricted manipulation of files by web applications. ...
... what are the relationships with the html5 file api? none, really. the file api is designed for high-level, highly-restricted manipulation of files by web applications. ...
...in thread file i/o. calling os.file from the main thread asynchronous, off-main thread file i/o, main thread api. calling os.file.directoryiterator from the main thread asynchronous, off-main thread file directory access, main thread api. ... from a worker thread in some cases, the main thread api for os.file is not appropriate as it would require too much message passing, or because the code that requires file i/o is already executed on a worker thread. for this reason, api clients can also spawn their own worker threads and make use of os.file directly from these threads. os.file for workers synchronous file i/o for worker threads os.file.directoryiterator for workers visiting directories synchronously from a worker thread ... shared components os.path and os.constants.pa...
PopupNotifications.jsm
the popupnotifications.jsm javascript code module provides a popup notification box service. this service is used, for example, to display geolocation related notifications. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/popupnotifications.jsm"); once you've imported the module, you can then use the popupnotifications object it exports; this object provides methods for creating and displaying popup notification panels. note: this code module is imported by firefox chrome windows, so you don't have to do it yourself in most extensions. method overview void locationchange(); notification getnotification(id, browser); void remove(notification); notification show(browser...
...n panel is currently visible, false if it is not. methods locationchange() the consumer can call this method to let the popup notification module know that the current browser's location has changed. this lets the notification service update the active notifications as appropriate. note: you shouldn't need to call this when using the popupnotifications object in firefox windows; firefox code takes care of this automatically. void locationchange(); parameters none. getnotification() retrieve a notification object associated with the browser/id pair. notification getnotification( string id xulelement browser ); parameters id the notification id to search for. browser the xul <xul:browser> element whose notifications should be searched. if null, the currently selected <...
... the notification has been dismissed by the user (for example, by clicking away or by switching tabs). this is different from "removed", in that the notification can be redisplayed. "removed" the notification has been removed, either by the user taking action on the notification or by the browser being navigated to a new location. "showing" the notification is about to be shown. the callback code can modify the notification message/actions if necessary during this notification. "shown" the notification has become visible. this can be fired multiple times as notifications are dismissed and redisplayed. the notification object each notification is represented by a notification object. this object contains all the data necessary to present and manage the notification, and has one method...
Localizing with Koala
in a real-life situation, that would become for example "de" (for german) or "es-es" (for spanish in spain). translating to x-testing will basically consist of converting any strings to uppercase, for example "file" in original version (en-us) will become "file" in x-testing. ...
...la\l10n\application\firefox> hg clone http://hg.mozilla.org/releases/mozilla-1.9.2 3.6 requesting all changes adding changesets adding manifests adding file changes added 33099 changesets with 158636 changes to 50664 files (+9 heads) updating working directory 40357 files updated, 0 files merged, 0 files removed, 0 files unresolved configure the locale locale id: x-testing (put your locale's code) version: 3.6 location: choose the folder where you want to keep the localized files or leave empty for now check "mercurial" if you wish to use mercurial to keep the revision history of your files (very recommended) existing localizations: url: if you're editing an existing localization or you already have a repository set up (either on hg.mozilla.org or bitbucket), type the url of the remote r...
...ent. they can be found in two files, inside the browser/chrome/browser directory: searchbar.dtd, search.properties. the difference between dtd and .properties files in the moment when they are used by the application. dtd's files are read by the xml parser, which goes through the xul files used in mozilla to create the interface when it launches. the .properties files are used in the javascript code while the application is already running. that's why the string "add %s..." (where %s is replaced by the search engine's name, like 'mdc search') is found in search.properties file. it has to be generated every time the user switches between pages. on the other hand, "manage search engines..." is generated only once, on start-up, and doesn't need to change. therefore, it is located in searchbar.d...
Localizing with Mercurial
mercurial allows localizers to work locally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org). localizing current versions of firefox, thunderbird and seamonkey includes working with mercurial. if the documentation is incomplete or you have questions, please drop by the #l10n or #hg channels on irc.mozilla.org. the mercurial faq are also worth a read, should you run into trouble. ...
...he second command will move you into that directory. the third command will do a clone of mozilla-central, and pull some other hg repositories. the other directories are required for seamonkey and thunderbird. cloning your localization repository for the first time is just as easy. for example, to clone your firefox nightly l10n repo, run the following command, replacing ab-cd with your locale code: hg clone https://hg.mozilla.org/l10n-central/ab-cd/ updating your local repos to update your working copy of mozilla-central, go to your local mozilla-central directory and run: hg pull -u this will both get new changesets from mozilla-central and apply those changes in your working copy. to update your working copy of comm-central, go to your comm-central directory and run: pytho...
...your changes to mozilla’s repository, but prepares them for it. the next step will send your changes to your remote repo via push. ...
Mozilla Development Tools
this page lists the various development tools that we operate and/or maintain here at mozilla.org. naturally, source code for all of these tools is also available. the tools needed to build mozilla are described on the build page for your platform. mozilla source code (mercurial and cvs) "trunk" development for gecko 1.9.1/firefox 3.5 and beyond uses the mercurial source code version control system. earlier releases and other products use the cvs version control system. if you are doing active development, checking out source code from one of these is preferable to downloading an archived snapshot, as you get up-to-the-minute changes. ...
... bonsai bonsai is tree control (get it?). ...
... bonsai bonsai is tree control (get it?). it is our home-grown web-based tool for watching the up-to-the-minute goings-on in our cvs repository (viewing checkins and log messages, reading diffs, etc.) tinderbox tinderbox is for knowing when the tree is in flames. ...
Leak-hunting strategies and tips
at owns references to reference counted objects). see bug 109671 for an example. destructors that should have been virtual: if you expect to override an object's destructor (which includes giving a derived class of it an nscomptr member variable) and delete that object through a pointer to the base class using delete, its destructor better be virtual. (but we have many virtual destructors in the codebase that don't need to be -- don't do that.) debugging leaks that go through xpconnect many large object graphs that leak go through xpconnect. this can mean there will be xpconnect wrapper objects showing up as owning the leaked objects, but it doesn't mean it's xpconnect's fault (although that has been known to happen, it's rare). debugging leaks that go through xpconnect requires a basic un...
...n there will be xpconnect wrapper objects showing up as owning the leaked objects, but it doesn't mean it's xpconnect's fault (although that has been known to happen, it's rare). debugging leaks that go through xpconnect requires a basic understanding of what xpconnect does. xpconnect allows an xpcom object to be exposed to javascript, and it allows certain javascript objects to be exposed to c++ code as normal xpcom objects. when a c++ object is exposed to javascript (the more common of the two), an xpcwrappednative object is created. this wrapper owns a reference to the native object until the corresponding javascript object is garbage-collected. this means that if there are leaked gc roots from which the wrapper is reachable, the wrapper will never release its reference on the native objec...
...ebug the leaked js roots. these roots are printed on shutdown in debug builds, and the name of the root should give the type of object it is associated with. one of the most common ways one could leak a js root is by leaking an nsxpcwrappedjs object. this is the wrapper object in the reverse direction -- when a js object is used to implement an xpcom interface and be used transparently by native code. the nsxpcwrappedjs object creates a gc root that exists as long as the wrapper does. the wrapper itself is just a normal reference-counted object, so a leaked nsxpcwrappedjs can be debugged using the normal refcount-balancer tools. if you really need to debug leaks that involve js objects closely, you can get detailed printouts of the paths js uses to mark objects when it is determining the set...
TimerFirings logging
sured in milliseconds. finally there is the identifying information for the timer. function timers have an informative label. interface and observer timers only have an address, which is less useful, but they are uncommon enough that this usually doesn't matter much. the above example shows only timers from c++ within gecko. there are also timers for settimer or setinterval calls in javascript code, as the following sample shows. -991946880[7f46c365ba00]: [6775] fn timer (one_shot 0 ms): [content] chrome://browser/content/tabbrowser.xml:1816:0 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://edition.cnn.com/:5:7231 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://a.visualrevenue.com/vrs.js:6:9423 these js timers are...
...//browser/content/tabbrowser.xml:1816:0 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://edition.cnn.com/:5:7231 711637568[7f3219c48000]: [6835] fn timer (one_shot 100 ms): [content] http://a.visualrevenue.com/vrs.js:6:9423 these js timers are annotated with [content] and show the javascript source location where they were created. they can come from chrome code within firefox, or from web content. the informative labels are only present on function timers that have had their creation site annotated. for unannotated function timers, there are three possible behaviours. first, on mac the code uses dladdr to get the name immediately, and the output will look like the following. 2082435840[100445640]: [81190] fn timer (one_shot 8000 ms): [from dladdr] gf...
...the following two lines show the output before and after being post-processed by that script. ...
Localization Use Cases
declensions in gaia's browser app, there's an about-browser string defined as follows in apps/browser/locales/browser: about-browser=about {{browserbrandshortname}} problem definition in many inflected languages (e.g. ...
...glish string could be as simple as: <availablesize "{{ $size }} {{ $unit }} available"> on the other hand, the italian translation would make use of proper pluralization rules: <plural($n) { $n == 1 ? "one" : "other" }> <availablesize[plural($size)] { one: "{{ $size }} {{ $unit }} disponibile", other: "{{ $size }} {{ $unit }} disponibili" }> so far, so good. the javascript code hasn't changed yet, but there's another improvement that can be introduced, which is described below. asymmetry the example above could benefit from another of l20n's features: local variables. in l20n, localization files can be asymmetrical and have more entities that the source language. you'll notice that devicestoragehelper.showformatedsize passes a localized name of the unit to availables...
...= kb byteunit-mb = mb byteunit-gb = gb byteunit-tb = tb for example in french, the unit abbreviations are as follows: byteunit-b = o byteunit-kb = ko byteunit-mb = mo byteunit-gb = go byteunit-tb = to solution in l20n, the french localizer could provide the translation of unit abbreviations locally in the localization file, without impacting the english localization file. ...
L20n
introducing l20n l20n reinvents software localization. users should be able to benefit from the entire expressive power of the natural language. l20n keeps simple things simple, and at the same time makes complex things possible. through l20n, mozilla is creating a new generation of technology that places more power in localizers' hands. ...
...x", locative: "firefoxu", instrumental: "firefoxom" }> <about "o {{ brandname.locative }}"> for developers documentation for developers wanting to implement localization functionality on their web apps using l20n. internationalization for your web app first read for developers looking to use the l20n infrastructure. l20n's html bindings tutorial on implementing l20n in your html code. l20n javascript api an api for l20n.js. l20n syntax cheatsheet for developers a simple cheatsheet to help developers as they add l20n to their localization infrastructure. for localizers documentation for localizers creating localized content for a project that uses l20n. learn the l20n syntax how to naturally localize applications using l20n. complete with use cases and examples of...
...ts the translation memory exchange standard for translation memory data. l20n syntax cheatsheet for localizers a simple cheatsheet to help localizers as they localize projects with l20n. additional resources some additional resources for developers and localizers involved with l20n. l20n.org you can try l20n live in your browser on the project page. l20n tinker test out your own l20n code in l20n tinker. github where the main code for the l20n infrastructure and design spec lives. wiki page info about the project to develop l20n. ...
PR_SetError
oserr the platform-specific error. if there is no appropriate os error number, a zero may be supplied. ...
... oserr the platform-specific error. if there is no appropriate os error number, a zero may be supplied. ...
... oserr the platform-specific error. if there is no appropriate os error number, a zero may be supplied. ...
Function_Name
n does (more than just what it returns). syntax #include <headers.h> returntype function_name( paramtype paramname, paramtype paramname, ); parameters paramname sample: in pointer to a certcertdbhandle representing the certificate database to look in paramname sample: in pointer to an secitem whose type must be sidercertbuffer and whose data contains a der-encoded certificate description long description of this function, what it does, and why you would use it. describe all side-effects on "out" parameters. avoid describing the return until the next section, for example: this function looks in the nsscryptocontext and the nsstrustdomain to find the certificate that matches the der-encoded certificate. a match is found when the issuer and serial number ...
... description long description of this function, what it does, and why you would use it. describe all side-effects on "out" parameters. avoid describing the return until the next section, for example: this function looks in the nsscryptocontext and the nsstrustdomain to find the certificate that matches the der-encoded certificate. a match is found when the issuer and serial number of the der-encoded certificate are found on a certificate in the certificate database. returns full description of the return value, for example: a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found. the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. see also co...
... ...
NSS FAQ
Mozilla › Projects › NSS › FAQ
ecurity-enabled client applications. the psm binary provides a client module that performs cryptographic operations on behalf of applications. netscape personal security manager ships with netscape 6 and the gateway connected touch pad with instant aol, and is also available for use with communicator 4.7x. where can i get the source? for instructions on how to check out and build the nss source code, see build instructions for nss. how much does it cost? nss source code and binaries (when they become available) are completely free. no license fees, no royalty fees, no subscription fees. developer questions what hardware accelerators are supported? nss supports the pkcs #11 interface for hardware acceleration. since leading accelerator vendors such as chrysalis-it, ncipher, and rainbow t...
...ard application protocols (http, pop3, ftp, smtp, etc.) as well as custom application protocols using tcp/ip. how long does it take to integrate nss into my application? the integration effort depends on an number of factors, such as developer skill set, application complexity, and the level of security required for your application. nss includes detailed documentation of the ssl api and sample code that demonstrates basic ssl functionality (setting up an encrypted session, server authentication, and client authentication) to help jump start the integration process. however, there is little or no documentation currently available for the rest of the nss api. if your application requires sophisticated certificate management, smart card support, or hardware acceleration, your integration effor...
...g/nspr/releases/. how can i learn more about tls? see https://developer.mozilla.org/docs/glossary/tls. licensing questions how is nss licensed? nss is available under the mozilla public license, version 2. is nss available outside the united states? this section is out of date yes; see build instructions for nss 3.1. and ftp://ftp.mozilla.org/pub/mozilla.org/security/. however, nss source code is subject to the u.s. export administration regulations and other u.s. law, and may not be exported or re-exported to certain countries (cuba, iran, iraq, libya, north korea, serbia, sudan, syria, and taleban-controlled areas of afghanistan as of january 2000) or to persons or entities prohibited from receiving u.s. exports (including those (a) on the bureau of industry and security denied parti...
Getting Started With NSS
ovides. a high level introduction to the internals of nss. learn about getting the nss sources, building, and testing. old documentation that is on the archived mozilla.org website. (unfortunately the nss project doesn't have a technical writer at this time, so our documentation is not as organized as we would like it to be. you could contribute by organizing it in a better way.) nss sample code a good place to start learning how to write nss applications are the command line tools that are maintained by the nss developers. you can find them in subdirectory mozilla/security/nss/cmd or have a look at some basic nss sample code. a new set of samples is currently under development and review, see create new nss samples. you are welcome to download the samples via: hg clone https://hg.mo...
...tunities) start by opening a bugzilla account at bugzilla.mozilla.org if you don't have one. nss :: libraries component for issues you'd like to work on. we maintain a list of nss bugs marked with a keyword "good-first-bug" that you can view. creating your patch seee our section on nss sources, building, and testing to get started making your patch. when you're satisfied with it, you'll need code review. code review http://phabricator.services.mozilla.com/ is our code review tool, which uses your bugzilla account. use our phabricator user instructions to upload patches for review. some items that will be evaluated during code review are listed in checklist form on github. after passing review, your patch can be landed by a member of the nss team. you can find us on mozilla irc in chan...
...icator.services.mozilla.com/ is our code review tool, which uses your bugzilla account. use our phabricator user instructions to upload patches for review. some items that will be evaluated during code review are listed in checklist form on github. after passing review, your patch can be landed by a member of the nss team. you can find us on mozilla irc in channel #nss. note that we don't land code that isn't both reviewed and tested. code only works when it has tests, and tests only work when they're part of the automation. ...
NSS 3.12.6 release notes
is intended for use when ocsp responses are provided via a side-channel, i.e. tls ocsp stapling (a.k.a. the status_request extension). ...
...e_force_proxy_locking 1 means force always use proxy, 0 means never use proxy, null means use proxy for non-local files only. sslkeylogfile key log file. if set, nss logs rsa pre-master secrets to this file. this allows packet sniffers to decrypt tls connections. see documentation. note: the code must be built with trace defined to use this functionality. bugs fixed the following bugs have been fixed in nss 3.12.6. bug 275744: support for tls compression rfc 3749 bug 494603: update nss's copy of sqlite3 to 3.6.22 to get numerous bug fixes bug 496993: add accessor functio...
... bug 530907: the peerid argument to ssl_setsockpeerid should be declared const bug 531188: decompression failure with https://livechat.merlin.pl/ bug 532417: build problem with spaces in path names bug 534943: clean up the makefiles in lib/ckfw/builtins bug 534945: lib/dev does not need to include headers from lib/ckfw bug 535669: move common makefile code in if and else to the outside bug 536023: der_utctimetotime and der_generalizedtimetotime ignore all bytes after an embedded null bug 536474: add support for logging pre-master secrets bug 537356: implement new safe ssl3 & tls renegotiation bug 537795: nss_initcontext does not work with nss_registershutdown bug 537829: allow nss to build for android ...
NSS 3.12.9 release notes
illa.org/pub/mozilla.org/security/nss/releases/nss_3.12.9_rtm/src/. you also need to download the nspr 4.8.7 binary distributions to get the nspr 4.8.7 header files and shared libraries, which nss 3.12.9 requires. nspr 4.8.7 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.7/. ...
....7 header files and shared libraries, which nss 3.12.9 requires. nspr 4.8.7 binary distributions are in https://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.7/. new in nss 3.12.9 removed functions new ssl options new error codes bugs fixed the following bugs have been fixed in nss 3.12.9. ...
...uring ssl handshake in [@ intel_aes_decrypt_cbc_256] bug 444367: nss 3.12 softoken returns the certificate type of a certificate object as ckc_x_509_attr_cert. bug 620908: certutil -t -d "sql:." dumps core bug 584257: need a way to expand partial private keys. ...
NSS 3.14.1 release notes
nss 3.14.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_1_rtm/src/ new in nss 3.14.1 new functionality nss now has the ability to create signed ocsp responses. the ability to create signed ocsp responses has been added in nss 3.14.1. ...
...lity nss now has the ability to create signed ocsp responses. the ability to create signed ocsp responses has been added in nss 3.14.1. note that this code is used primarily for purposes of testing. new functions in ocspt.h cert_createocspsingleresponsegood cert_createocspsingleresponseunknown cert_createocspsingleresponserevoked cert_createencodedocspsuccessresponse cert_createencodedocsperrorresponse new types in ocspt.h ​certocspresponderidtype notable changes in nss 3.14.1 windows ce support has been removed from the code base. bug 812399 - in nss 3.14, a regression caused bug 641052 / cve-2011-3640 to be re-introduced under certain situations. this regression only affected applications that...
...lar algorithms, and which do make use of cipherorder may now find that cryptographic operations occur on a different pkcs#11 token. bug 802429 - the nss softoken is now the default token for sha-256 and sha-512. in previous versions of nss, these algorithms would be handled by the most recently added pkcs#11 token that supported them. bug 611451 - when built with the current version of apple xcode on mac os x, the nss shared libraries will now only export the public nss functions. bug 810582 - tls false start is now only used with servers that negotiate a cipher suite that supports forward secrecy. note: the criteria for false start may change again in future nss releases. bugs fixed in nss 3.14.1 the following bugzilla query returns all of the bugs fixed in nss 3.14.1: https://bugz...
NSS 3.21 release notes
ster secret for dh (and ecdh) cipher suites ckm_tls12_key_safe_derive and ckm_tls_kdf are identifiers for additional pkcs#12 mechanisms for tls 1.2 that are currently unused in nss. ...
...kcs#12 mechanisms for tls 1.2 that are currently unused in nss. ...
...coidt.h nss_use_alg_in_ssl_kx - policy flag indicating that keys are used in tls key exchange in sslerr.h ssl_error_rx_short_dtls_read - error code for failure to include a complete dtls record in a udp packet ssl_error_no_supported_signature_algorithm - error code for when no valid signature and hash algorithm is available ssl_error_unsupported_signature_algorithm - error code for when an unsupported signature and hash algorithm is configured ssl_error_missing_extended_master_secret - error code for when the extended master secret is missing after having been negotiated ssl_error_unexpected_extended_master_secret - error code for receiving an extended master secret when previously not negotiated in sslt.h ssl_enable_extended_master_secret - configurat...
NSS 3.23 release notes
.12 or newer. nss 3.23 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_23_rtm/src/ new in nss 3.23 new functionality chacha20/poly1305 cipher and tls cipher suites now supported (bug 917571, bug 1227905) experimental-only support tls 1.3 1-rtt mode (draft-11). this code is not ready for production use. new functions in ssl.h ssl_setdowngradecheckversion - set maximum version for new serverrandom anti-downgrade mechanism. clients that perform a version downgrade (which is a dangerous practice) call this with the highest version number that they possibly support. this gives them access to the version downgrade protection from tls 1.3. notab...
...the list of tls extensions sent in the tls handshake has been reordered to increase compatibility of the extended master secret with servers (bug 1243641) the build time environment variable nss_enable_zlib has been renamed to nss_ssl_enable_zlib (bug 1243872). the build time environment variable nss_disable_chachapoly was added, which can be used to prevent compilation of the chacha20/poly1305 code. the following ca certificates were removed cn = staat der nederlanden root ca sha-256 fingerprint: d4:1d:82:9e:8c:16:59:82:2a:f9:3f:ce:62:bf:fc:de:26:4f:c8:4e:8b:95:0c:5f:f2:75:d0:52:35:46:95:a3 cn = netlock minositett kozjegyzoi (class qa) tanusitvanykiado sha-256 fingerprint: e6:06:dd:ee:e2:ee:7f:5c:de:f5:d9:05:8f:f8:b7:d0:a9:f0:42:87:7f:6a:17:1e:d8:ff:69...
...ngerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66 security fixes in nss 3.23 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user. bugs fixed in nss 3.23 this bugzilla query returns all the bugs fixed in nss 3.23: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.23 acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue i...
NSS 3.44 release notes
3.44 requires nspr 4.21 or newer. nss 3.44 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_44_rtm/src/ other releases are available in nss releases. ...
... in lib/certdb/cert.h cert_getcertificateder - access the der-encoded form of a certcertificate. notable changes in nss 3.44 it is now possible to build nss as a static library (bug 1543545) initial support for building for ios. ...
...546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variables passed to nspr 1543545 - allow to build nss as a static library 1487597 - early data that arrives before the handshake completes can be read afterwards 1548398 - freebl_gtest not building on linux/mac 1548722 - fix some coverity warnings 1540652 - softoken/sdb.c: logically dead code 1549413 - android log lib is not included in build 1537927 - ipsec usage is too restrictive for existing deployments 1549608 - signature fails with dbm disabled 1549848 - allow building nss for ios using gyp 1549847 - nss's sqlite compilation warnings make the build fail on ios 1550041 - freebl not building on ios simulator 1542950 - macos cipher test timeouts this bugzilla query returns...
NSS Developer Tutorial
nss coding style formatting line length should not exceed 80 characters. indentation level is 4. tabs are used heavily in many nss source files. try to stay consistent when you modify existing code. the proper use of tabs has often been confusing for new nss developers, so in nss/lib/ssl, we're gradually removing the use of tabs. curly braces: both of the following styles are allowed: if (condition) { action1(); } else { action2(); } or: if (condition) { action1(); } else { action2(); } the former style is more common. ...
...en you modify existing code. the proper use of tabs has often been confusing for new nss developers, so in nss/lib/ssl, we're gradually removing the use of tabs. curly braces: both of the following styles are allowed: if (condition) { action1(); } else { action2(); } or: if (condition) { action1(); } else { action2(); } the former style is more common. when modifying existing code, try to stay consistent. in new code, prefer the former style, as it conserves vertical space. when a block of code consists of a single statement, nss doesn’t require curly braces, so both of these examples are fine: if (condition) { action(); } or: if (condition) action(); although the use of curly braces is more common. multiple-line comments should be formatted as fol...
...ions may depend on the buggy behavior. we would need to add a new function to provide the desired behavior. similarly, new options often need to be disabled by default. nss review/feature approval process nss doesn’t have 'super reviewers'. we wish to increase the number of nss developers, who have broad understanding of nss. one review is usually enough for the review to pass. for critical code reviews, such as a patch release of a stable branch, two reviews may be more reasonable. for new features, especially those that appear controversial, try to find a reviewer from a different company or organization than your own, to avoid any perceptions of bias. update nss in mozilla-inbound and mozilla-central the procedure is documented at https://developer.mozilla.org/docs/updating_nspr_or...
Utilities for nss samples
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...e 0: utilities. these utility functions are adapted from those found in the sectool library used by the nss security tools and other nss test applications. it shows the following: read der from a file. compile file size. get seed from a noise gile. generate random numbers. get a module password. extract the password from a text file. print data as hexadecimal. util.h /* this source code form is subject to the terms of the mozilla public * license, v. 2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. */ #ifndef _util_h #define _util_h #include <prlog.h> #include <termios.h> #include <base64.h> #include <unistd.h> #include <sys/stat.h> #include "util.h" #include <prprf.h> #include <prerror.h> #include <nss.h> #i...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. */ #include "util.h" /* * these utility functions are adapted from those found in * the sectool library used by the nss security tools and * other nss test applications. */ /* * newline */ static void newline...
Overview of NSS
s ssl module for the apache web server. server products from oracle (formerly sun java enterprise system), including oracle communications messaging server and oracle directory server enterprise edition. suse linux enterprise server supports nss and the mod_nss ssl module for the apache web server. nss includes a framework to which developers and oems can contribute patches, such as assembler code, to optimize performance on their platforms. nss 3.x has been certified on 18 platforms. for more detailed information about nss, see wiki.mozilla.org and nss faq. source code for a java interface to nss is available in the mozilla cvs tree. for details, see network security services for java. nss makes use of netscape portable runtime (nspr), a platform-neutral open-source api for system func...
... input data). complete software development kit in addition to libraries and apis, nss provides security tools required for debugging, diagnostics, certificate and key management, cryptography module management, and other development tasks. nss comes with an extensive and growing set of documentation, including introductory material, api references, man pages for command-line tools, and sample code. ...
...r command-line tools, and sample code. nss is available as source and shared (dynamic) libraries. every nss release is backward compatible with previous releases, allowing nss users to upgrade to the new nss shared libraries without recompiling or relinking their applications. open-source licensing and distribution nss is available under the mozilla public license, version 2. the latest source code is available for free worldwide from https://www.mozilla.org and its mirror sites. ...
NSPR functions
r of nspr functions are required for using the certificate verification and ssl functions in nss. these nspr functions are listed in this section. nspr initialization and shutdown nspr is automatically initialized by the first nspr function called by the application. call pr_cleanup to shut down nspr and clean up its resources. pr_cleanup error reporting nss uses nspr's thread-specific error code to report errors. call pr_geterror to get the error code of the last failed nss or nspr function. call pr_seterror to set the error code, which can be retrieved with pr_geterror later. the nss functions port_geterror and port_seterror are simply wrappers of pr_geterror and pr_seterror. pr_geterror pr_seterror calendar time nss certificate verification functions take a prtime parameter that sp...
...nds or milliseconds to printervaltime. pr_secondstointerval pr_millisecondstointerval nspr i/o layering nspr file descriptors can be layered, corresponding to the layers in the network stack. the ssl library in nss implements the ssl protocol as an nspr i/o layer, which sits on top of another nspr i/o layer that represents tcp. you can implement an nspr i/o layer that wraps your own tcp socket code. ...
... this method is convenient and works for most applications. ...
sslcrt.html
certusageverifyca certusageprotectedobjectsigner wincx the pin argument value to pass to pk11 functions. see description below for more information. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to obtain the error code. description the cert_verifycertnow function must call one or more pk11 functions to obtain the services of a pkcs #11 module. some of the pk11 functions require a pin argument (see ssl_setpkcs11pinarg for details), which must be specified in the wincx parameter. to obtain the value to pass in the wincx parameter, call ssl_revealpinarg. cert_verifycertname compares the common name speci...
...tname to be checked. returns the function returns one of these values: if the common name in the subject dn for the certificate matches the domain name passed in the hostname parameter, secsuccess. if the common name in the subject dn for the certificate is not identical to the domain name passed in the hostname parameter, secfailure. use pr_geterror to obtain the error code. description the comparison performed by cert_verifycertname is not a simple string comparison. instead, it takes account of the following rules governing the construction of common names in ssl server certificates: * matches anything ? matches one character \ escapes a special character $ matches the end of the string [abc] matches one occurrence of a, b, or c. the only ...
...is to be checked. canames a pointer to a structure that contains a list of distinguished names (dns) against which to check the dns for the signers in the certificate chain. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to obtain the error code. manipulating certificates cert_dupcertificate cert_destroycertificate cert_dupcertificate makes a shallow copy of a specified certificate. syntax #include <cert.h> certcertificate *cert_dupcertificate(certcertificate *c) parameter this function has the following parameter: c a pointer to the certificate object to be duplicated. ...
Network Security Services
explains the basic concepts of public-key cryptography that underlie nss. introduction to ssl introduces the ssl protocol, including information about cryptographic ciphers supported by ssl and the steps involved in the ssl handshake. getting started nss releases this page contains information about the current and past releases of nss. get the source code and build it instructions on how to build nss on the different supported platforms. nss apis introduction to network security services provides an overview of the nss libraries and what you need to know to use them. nss ssl public functions summarizes the ssl apis exported by the nss shared libraries. nss ssl reference api used to invoke ssl oper...
... supported platforms. nss apis introduction to network security services provides an overview of the nss libraries and what you need to know to use them. nss ssl public functions summarizes the ssl apis exported by the nss shared libraries. nss ssl reference api used to invoke ssl operations. nss api guidelines explains how the libraries and code are organized, and guidelines for developing code (naming conventions, error handling, thread safety, etc.) nss technical notes links to nss technical notes, which provide latest information about new nss features and supplementary documentation for advanced topics in programming with nss. tools, testing, and other technical details build instructions for nss d...
...ogramming with nss. tools, testing, and other technical details build instructions for nss describe how to check out and build nss releases. nss developer tutorial how to make changes in nss. coding style, maintaining abi compatibility. nss tools tools for developing, debugging, and managing applications that use nss. sample code demonstrates how nss can be used for cryptographic operations, certificate handling, ssl, etc. third-party code a list of third-party code included in the nss library. nss 3.2 test suite archived version. describes how to run the standard nss tests. nss performance reports archived version. links to performance reports for nss 3.2 and later releases. encryp...
Necko walkthrough
an nsdocumentopeninfo object, which implements nsistreamlistener, i.e. has onstartrequest, onstoprequest, ondataavailable, the three functions in which channel responses are received asynchronously. nshttpchannel::asyncopen called from openuri; openchannel isn't named the best, since the opening happens in the context of openuri, its calling function. this is where it hits necko code. but the interface for clients of necko is important to consider: send request uri helps creates channel setup channel (headers, request data, response callback...) channel->asyncopen. receive response get a callback to each of these: nsistreamlistener::onstartrequest (header info) nsistreamlistener::ondataavailable (data in single or multiple chunks) ...
... nsistreamlistener::onstoprequest (no more data from http) this all happens on the main thread, in a non-blocking fashion: make your request on the main thread, then carry on and get the async response later, also on the main thread. there is an option to receive ondataavailable specifically on a non-main thread, but all other calls happen on the main thread. ...
...et etc.). note: nsconnectionentry has a single nshttpconnectioninfo object attached, a pending queue of nshttptransactions, and 3 arrays for connections: active nshttpconnections idle nshttpconnections nshalfopensockets nshttpconnectionmgr::trydispatchtransaction there is a series of decisions about whether dispatchtransaction is called, along with good code comments: best to read the code for more detail. basically, if a connection is available... nshttpconnectionmgr::dispatchtransaction nshttpconnectionmgr::dispatchabstracttransaction the transaction is given an indirect reference to the connection (for use later, when the socket has received data from the far end). nshttpconnection::activate this connection is passed th...
Rhino Debugger
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 history of the commands you have entered. you may move backward and forward through the histo...
...re 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-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 n...
...in window. the expressions you enter are re-evaluated in the current scope and their current values displayed each time control returns to the debugger or when you change the stack location in the context: window. evaluation window the evaluate pane located in the lower-right (dockable) pane in the debugger main window contains an editable command line where you may enter arbitrary javascript code. the code is evaluated in the context of the current stack frame. the window maintains a history of the commands you have entered. you may move backward or forward through the history by pressing the up/down arrow keys on the keyboard. ...
Rhino history
etscape stopped work on "javagator," as it was called, somehow rhino escaped the axe (rumor had it that the executives "forgot" it existed). for a time, a couple of major companies (including sun) licensed rhino for use in their products and paid netscape to do so, allowing work on rhino to continue. now rhino is part of mozilla's open-source repository. originally, rhino compiled all javascript code to java bytecodes in generated classfiles. this produced the best performance (often beating the c implementation of javascript when run on a jit), but suffered from two faults. first, compilation time was long since generating java bytecodes and loading the generated classes was a heavyweight process. also, the implementation effectively leaked memory since most jvms don't really collect unused ...
...compilation is faster and when scripts are no longer in use they can be collected like any other java object. rhino was released to mozilla.org in april 1998. originally rhino classfile generation had been held back from release. ...
...ted like any other java object. rhino was released to mozilla.org in april 1998. originally rhino classfile generation had been held back from release. however the licensees of rhino have now agreed to release all of rhino to open source, including class file generation. since its release to open source, rhino has found a variety of uses and an increasing number of people have contributed to the code. ...
Rhino overview
l other versions are ecma compliant. string.prototype.split for version 1.2 only, split performs the perl4 special case when given a single space character as an argument (skips leading whitespace, and splits on whitespace). all other versions split on the space character proper as specified by ecma. security the security features in rhino provide the ability to track the origin of a piece of code (and any pieces of code that it may in turn generate). these features allow for the implementation of a traditional url-based security policy for javascript as in netscape navigator. embeddings that trust the javascript code they execute may ignore the security features. embeddings that run untrusted javascript code must do two things to enable the security features. first, every context that is...
...omain should be changed to true in the resource bundle org.mozilla.javascript.resources.security. the value of this property can be determined at runtime by calling the issecuritydomainrequired method of context. setting this property to true requires that any calls that compile or evaluate javascript must supply a security domain object of any object type that will be used to identify javascript code. in a typical client embedding, this object might be a string with the url of the server that supplied the script, or an object that contains a representation of the signers of a piece of code for certificate-based security policies. when javascript code attempts a restricted action, the security domain can be retrieved in the following manner. the class context should be obtained from the secur...
...if the caller is javascript the class obtained may be one of two types. first, it may be the class of the interpreter if interpretive mode is in effect. ...
Future directions
and of course, the idea of the future is always evolving in time as things change and we learn more. concurrent and wasm gc we are working towards a concurrent collector. we would also like to allow webassembly to interact with gc-managed data. ...
...and of course, the idea of the future is always evolving in time as things change and we learn more. concurrent and wasm gc we are working towards a concurrent collector. we would also like to allow webassembly to interact with gc-managed data. ...
...and of course, the idea of the future is always evolving in time as things change and we learn more. concurrent and wasm gc we are working towards a concurrent collector. we would also like to allow webassembly to interact with gc-managed data. ...
Exact Stack Rooting
he gcthing is already rooted on some previous stack frame, freeing us from having to worry about rooting the gcthing for the duration of the call. bool hello(jscontext *cx, handleobject foo) { return hello(cx, foo); } ..... void otherfunction(jscontext *cx) { ... rootedobject obj(cx, ...); hello(cx, obj); ... } a secondary benefit: since all js functions take js::handlets, code that does not root cstack gcpointers correctly will be much less likely to compile. warning: js::handlet does not root objects itself! that is the job of js::rootedt. warning: never give a function a js::handlet return type: this can easily lead to a js::handlet outliving its js::rootedt's lifetime. js::mutablehandle<t> typedef js::mutablehandle<t> js::mutablehandlet; -> mutablehandleobje...
...on the stack so that the conservative scanner will find it. this distinction should not be noticable to the end user. performance tweaking in aggregate, exact and conservate stack rooting should have similar performance. the performance tradeoffs that these techniques make, however, are quite different. if the extra overhead of exact rooting does end up adding an unacceptable cost to a specific code path that is not mitigated by a faster gc, there are some tricks you can use to get better performance at the cost of more complex code. move js::rootedt declarations above loops. modern c++ compilers are not smart enough to do licm on js::rootedt, so forward declaring a single js::rootedt above the loop and re-using it on every iteration can save some cycles. raw pointers. if you are 100% su...
...g it on every iteration can save some cycles. raw pointers. if you are 100% sure that there is no way for spidermonkey to gc while the pointer is on the stack, this is an option. note: spidermonkey can gc because of any error, gc because of timers, gc because we are low on memory, gc because of environment variables, gc because of cosmic rays, etc. this is not a terribly safe option for embedder code, so only consider this as a very last resort. ...
JS::DeflateStringToUTF8Buffer
this article covers features introduced in spidermonkey 38 encode the given string as utf8 into given buffer. syntax // new in jsapi 52 void deflatestringtoutf8buffer(jsflatstring* src, mozilla::rangedptr<char> dst, size_t* dstlenp = nullptr, size_t* numcharsp = nullptr); // obsolete in spidermonkey 49 void deflatestringtoutf8buffer(jsflatstring* src, mozilla::rangedptr<char> dst); name type description src jsflatstring * the pointer to the string to deflate. dst mozilla::rangedptr<char> the ranged pointer to the buffer. dstlenp size_t* the pointer to receive the number of bytes written to the buffer. ...
...ing* src, mozilla::rangedptr<char> dst); name type description src jsflatstring * the pointer to the string to deflate. dst mozilla::rangedptr<char> the ranged pointer to the buffer. dstlenp size_t* the pointer to receive the number of bytes written to the buffer. numcharsp size_t* the pointer to receive the number of unicode characters written to the buffer. description js::deflatestringtoutf8buffer encodes src as utf8. the caller must either ensure dst has enough space to encode the entire string, or pass the length of the buffer as dstlenp. in which case, the function will encode characters from the string until the buffer is exhausted. does not write the null terminator. if dstlenp is provided, it will be...
...nsure dst has enough space to encode the entire string, or pass the length of the buffer as dstlenp. in which case, the function will encode characters from the string until the buffer is exhausted. does not write the null terminator. if dstlenp is provided, it will be updated to hold the number of bytes written to the buffer. if numcharsp is provided, it will be updated to hold the number of unicode characters written to the buffer. this can be less than the length of the string, if the buffer is exhausted before the string is fully encoded. examples char16_t uchars[] = { 0xd83e, 0xdd8a, 0 }; js::rootedstring str(cx, js_newucstringcopyn(cx, uchars, 2)); if (!str) return false; js::rooted<jsflatstring*> flatstr(cx, js_flattenstring(cx, str)); if (!flatstr) return false; size_t length = j...
JSNative
syntax typedef bool (* jsnative)(jscontext *cx, unsigned argc, js::value *vp); name type description cx jscontext * the context in which the native function is being called. provides request. ...
... syntax typedef bool (* jsnative)(jscontext *cx, unsigned argc, js::value *vp); name type description cx jscontext * the context in which the native function is being called. provides request. ...
... syntax typedef bool (* jsnative)(jscontext *cx, unsigned argc, js::value *vp); name type description cx jscontext * the context in which the native function is being called. provides request. ...
JS_BeginRequest
this "request model" is necessary to interlock with the global garbage collector. ...
... syntax void js_beginrequest(jscontext *cx); void js_endrequest(jscontext *cx); name type description cx jscontext * the context in which the calling thread intends to call jsapi functions. description when your multithreaded application wants to use a jscontext, it must use js_beginrequest and js_endrequest to bracket maximal non-blocking hunks of native code that call the jsapi. this "request model" is necessary to interlock with the global garbage collector. in a js_threadsafe build, many jsapi functions must only be called from within a request. in this reference, the cx parameter of such functions is documented with the phrase “requires request”, like this: name type description cx jscontext * the context to us...
...fe build, the caller must be in a request on this jscontext. in a debug build, this is enforced with assertions. requests constrain garbage collection. if any thread is in a requests, garbage collection can happen only when that thread calls into the jsapi. if one thread needs garbage collection, it blocks until each other thread makes a jsapi call. it is therefore imperative that native code executing within an active request on cx not block, or simply take too long, outside the jsapi. any blocking native call, or lengthy computation that can race safely with the garbage collector, within a request, must be bracketed with js_suspendrequest and js_resumerequest. it is safe to nest calls to js_beginrequest so long as each call is balanced by a matching call to js_endrequest. jsapi 1.
JS_CompileFunctionForPrincipals
to the structure holding the security information for this function. name const char * name to assign the newly compiled function. nargs unsigned int number of arguments to pass to the function. argnames const char ** names to assign to the arguments passed to the function. body const char * or const jschar * string containing the source code of the function to compile. length size_t the length, in characters, of body. filename const char * name of file or url containing the function. used to report filename or url in error messages. lineno unsigned int line number. used to report the offending line in the file or url if an error occurs. description js_compilefunctionforprincipals c...
...rl containing the function. used to report filename or url in error messages. lineno unsigned int line number. used to report the offending line in the file or url if an error occurs. description js_compilefunctionforprincipals compiles a security-enabled function from a text string, bytes, and associates it with a js object, obj. js_compileucfunctionforprincipals is the unicode version of the function. principals is a pointer to the jsprincipals structure that contains the security information to associate with this function. name is the name to assign to the newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match ...
...contains the security information to associate with this function. name is the name to assign to the newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. body is the string containing the source code of the function. length is the length of the string in characters. filename is the name of the file (or url) containing the function. this information is passed in messages if an error occurs during compilation. similarly, lineno is used to report the line number of the function or file where an error occurred during compilation. on success, js_compilefunctionforprincipals and js_compileucfunct...
JS_DecompileFunction
if successful, js_decompilefunction returns a string containing the text of the function. otherwise, it returns null. ...
...:handle<jsfunction*> fun); 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. fun js::handle&lt;jsfunction*&gt; function to decompile. description js_decompilefunction generates the complete source code of a function declaration from a function's compiled form, fun. if successful, js_decompilefunction returns a string containing the text of the function. otherwise, it returns null. if you decompile a function that does not make a native c call, then the text created by js_decompilefunction is a complete function declaration suitable for re-parsing. if you decompile a function that makes a nati...
...n. if successful, js_decompilefunction returns a string containing the text of the function. otherwise, it returns null. if you decompile a function that does not make a native c call, then the text created by js_decompilefunction is a complete function declaration suitable for re-parsing. if you decompile a function that makes a native c call, the body of the function contains the text "native code'" and cannot be re-parsed. see also mxr id search for js_decompilefunction js_decompilescript js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_decompilefunctionbody js_definefunction js_definefunctions js_getfunctionobject js_newfunction js_setbranchcallback js_valuetofunction ...
JS_DecompileFunctionBody
generate the source code representing the body of a function, minus the function keyword, name, parameters, and braces. syntax jsstring * js_decompilefunctionbody(jscontext *cx, js::handle<jsfunction*> fun, unsigned indent); name type description cx jscontext * the context in which to decompile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handle&lt;jsfunction*&gt; the function to decompile. indent unsigned if it's not js_dont_pretty_print, js_decompilefunction returns pretty printed source code of the function. ...
...to decompile the function. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. fun js::handle&lt;jsfunction*&gt; the function to decompile. indent unsigned if it's not js_dont_pretty_print, js_decompilefunction returns pretty printed source code of the function. ...
... indent unsigned if it's not js_dont_pretty_print, js_decompilefunction returns pretty printed source code of the function. description js_decompilefunctionbody generates the source code of a function's body, minus the function keyword, name, parameters, and braces, from a function's compiled form, fun. if successful, js_decompilefunctionbody returns a string containing the source code of the function body. otherwise, it returns null. the source code generated by this function is accurate but unadorned and is not suitable for recompilation without providing the function's declaration. if you decompile a function that makes a native c call, the body of the function only contains the text "[native code]". notes to decompile a complete function, including its body and declaration,...
JS_DecompileScript
if the script is not cached, it tries to load the source from file, and returns nullptr if an error happened while loading. ...
...pilescript(jscontext *cx, js::handle<jsscript*> script); name type description cx jscontext * the context to use to decompile the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. script js::handle<jsscript*> script or function to decompile. description js_decompilescript returns the source code of script. if script is a function, it calls js_decompilefunction. otherwise, it returns the original source code of the script. if the script is not cached, it tries to load the source from file, and returns nullptr if an error happened while loading. if successful, js_decompilescript returns a string containing the source code of the script. otherwise, it returns a string containing "[no sourc...
...rce code of the script. if the script is not cached, it tries to load the source from file, and returns nullptr if an error happened while loading. if successful, js_decompilescript returns a string containing the source code of the script. otherwise, it returns a string containing "[no source]". from spidermonkey 17, this does not actually decompile the script, but returns the original source code (bug 761723). see also mxr id search for js_decompilescript js::compile js_compilescript js_decompilefunction js_destroyscript js::evaluate js_executescript bug 761723 ...
JS_SetNativeStackQuota
this article covers features introduced in spidermonkey 17 enable or disable checks to avoid overflowing the c stack. syntax void js_setnativestackquota(jsruntime *cx, size_t systemcodestacksize, size_t trustedscriptstacksize = 0, size_t untrustedscriptstacksize = 0); name type description rt jsruntime * the runtime. systemcodestacksize size_t the desired stack quota setting, in bytes. trustedscriptstacksize size_t the desired stack quota setting, in bytes for trusted script. if omitted, it uses the value of systemcodestacksize. added in spidermonkey 31 untrustedscriptstacksize size_t the desired stack quota setting, in bytes for untrusted script. if o...
...key 31 untrustedscriptstacksize size_t the desired stack quota setting, in bytes for untrusted script. if omitted, it uses the value of trustedscriptstacksize. added in spidermonkey 31 description js_setnativestackquota sets the size of the native stack that should not be exceeded. to disable stack size checking, pass 0. spidermonkey allows for a distinction between system code (such as gcs, which may incidentally be triggered by script but are not strictly performed on behalf of such script), trusted script (as determined by js_settrustedprincipals), and untrusted script. each kind of code may have a different stack quota, allowing embedders to keep higher-priority machinery running in the face of scripted stack exhaustion by something else. the stack quotas for each ...
...s gcs, which may incidentally be triggered by script but are not strictly performed on behalf of such script), trusted script (as determined by js_settrustedprincipals), and untrusted script. each kind of code may have a different stack quota, allowing embedders to keep higher-priority machinery running in the face of scripted stack exhaustion by something else. the stack quotas for each kind of code should be monotonically descending, and may be specified with this function. if 0 is passed for a given kind of code, it defaults to the value of the next-highest-priority kind. this function may only be called immediately after the runtime is initialized and before any code is executed and/or interrupts requested. see also mxr id search for js_setnativestackquota js_settrustedprincipals b...
SpiderMonkey 31
g under product: core, component: javascript engine. the download url is outdated and spidermonkey not release alone! get it here mozilla-esr31 you will find it in "firefox extended support release 31" package on hg release platform support spidermonkey 31 is supported on all the platforms where firefox 31 runs. compiling it requires a c++ compiler, and the jsapi can only be used from c++ code. if you are compiling with microsoft's visual studio, note that the minimum supported version is msvc10/2010: msvc8/9 support has been dropped. spidermonkey 31 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase. it is supported on x86, x86_64, and arm architectures. on some other platforms (sparc, mips), the jit is provided but not ...
...it's the same language, just not as fast. ...
...nt the same interface as js::value, for simplicity and to ease migration pain. changes to introduce handles to the jsapi are not individually documented, because of the breadth of the changes involved. the following features in earlier versions of spidermonkey have been dropped. xxx list removed features here spidermonkey 31 is not binary-compatible with previous releases, nor is it source-code compatible. many jsapi types, functions, and callback signatures have changed, though most functions that have changed still have the same names and implement essentially unchanged functionality. applications will need significant changes, but most of those changes will be detected by the c/c++ compiler, so they are easy to detect and updating the code is a fairly straightforward job. here is a l...
Thread Sanitizer
the same reason. you can check which version of clang you have by running the command: clang -v if you are not building from mozilla-central and are building firefox 39 or earlier, you must use clang 3.3. you can find precompiled binaries for llvm/clang 3.3 on the llvm releases page. we recommend using clang 3.6 or later. ...
...lding firefox getting the source if you don't have a source code repository clone yet, you need to get yourself a clone of mozilla-central. adjusting the build configuration create the build configuration file .mozconfig with the following content in your mozilla-central directory: mk_add_options moz_objdir=@topsrcdir@/objdir-ff-tsan mk_add_options moz_make_flags=-j12 # enable llvm specific code and build workarounds ac_add_options --enable-thread-sanitizer # if clang is already in your $path, then these can simply be: # export cc=clang # export cxx=clang++ export cc="/path/to/clang" export cxx="/path/to/clang++" # llvm-symbolizer displays much more complete backtraces when data races are detected. # if it's not already in your $path, then uncomment this next line: #export llvm_symb...
...n you will want to set the variable to $llvm_home/build/bin/llvm-symbolizer. ignoring known races in some cases, races can be confirmed to be benign and fixing them would cause possible performance issues. tsan offers two possibilities to ignore such known races. compile-time blacklisting functions with racy memory access can be flagged, such that the compiler will not instrument them. in our codebase, this is done using the moz_tsan_blacklist macro on the function definition. it will expand to the appropriate attributes if the compiler supports them. compile-time blacklisting is the preferred way of blacklisting, because it does not have a performance impact. still, blacklisting should be done very carefully so we won't miss important bugs. runtime suppressions to prevent races from sho...
Browser security
a web pki x509 certificate primerx.509 (in this document referred as x509) is an itu standard to describe certificates. ...
... a web pki x509 certificate primerx.509 (in this document referred as x509) is an itu standard to describe certificates. ...
... ...
AT APIs Support
ind helpful the about:accessibilityenabled firefox extension. supported at apis at apis terms microsoft active accessibility (msaa) an api devised by microsoft so that accessibility aids can track what's going on inside the user interface of any software package that supports it. if you seriously need to understand msaa, you'll need to read the docs on msdn and play with the sample apps and code that come with msaa sdk 1.3. (i recommend sdk 1.3 because the msaa sdk 2.0 doesn't come with the source code to the testing tools. the other differences are not important). iaccessible2 (ia2) iaccessible2 is a new accessibility api which complements microsoft's earlier work on msaa. this api fills critical accessibility api gaps in the msaa offering. assistive technology service provider inter...
... critical accessibility api gaps in the msaa offering. assistive technology service provider interface (at-spi) an api devised by sun microsystems so that accessibility aids can track what's going on inside the user interface of any software package that supports it. if you seriously need to understand at-spi, you'll need to read the docs on gnome.org and play with the available sample apps and code, such as at-poke. please note that the web docs are sometimes out of date, and the latest at-spi is available on cvs. universal access (ua) universal access (ua) is the apple's accessibility framework. windows platform we support msaa (microsoft active accessibility) and iaccessible2 on windows. also we expose ms com interfaces isimpledom* to provide an access to dom tree. iaccessible2 is a...
...gecko uses the standard keyboard api's for each supported platform. the mozilla keyboard shortcuts for content are similar to what is used in other browsers. here is a list of firefox keyboard shortcuts. test tools here you will find a list of tools to test accessibility gecko-based applications. msaa msaa sdk tools - version 1.3 is recommended instead of 2.0 because it includes source code for the tools iaccessible2 accessibility probe -- includes msaa support as well atk/at-spi accerciser - interactive python accessibility explorer for the gnome desktop gecko dom inspector has an ability to test gecko accessibility layer, supports base features. firebug screen readers here's a list of screen readers we are oriented to in the first pla...
Feed content access API
s functions that let you fetch the text as plain text or html. nsiscriptableunescapehtml a utility class that unescapes html strings. example: reading a feed from the web it's actually quite easy to read and parse a feed. use an xmlhttprequest to load the feed, then pass its string to an nsifeedprocessor to parse the feed. ...
...the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parsefromstring() method. however, you could also parse it from a file using parsefromstream(), or directly from an url using parseasync(). the actual processing of the parsed feed is done by a method called handleresult() on the feedtestresultlistener object. ...
... doc.close(); } } the handleresult() function receives as its argument an nsifeedresult that describes a feed; its doc property is an nsifeed that contains all the feed data. to get the title of the feed, you look at the feed.title property. the title is an nsifeedtextconstruct that can represent the text in various formats; we get its text property to fetch the feed's title as html-encoded text. we could, alternatively, use its plaintext() method to get a copy of the title translated into plain text. we then scan the array of items in the feed by looking at the feed.items nsiarray. this array contains nsifeedentry objects that describe each feed item. we build the contents of the document by looking at the title, link, summary, and content properties for each item. the full url of...
Manipulating bookmarks using Places
(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method. for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it. specifying default_index as the index at which to insert the new folder places it at the end of the list. you can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksmenufolder to another folder attribute. creating a new bookmark to create a new bookmark, ...
...f a site and wish to find all bookmarks that link to it, you can use the nsinavbookmarksservice.getbookmarkidsforuri() method. var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var bookmarksarray = bmsvc.getbookmarkidsforuri(uri, {}); after executing this code, the array bookmarksarray contains the ids of all bookmarks that refer to the specified uri (in this case, "http://google.com"). manipulating existing items there are a number of convenient methods you can use to make changes to existing bookmarks and bookmark folders. this section covers some of them. the item title to change the title of a bookmark or bookmark folder, you use the nsinavbook...
...title to change the title of a bookmark or bookmark folder, you use the nsinavbookmarksservice.setitemtitle() method. bmsvc.setitemtitle(newbkmkid, "new title"); this sets the title of the item referenced by the id newbkmkid to "new title". you can fetch the current title of an item using the nsinavbookmarksservice.getitemtitle() method: var thistitle = bmsvc.getitemtitle(newbkmkid); this code will display an alert containing the title of the item referenced by the id newbkmkid. the item uri similarly, you can obtain the uri corresponding to a given bookmark item by calling the nsinavbookmarksservice.getbookmarkuri() method. var thisuri = bmsvc.getbookmarkuri(newbkmkid); assuming you've run all the code samples previous to this one, this will output "http://google.com". you can u...
Places Developer Guide
overview places 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. ...
...onendupdatebatch: function() { this._inbatch = false; }, onitemadded: function(id, folder, index) { }, onitemremoved: function(id, folder, index) { }, onitemchanged: function(id, property, isannotationproperty, value) { // isannotationproperty is a boolean value that is true of the changed property is an annotation. // you can access a bookmark item's annotations with the <code>nsiannotationservice</code>. }, onitemvisited: function(id, visitid, time) { // the visit id can be used with the history service to access other properties of the visit. // the time is the time at which the visit occurred, in microseconds. }, onitemmoved: function(id, oldparent, oldindex, newparent, newindex) { // oldparent and newparent are the ids of the old and new parent ...
...var historyservice = components.classes["@mozilla.org/browser/nav-history-service;1"] .getservice(components.interfaces.nsinavhistoryservice); var query = historyservice.getnewquery(); var options = historyservice.getnewqueryoptions(); options.sortingmode = options.sort_by...
XML Extras
th some caveats: all functions and property names begin with a lower case letter and the object creation is different. some properties are not implemented. thad hoffman has written a document that shows how you can mimic xml data islands in mozilla. edmond woychowsky has also written articles on xml data islands in mozilla: "make xml data islands work in mozilla", "build cross-browser xml paging code" and "implement a flexible shopping cart with xml and asp". the mozilla developer center has several pages for xmlhttprequest. below are some key differencies in "xml extras" between mozilla and microsoft software: difference microsoft mozilla member names case insensitive? begins with lower case letter xmlhttprequest creation new activexobject("msxml2.
... ...
... ...
Building the WebLock UI
mponent is being installed in mozilla or another gecko-based browser, then this third section shows you how to create the entry point in the browser for controlling the web locking. if you are planning on deploying the weblock component in some other application, you'll have to devise a different means of access (e.g., native widgetry that instantiates and controls the weblock component). client code overview before we get started on the actual user interface, we should establish how the client code is to access the weblock component and use its interfaces to control the web locking of the browser. first of all, it's important to be able to represent the basic state of the lock as soon as it's loaded. like the secure page icon, the weblock icon that appears in the lower right corner of the ...
... control the web locking of the browser. first of all, it's important to be able to represent the basic state of the lock as soon as it's loaded. like the secure page icon, the weblock icon that appears in the lower right corner of the browser should indicate whether the browser is currently locked or unlocked. since the weblock component is always initialized as unlocked, we can have the client code - the javascript code in the interface - represent this state and track it as the user manipulates the iweblock interface. a boolean wlocked variable can do this: // initialize the wlocked variable as unlocked var wlocked = 0; then the functions that get called from the interface and call through to the lock and unlock methods of the weblock component must also adjust this variable accordingly...
...nvisible - that controls the way its child elements are rendered. in this case the <hbox/> centers the textbox and the button children, and it orients them horizontally (in contrast to the <vbox/>, which orients its children vertically). notice also that when it's clicked, the button executes a javascript function called addthissite(), which we've already defined in the weblock.js file in client code overview above. weblock.xul <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog id="weblock_mgg" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="web lock manager" style="width: 30em;" persist="screenx screeny" screenx="24" screeny="24"> <script src="chrome://weblock/content/weblock.js"/> ...
Making cross-thread calls using runnables
chrome javascript should instead use workers. ...
...chrome javascript should instead use workers. in general, threading and message passing should be asynchronous. ...
...in case of failure, call back immediately with an empty string which indicates failure callback(emptycstring()); return; } nscomptr<nsirunnable> r = new picalculatetask(callback, digits); mythread->dispatch(r, nsieventtarget::dispatch_normal); // the result callback will shut down the worker thread, we can let it go here... } see also chromeworker using workers in javascript code modules the thread manager ...
XPCOM guide
Mozilla › Tech › XPCOM › Guide
these articles provide tutorials and usage documentation for xpcom, including how to use it in your own projects and how to build xpcom components for your firefox add-ons and the like. avoiding leaks in javascript xpcom componentsprogrammers writing and reviewing javascript code in mozilla should understand how code using xpcom in javascript can leak so that they can avoid leaks. this document attempts to help them do so, first by explaining the underlying concepts, and second by describing a number of common javascript patterns that cause leaks.creating xpcom componentsthis guide is about gecko, and about creating xpcom components for gecko-based applications.how to build an xpcom component in javascriptif you are looking for add-on sdk solution for xpcom javascript components ...
...rchy, you run into multiple inheritance. that's not inherently multiple inheritance, though, because you only mix in interfaces (i.e. the problem would not exist with java's interfaces).making cross-thread calls using runnablesin the mozilla platform, most activities such as layout, dom operations, content javascript, and chrome javascript run on the main thread. however, it may be useful for c++ code in the mozilla platform to run tasks on another thread.mozilla internal string guidemost of the mozilla code uses a c++ class hierarchy to pass string data, rather than using raw pointers. this guide documents the string classes which are visible to code within the mozilla codebase (code which is linked into libxul). mozilla::services namespacethe services c++ namespace offers an easy and eff...
...cribes the available arrays as well as the enumerator classes that can be used to get to them. in this document the term array refers to a container for multiple objects with a numeric, zero-based index.xpcom changes in gecko 2.0several changes that affect xpcom component compatibility are taking place in gecko 2. this article details those changes, and provides suggestions for how to update your code.xpcom hashtable guidea hashtable is a data construct that stores a set of items. each item has a key that identifies the item. items are found, added, and removed from the hashtable by using the key. hashtables may seem like arrays, but there are important differences:xpcom stream guidein mozilla code, a stream is an object which represents access to a sequence of characters. it is not that sequ...
How to build a binary XPCOM component using Visual Studio
sewhere. development setup the simplest way to get an xpcom component built is to use the gecko sdk. on windows, the sdk is built using a microsoft compiler, so you need to use one too. this tutorial uses microsoft’s free visual c++ express and the sample project in the next paragraph. you could try to use a different vendor's compiler, but you are going to need to build the sdk from source code. not the simplest thing to do and it may be incompatible with production releases of firefox, thunderbird, and xulrunner from mozilla. for example, xulrunner 1.8.0.4 which has a pre-built sdk at gecko-sdk-win32-msvc-1.8.0.4.zip. extract the sdk to a folder. the tutorial assumes the folder is called xulrunner-1.8.0.4, but you can call yours whatever you want. you also need a couple of pre-built li...
...mentation object. the blank vc++ project has a bat file that will create the xpt and the h files. the command executes xpidl.exe twice, like this: {path_to_geckosdk}\bin\xpidl.exe -m header -i..\gecko-sdk\idl {your_idl_file} {path_to_geckosdk}\bin\xpidl.exe -m typelib -i..\gecko-sdk\idl {your_idl_file} the generated h file actually has a skeleton implementation (commented out). you can take the code and create implementation h and cpp files. they could look like this: h file: #ifndef __specialthing_impl_h__ #define __specialthing_impl_h__ #include "comp.h" #include "nsstringapi.h" #define specialthing_contractid "@starkravingfinkle.org/specialthing;1" #define specialthing_classname "specialthing" #define specialthing_cid { 0x245626, 0x5cc1, 0x11db, { 0x96, 0x73, 0x0, 0xe0, 0x81, 0x61, 0x1...
...e0, 0x81, 0x61, 0x16, 0x5f } } class cspecialthing : public ispecialthing { public: ns_decl_isupports ns_decl_ispecialthing cspecialthing(); private: ~cspecialthing(); protected: /* additional members */ nsstring mname; }; #endif cpp file: #include "comp-impl.h" ns_impl_isupports1(cspecialthing, ispecialthing) cspecialthing::cspecialthing() { /* member initializers and constructor code */ mname.assign(l"default name"); } cspecialthing::~cspecialthing() { /* destructor code */ } /* attribute astring name; */ ns_imethodimp cspecialthing::getname(nsastring & aname) { aname.assign(mname); return ns_ok; } ns_imethodimp cspecialthing::setname(const nsastring & aname) { mname.assign(aname); return ns_ok; } /* long add (in long a, in long b); */ ns_imethodimp cspecialthing::ad...
How To Pass an XPCOM Object to a New Window
for example: var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"]. ...
...for example: var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"]. ...
... ...
Components.utils.evalInWindow
this function is no longer available as of firefox 34. see bug 1042840 for details. this function enables code running in a more-privileged javascript context to evaluate a string in a less-privileged javascript context. the result is structured cloned back to the original context, unless it is native (for example, if it returns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper already), so it's guaranteed to behave predictably. this is useful for privileged code, such as add-on code, to access variables and apis defined in web content. ...
... result is structured cloned back to the original context, unless it is native (for example, if it returns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper already), so it's guaranteed to behave predictably. this is useful for privileged code, such as add-on code, to access variables and apis defined in web content. even so, while the code is being evaluated it is in the content's context, so the caller has to be prepared for the possibility that the content could have redefined behavior (for example, a setter in the script may have been redefined to do something unexpected). this function is made available as a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. syntax var result = compone...
...pose a page script defines a variable: // page-script.js var somelocalvariable = { name: "selection1", node: document.documentelement }; an add-on script or other privileged script can access the variable using evalinwindow(): // add-on-script.js var result = components.utils.evalinwindow("somelocalvariable", contentwindow); console.log(result); // {"name":"selection1","node":{}} the add-on code can modify the variable as well, of course: // add-on-script.js components.utils.evalinwindow("somelocalvariable.newprop = 42", contentwindow); // page-script.js console.log(window.somelocalvariable.newprop); // 42 but note that the add-on script must trust that the page script has not redefined the setter on somelocalvariable: unlike xraywrappers, evalinwindow() does not provide x-ray vision.
Components.utils.exportFunction
this function provides a safe way to expose a function from a privileged scope to a less-privileged scope. in this way privileged code, such as an extension, can share code with less-privileged code like a normal web page script. a function exported from privileged to less-privileged code can be called from the less privileged code's context. the function has access to its surrounding closure just as if it were being called in the privileged context. the exported function does not have to be added to the less privileged code's global window object: it can be exported to any object in the target scope. exportfunction() is made available as a global in sandboxes which have the wantexporthelpers option set in the sandbox() constructor. this includes add-on sdk content scripts. to...
...} var test = document.getelementbyid("test"); test.addeventlistener("click", function() { window.loguser(getuser); }, false); cross-origin checking when the exported function is called each argument, including this, is checked to make sure that the caller subsumes that argument. this prevents passing cross-origin objects (like window or location) to privileged functions, since the privileged code will have full access to those objects and might unintentionally do something dangerous. this provision can be overridden by passing { allowcrossoriginarguments: true } to exportfunction. example export to global scope this add-on script defines a function, then exports it to a content window: // addon-script.js var salutation = "hello "; function greetme(user) { return salutation + user;...
...suppose the content window defines a local variable bar: // page-sc...
Components.utils.importGlobalProperties
g scope's global. the following strings are supported: string/object xpcom component atob blob btoa crypto css fetch file nsidomfile indexeddb nodefilter firefox 60 nsidomnodefilter obsolete since gecko 60 rtcidentityprovider textdecoder textencoder url urlsearchparams xmlhttprequest nsixmlhttprequest obsolete since gecko 60 for string/object in table without a minimum firefox version, it is not exactly known since when it was available, however it is guranteed available from firefox 28 and up. syntax void components.utils.importglobalproperties([string1, str...
..., however it is guranteed available from firefox 28 and up. syntax void components.utils.importglobalproperties([string1, string2, ...]); parameters [string1, string2, ...] an array of strings. each string is the name of an object to import. example components.utils.import("resource://gre/modules/devtools/console.jsm"); components.utils.importglobalproperties(["atob", "btoa"]); var encoded = btoa("hello"); console.log(encoded); // "sgvsbg8=" console.log(atob(encoded)); // "hello" alternative methods if importglobalproperties does not support the targeted firefox version, here are some alternative methods to import these objects. import from jsm this method worked until blob and file were no longer apart of jsm modules. it is suspected this works up till f...
.../ "hello" alternative methods if importglobalproperties does not support the targeted firefox version, here are some alternative methods to import these objects. import from jsm this method worked until blob and file were no longer apart of jsm modules. it is suspected this works up till firefox 35. this imports blob, file, along with the regular services. the reason this works is because js code modules actually have blob and file. cu.import() will return the full global of a code module. knowing that, we can just get a valid blob by importing a known module that has the objects, such as services.jsm const {blob, file, services} = cu.import("resource://gre/modules/services.jsm", {}); reference: stackoverflow :: use blob on firefox add-on hiddendomwindow the hidden domwindow has all o...
XPConnect wrappers
ects are created when any natively implemented xpcom object (that is, any object implemented in c++) needs to be reflected into javascript. this includes all dom objects (including window) and chrome elements that are reflected into javascript. this wrapper is responsible for mapping calls from javascript into c++. this means that when you say window.focus(), you're calling into xpcwrappednative code. if you call 'tostring()' and get "[xpconnect wrapped nsifoo]" then the reference is to a xpcwrappednative object with interface nsifoo. they are implicitly created by xpconnect and you should not have to worry about how that happens. there are several types of wrapped natives, but i won't cover those here. xpcwrappedjs these objects are the exact opposite of xpcwrappednative. they exist to r...
...ist to reflect an object from javascript into c++. this means that whenever you pass your javascript object into a c++ function, we create one of these wrappers. for example, if you've implemented some component with an interface nsifoo and you pass your javascript object into a c++ function taking an nsifoo, an xpcwrappedjs is created around your object. c++ calls are routed through xpcwrappedjs code into your javascript implementation. these wrappers are created by xpconnect, so you should not have to worry about how to construct them or whether to construct them. double wrapping. there is one case where an xpcwrappednative wraps another wrapper object. this case is where a js object was passed in via some idl-declared interface, creating an xpcwrappedjs, and is now being returned to javas...
...d the xpcwrappedjs. security wrappers exposed to chrome to learn about security wrappers, see the article on script security in gecko. note that a previous version of the current page recommended using __exposedprops__ to expose objects from chrome to content. this is now deprecated and we are in the process of removing support for it. if you need to make objects or functions defined in chrome code accessible to content, use components.utils.cloneinto or components.utils.exportfunction. ...
Monitoring HTTP activity
this is very simple, requiring you to implement a single method, nsihttpactivityobserver.observeactivity(), which gets called each time an action of interest takes place on the http channel. ...
...this is very simple, requiring you to implement a single method, nsihttpactivityobserver.observeactivity(), which gets called each time an action of interest takes place on the http channel. ...
...re two classes of observable activities: those that occur at the socket level and those that occur at the http transaction level. observable socket activities when the activity type reported to your nsihttpactivityobserver.observeactivity() method is activity_type_socket_transport, the activity subtype, which indicates the specific type of activity that occurred, will be a socket transport status code. observable http activities when the activity type is activity_type_http_transaction, the activity subtype will be one of the activity subtype constants. these include the ability to monitor outgoing http request headers and bodies as well as incoming http headers and complete http transactions. ...
NS_ConvertASCIItoUTF16
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
NS ConvertASCIItoUTF16 external
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
NS_ConvertUTF16toUTF8
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
NS ConvertUTF16toUTF8 external
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
NS_ConvertUTF8toUTF16
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
NS ConvertUTF8toUTF16 external
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
NS_LossyConvertUTF16toASCII
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
NS LossyConvertUTF16toASCII external
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
PromiseFlatCString (External)
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
PromiseFlatString (External)
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsACString (External)
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsAString (External)
a character in a string. @return the offset of the character from the beginning of the string, or -1 if not found. ...
...urn the offset of the character from the beginning of the string, or -1 if not found. ...
... or -1 if not found. parameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
nsAdoptingCString
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsAdoptingString
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsAutoString
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsAutoString (External)
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsCAutoString
print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...e @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsCAutoString (External)
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsCString
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsCStringContainer (External)
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...id appendint(int, print32) - source append a string representation of a number. ...
nsCString external
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsDependentCString
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsDependentCString external
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsDependentCSubstring external
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsDependentString
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsDependentString external
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsDependentSubstring external
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...id appendint(int, print32) - source append a string representation of a number. ...
nsFixedCString
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsFixedString
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsLiteralCString (External)
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsLiteralString (External)
he string, or -1 if not found. ...
... parameters char achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsPromiseFlatCString
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsPromiseFlatString
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsString
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsStringContainer (External)
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsString external
ring, or -1 if not found. ...
...arameters prunichar achar appendint void appendint(int, print32) - source append a string representation of a number. ...
...d appendint(int, print32) - source append a string representation of a number. ...
nsXPIDLCString
e(const char*, print32) const - source equality check between given string and this string. @param astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...m astring is the string to check @param aignorecase tells us how to treat case @param acount tells us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... us how many chars to compare @return boolean parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
nsXPIDLString
d parameters prunichar* astring print32 aoffset print32 rfindcharinset(const nsstring&, print32) const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
... const - source parameters nsstring& astring print32 aoffset equalsignorecase prbool equalsignorecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
...orecase(const char*, print32) const - source parameters char* astring print32 acount tofloat float tofloat(print32*) const - source perform string to float conversion. ...
XPCOM glue classes
these "glue" classes are provided to make it easier to use xpcom from c++ code. when these classes are used by a component, you may need to link the component against the xpcom glue library. ns convertasciitoutf16 externalclass declarationns convertutf16toutf8 externalclass declarationns convertutf8toutf16 externalclass declarationns lossyconvertutf16toascii externalclass declarationns_convertasciitoutf16class declarationns_convertutf16toutf8class declarationns_convertutf8toutf16class declarationns_lossyconvertutf16toasciiclass declarationns_overridens_override is a macro which allows c++ code in mozilla to specify that a method is intended to override a base class method. if there is no base class method with the same signature, a compiler with static-checking enabled will fail t...
...ed of single-byte storage units. this class is typically used to represent ascii or utf-8 character arrays.nsacstring (external)class declarationnsacstring_internalclass declarationnsadoptingcstringclass declarationnsadoptingstringclass declarationnsastringthe nsastring abstract class represents a character string composed of double-byte storage units. ...
...truction of the object.</t>nsautoreftraitsnsautoreftraits<t> is a template class describing traits of resources held by objects of class nsautoref<t> and/or nscountedref<t>.</t>nsautostringclass declarationnsautostring (external)class declarationnscautostringclass declarationnscautostring (external)class declarationnscomptrthis utility class simplifies managing xpcom interface references from c++ code.nscountedrefnscountedref<t> is a template class implementing an object that takes a strong reference to a reference-counted resource that must be released, typically on destruction of the object.</t>nscstringclass declarationnscstring externalclass declarationnscstringcontainer (external)class declaration nscstringencodingthe nscstringencoding enumeration describes the set of character encodi...
mozIStorageConnection
te type description connectionready boolean indicates if the connection is open and ready to use. this will be false if the connection failed to open, or it has been closed. read only. databasefile nsifile the current database nsifile. null if the database connection refers to an in-memory database. read only. lasterror long the last sqlite error code that occurred. read only. note: this is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads. lasterrorstring autf8string the english error string reported by the sqlite library for the last sqlite operation. read only. note: this is not reliable if you are using asynchronous statements or if you are using the connec...
...nt has been executed asynchronously on the connection, or if the method was called on a thread other than the one that opened the connection. committransaction() this method commits the current transaction. void committransaction(); parameters none. createaggregatefunction() this method creates a new aggregate function that can be used in sql. see mozistorageaggregatefunction for sample code and more details. if you use your connection on multiple threads, your function needs to be threadsafe, or it should only be called on one thread. void createaggregatefunction( in autf8string afunctionname, in long anumarguments, in mozistorageaggregatefunction afunction ); parameters afunctionname the name of the aggregate function to create, as seen in sql. anumarguments th...
... javascript callers should use named parameters. mozistorageasyncstatement createasyncstatement( in autf8string asqlstatement ); parameters asqlstatement the sql statement to execute. return value returns a new mozistorageasyncstatement to be used to execute the specified statement. createfunction() creates a new function that can be used in sql. see mozistoragefunction for sample code and more details. if you use your connection on multiple threads, your function needs to be threadsafe, or it should only be called on one thread. void createfunction( in autf8string afunctionname, in long anumarguments, in mozistoragefunction afunction ); parameters afunctionname the name of function to create, as seen in sql. anumarguments the number of arguments the functi...
nsIAccessibleDocument
nt from the nsiaccessible or nsiaccessnode for the root node of a document. you can also get one from nsiaccessnode.getaccessibledocument() or nsiaccessibleevent.getaccessibledocument() method overview nsiaccessible getaccessibleinparentchain(in nsidomnode adomnode, in boolean acancreate); obsolete since gecko 2.0 nsiaccessnode getcachedaccessnode(in voidptr auniqueid); native code only! obsolete since gecko 2.0 astring getnamespaceuriforid(in short namespaceid); attributes attribute type description caretaccessible nsiaccessible read only. obsolete since gecko 1.9 doctype astring the doc type of the document, as specified in the document. read only. domdocument nsidomdocument the nsidomdocument in...
...e of the document, as specified in the document. read only. url astring the url of the document read only. window nsidomwindow the nsidomwindow that the document resides in. read only. windowhandle voidptr the window handle for the os window the document is being displayed in. for example, in windows you can static cast it to an hwnd. read only. native code only! methods getaccessibleinparentchain() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) returns the first accessible parent of a dom node. guaranteed not to return null if the dom node is in a document. nsiaccessible getaccessibleinparentchain( in nsidomnode adomnode, in boolean acancreate ); parameters adomnode the dom node ...
...accessible getaccessibleinparentchain( in nsidomnode adomnode, in boolean acancreate ); parameters adomnode the dom node we need an accessible for. acancreate if true, this method can create a new accessible. otherwise, it will return the first cached accessible in the parent chain. return value the first nsiaccessible found by crawling up the dom node to the document root. native code only!getcachedaccessnode 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. returns the access node cached by this document. nsiaccessnode getcachedaccessnode( in voidptr auniqueid ); parameters auniqueid the un...
nsIAppShell
create() obsolete since gecko 1.9 (firefox 3) creates an application shell. void create( inout int argc, inout string argv ); parameters argc the number of parameters passed in on the command line. argv a direct reference to the parameter array. dispatchnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app specific code. void dispatchnativeevent( in prbool arealevent, in voidptr aevent ); parameters arealevent event is real or a null placeholder (macintosh). aevent void pointer to native event structure. exit() exit the handle event loop. void exit(); parameters none. favorperformancehint() give hint to native event queue notification mechanism. if the native platform needs to tradeoff performance vs. na...
...oidptr aevent ); parameters arealevent event is real or a null placeholder (macintosh). aevent void pointer to native event structure. exit() exit the handle event loop. void exit(); parameters none. favorperformancehint() give hint to native event queue notification mechanism. if the native platform needs to tradeoff performance vs. native event starvation this hint tells the native dispatch code which to favor. the default is to prevent native event starvation. calls to this function may be nested. when the number of calls that pass pr_true is subtracted from the number of calls that pass pr_false is greater than 0, performance is given precedence over preventing event starvation. void favorperformancehint( in boolean favorperfoverstarvation, in unsigned long starvationdelay ); para...
...on true to favor event performance over event starvation, false to favor event starvation over event performance. starvationdelay is only used when favorperfoverstarvation is pr_false. it is the amount of time in milliseconds to wait before the pr_false actually takes effect. getnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app specific code. void getnativeevent( in prboolref arealevent, in voidptrref aevent ); parameters arealevent event is real or a null placeholder (macintosh). aevent void pointer to native event structure. listentoeventqueue() obsolete since gecko 1.9 (firefox 3) an event queue has been created or destroyed. hook or unhook it from your system, as necessary. void listentoeventqueue...
nsIDOMParser
this section covers changes introduced to domparser in gecko 1.9. (this section is only relevant to firefox extensions--not to web content.) to create a document, the parser needs to specify a principal (see security check basics), a base uri (see document.baseuriobject), and a documenturi. ...
...if the caller has universalxpconnect privileges, it can pass parameters to new domparser(). if fewer than three parameters are passed, the remaining parameters will default to null. ...
...null pointers for documenturi and baseuri. cases where these values matter: if you don't specify the document uri by calling init() after creating the parser via createinstance() the created documents will use a moz-nullprincipal:{<guid>} uri, which will show in the error console in parsing errors, in particular. supposedly, if you want to create objects that some particular set of unprivileged code will be able to access (see discussion in bug 565480). parsing a string once you've created a domparser object, you can use its parsefromstring method to parse xml or html as described in the web platform documentation. examples within the context of a window: var parser = new domparser(); var doc = parser.parsefromstring(astr, "application/xml"); outside of a window (e.g., a js xpcom component...
nsIDeviceMotion
1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) note: this interface was named nsidevicemotion prior to gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3). method overview void addlistener(in nsidevicemotionlistener alistener); void addwindowlistener(in nsidomwindow awindow); native code only! void removelistener(in nsidevicemotionlistener alistener); void removewindowlistener(in nsidomwindow awindow); native code only! methods addlistener() when called, the accelerometer support implementation must begin to notify the specified nsidevicemotionlistener by calling its nsidevicemotionlistener.onaccelerationchange() method as appropriate to share updated acceleration data. vo...
...notify the specified nsidevicemotionlistener by calling its nsidevicemotionlistener.onaccelerationchange() method as appropriate to share updated acceleration data. void addlistener( in nsidevicemotionlistener alistener ); parameters alistener the nsidevicemotionlistener object whose nsidevicemotionlistener.onaccelerationchange() method should be called with updated acceleration data. native code only!addwindowlistener sets the nsiaccelerometer as the source for mozorientation events on the specified dom window. void addwindowlistener( in nsidomwindow awindow ); parameters awindow the dom window that the accelerometer should begin sending mozorientation events to. removelistener() tells the accelerometer to stop sending updates to the specified nsidevicemotionlistener. void removelis...
...w awindow ); parameters awindow the dom window that the accelerometer should begin sending mozorientation events to. removelistener() tells the accelerometer to stop sending updates to the specified nsidevicemotionlistener. void removelistener( in nsidevicemotionlistener alistener ); parameters alistener the nsidevicemotionlistener object to which no further updates should be sent. native code only!removewindowlistener removes the nsiaccelerometer as the source for mozorientation events on the specified dom window. void removewindowlistener( in nsidomwindow awindow ); parameters awindow the dom window that the accelerometer should stop sending mozorientation events to. see also mozorientation nsidomorientationevent nsidevicemotiondata nsidevicemotionlistener ...
nsIHttpChannel
equest can be configured via nsiuploadchannel. however, after setting the upload data, it may be necessary to set the request method explicitly. the documentation for nsiuploadchannel has further details. exceptions thrown ns_error_in_progress if set after the channel has been opened. ...
...read only. ...
...read only. exceptions thrown ns_error_not_available if called before the response has been received (before onstartrequest()). ...
nsIInputStream
ion thread. for this reason, it is generally the case that a blocking input stream should be implemented using thread-safe addref and release. method overview unsigned long available();deprecated since gecko 17.0 unsigned long long available(); void close(); boolean isnonblocking(); unsigned long read(in charptr abuf, in unsigned long acount); native code only! unsigned long readsegments(in nswritesegmentfun awriter, in voidptr aclosure, in unsigned long acount); native code only! methods available() determine number of bytes available in the stream. in addition to the number of bytes available in the stream, this method also informs the caller of the current status of the stream. a stream that is closed will throw an exception ...
...closed normally. close() close the stream. this method causes subsequent calls to read() and readsegments() to return 0 bytes read to indicate end-of-file. note: the close method may be called more than once, but subsequent calls are ignored. void close(); parameters none. isnonblocking() boolean isnonblocking(); parameters none. return value true if stream is non-blocking. native code only!read this method copies data from the stream into a buffer. unsigned long read( in charptr abuf, in unsigned long acount ); parameters abuf the buffer into which the data from the stream is copied. acount the size of the buffer, or the maximum number of bytes to copy from the stream. return value this method returns the number of bytes copied from the stream (may be less tha...
... value this method returns the number of bytes copied from the stream (may be less than acount). it returns 0 to indicate end-of-file. exceptions thrown <other-error> on failure. ns_base_stream_would_block indicates that reading from the input stream would block the calling thread for indeterminate amount of time. this exception may only be thrown if isnonblocking() returns true. native code only!readsegments this method provides direct access to the stream's internal buffer. note: a nsiinputstream is not required to implement this method. in some contexts, readsegments may be guaranteed to be implemented, but in general it is not. this method serves as an optimization. unsigned long readsegments( in nswritesegmentfun awriter, in voidptr aclosure, in unsigned long acount ); ...
nsIOutputStream
addref and release. method overview void close(); void flush(); boolean isnonblocking(); unsigned long write(in string abuf, in unsigned long acount); unsigned long writefrom(in nsiinputstream afromstream, in unsigned long acount); unsigned long writesegments(in nsreadsegmentfun areader, in voidptr aclosure, in unsigned long acount); native code only! methods close() close the stream. forces the output stream to flush() any buffered data. note: this method may be called more than once, but subsequent calls are ignored. void close(); parameters none. exceptions thrown ns_base_stream_would_block indicates that closing the output stream would block the calling thread for an indeterminate amount of time. this exception may...
... data without blocking. boolean isnonblocking(); parameters none. return value true if stream is non-blocking. exceptions thrown ns_base_stream_would_block a non-blocking stream may throw this exception when written to if space for the data is not immediately available. write() this method copies data from a buffer into the stream. note: though this method is scriptable, javascript code must only pass an ascii character string as the abuf parameter. c++ code may however pass any arbitrary binary data, including data with embedded null bytes. unsigned long write( in string abuf, in unsigned long acount ); parameters abuf the buffer containing the data to be written. acount the size of the buffer, or the maximum number of bytes to copy from the buffer. return value ...
...eption may only be thrown if isnonblocking() returns true. ns_error_not_implemented indicates that the stream does not implement this method. typically, output streams that do not have an internal buffer will not implement this method since such an implementation would require an intermediate buffer unless afromstream supported nsiinputstream.readsegments(), but that is not guaranteed. native code only!writesegments low-level write method that has access to the stream's underlying buffer. the reader function may be called multiple times for segmented buffers. this method is expected to keep calling the reader until either there is nothing left to write or the reader returns an error. this method should not call the reader with zero bytes to provide. note: a nsioutputstream is not require...
nsIPromptService
inherits from: nsisupports last changed in gecko 1.7.5 you can define access keys (or keyboard shortcuts) for buttons by including an ampersand ("&") in front of the character that should be the access key for that button. if you need to include an ampersand in the button's text, use two of them, like this: "&&". ...
...button_title_cancel * button_pos_1) std_yes_no_buttons 1027 selects the standard set of yes/no buttons. (button_title_yes *button_pos_0) +(button_title_no * button_pos_1) methods alert() alert shows an alert dialog with an ok button. it works the same way as window.alert, but accepts a title for the dialog. you should use this method instead of window.alert in chrome code. void alert( in nsidomwindow aparent, in wstring adialogtitle, in wstring atext ); parameters aparent the parent window for the dialog, or null, in which case the parent window will be nsiwindowwatcher.activewindow. adialogtitle text to appear in the title of the dialog. atext text to appear in the body of the dialog. see also the alert_example. alertcheck() shows...
... length of the aselectlist array parameter. aselectlist list of strings to display. aoutselection contains the index of the selected item in the list when this method returns true. if you call this method from javascript, this argument is wrapped in an object with an attribute named 'value' which holds the selected index. return value true for ok, false for cancel example code alert example alert displays a simple dialog. var prompts = components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice); prompts.alert(null, "title of this dialog", "hello! you have now been alerted."); alertcheck example alertcheck dispays a dialog with a checkbox. var prompts = components.classes["@mozilla.org/em...
nsIProtocolHandler
lot of control over, such as an email reader. uri_loadable_by_anyone 1<<6 anyone can load the uris for this protocol; for example, any web site can load a uri for this protocol. web-safe protocols such as http should use this flag. uri_dangerous_to_load 1<<7 uris using this protocol are unsafe if loaded by untrusted web content and may only be loaded by privileged code (for example, code that has the system principal). various internal protocols use this flag. uri_is_ui_resource 1<<8 the uris for this protocol refer to resources that are part of the application's user interface. there are cases in which such resources may be made accessible to untrusted content such as web pages, so this is less restrictive than uri_dangerous_to_load but more re...
...ns should only be allowed if those origins should have access to the local file system. it's up to the application to decide what origins should have such access. protocols like file that point to local data should set this flag. uri_loadable_by_subsumers 1<<14 the uris for this protocol can be loaded only by callers with a principal that subsumes this uri. for example, privileged code and websites that are same origin as this uri. uri_non_persistable 1<<10 loading channels from this protocol has side-effects that make it unsuitable for saving to a local file. uri_does_not_return_data 1<<11 channels using this protocol never call ondataavailable() on the listener passed to asyncopen(), and therefore do not return any usable data. ...
...icating with, for example, the origin server of the uri string. (many servers do not support utf-8 iris at the present time, so we must be careful about tracking the native charset of the origin server.) nsiuri newuri( in autf8string aspec, in string aorigincharset, in nsiuri abaseuri ); parameters aspec the uri string in utf-8 encoding. depending on the protocol's implementation, unicode character sequences may or may not be %xx escaped. aorigincharset the character set of the document from which this uri string originated. this corresponds to the character set that should be used when communicating this uri to an origin server. if this is null, then utf-8 encoding is assumed and no character transformation is not performed. abaseuri if null, aspec must specify an absolute ur...
nsIPushSubscription
inherits from: nsisupports last changed in gecko 46.0 (firefox 46.0 / thunderbird 46.0 / seamonkey 2.43) each subscription is associated with a unique url generated by the push service. sending a post request to this url routes the message to the instance of firefox that created the subscription. a subscription also has a public key and secret; these are used to encrypt message payloads. this interface resembles pushsubscription from the push api. ...
...bscription) { let request = cc["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(ci.nsixmlhttprequest); request.open("post", "https://example.com/register-for-push", true); request.addeventlistener("error", () => { cu.reporterror("error sending subscription to server"); }); request.send(json.stringify({ endpoint: subscription.endpoint, // base64-encode the key and authentication secret. key: string.fromcharcode.apply(null, btoa(subscription.getkey("p256dh"))), secret: string.fromcharcode.apply(null, btoa(subscription.getkey("auth"))), })); } pushservice.subscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("erro...
...ecret. ...
nsIRequestObserver
irequestobserver.idlscriptable this interface is used by various streams (such as nsichannel ) to indicate the start and end of a request. inherits from: nsisupports last changed in gecko 1.0 method overview void onstartrequest(in nsirequest arequest, in nsisupports acontext); void onstoprequest(in nsirequest arequest, in nsisupports acontext, in nsresult astatuscode); methods onstartrequest() called to signify the beginning of an asynchronous request. note: an exception thrown from onstartrequest has the side-effect of causing the request to be canceled. void onstartrequest( in nsirequest arequest, in nsisupports acontext ); parameters arequest request being observed. acontext user defined context. onstoprequest() ...
...); parameters arequest request being observed. acontext user defined context. onstoprequest() called to signify the end of an asynchronous request. this call is always preceded by a call to onstartrequest(). ...
...lled to signify the end of an asynchronous request. this call is always preceded by a call to onstartrequest(). note: an exception thrown from onstoprequest is generally ignored. ...
nsISOCKSSocketInfo
netwerk/socket/nsisockssocketinfo.idlscriptable this interface provides information about a socks socket. ...
... netwerk/socket/nsisockssocketinfo.idlscriptable this interface provides information about a socks socket. ...
...is interface provides information about a socks socket. ...
nsIScriptError
r providing that line. you may pass null if you are lazy; that will prevent showing the source line in javascript console. linenumber the number of the line where the error occurred. columnnumber the column number where the error occurred. this is used to draw an arrow pointing to the problem character. flags one of flags listed in flag constants. category a string indicating what kind of code caused the message. there are quite a few category strings and they don't seem to be listed in a single place. see categories for a partial list. initwithwindowid() initializes the nsiscripterror object with the given inner window's id. note: prior to gecko 12.0, this method was provided by the nsiscripterror2 interface, which has now been merged into this one. void initwithwindowid( in ...
...r providing that line. you may pass null if you are lazy; that will prevent showing the source line in javascript console. linenumber the number of the line where the error occurred. columnnumber the column number where the error occurred. this is used to draw an arrow pointing to the problem character. flags one of the script error flag constants category a string indicating what kind of code caused the message. there are quite a few category strings and they aren't listed in a single place, so you may need to search the firefox code to find the one you want. see categories for a partial list. innerwindowid the id of the inner window associated with the error. tostring() outputs a string representing the error message described by the object. autf8string tostring(); parameters...
...ts.classes["@mozilla.org/scripterror;1"] .createinstance(components.interfaces.nsiscripterror); scripterror.init(amessage, asourcename, asourceline, alinenumber, acolumnnumber, aflags, acategory); consoleservice.logmessage(scripterror); } categories there are a lot of categories, and they're not all maintained in a single list anywhere in the code. this is an attempt to group them together for reference. note that these are strings. if you want to log an error at chrome level you should set a category from the first section (leaving it empty might log it as content error). as addon author i would recommend using "chrome javascript" for logging exceptions caused by addon code. categories the web console does not display "xpconnect javas...
nsIScriptableInputStream
in nsiinputstream ainputstream ); parameters ainputstream the nsiinputstream to be wrapped. read() read data from the stream. warning: if the data contains a null byte, then this method will return a truncated string. note: it is also important to consider how a language bindings may interpret the string data type. in particular, some bindings may convert the byte values into unicode code points, by assuming the byte values are encoded as iso-latin-1. this is the case for the javascript bindings. string read( in unsigned long acount ); parameters acount the maximum number of bytes to read from the stream. return value the data read as a string, which will be an empty string if the stream is at eof. exceptions thrown ns_error_not_initialized if init() was...
...block if reading from the input stream would block the calling thread (non-blocking mode only). remarks this interface provides javascript with a way to read ascii text from a nsiinputstream. however, it does not address the problem of reading arbitrary binary data from a stream. for binary input see nsibinaryinputstream. note: starting in gecko 2.0, you can use the netutils.jsm javascript code module and its readinputstreamtostring() method to read arbitrary binary data into a javascript string. the nsscriptableinputstream component implements this interface. this interface was frozen for gecko 1.2. from gecko 2.0 interfaces are no longer frozen. examples list contents of xpi and read file contents this example here uses the read function. it takes a input stream from the zip reader a...
.... it takes a input stream from the zip reader and outputs the text in it. full example using the zip interfaces is seen here: list contents of xpi and read file contents. remember: the nsiscriptableinputstream has a contract where `init` should only be called once, and should always be closed. excerpt of the stream for this stream article is here, this is only an excerpt so cannot copy paste this code into scratchpad. var {classes: cc, interfaces: ci, results: cr, constructor: cc, utils: cu } = components; var scriptableinputstream = cc("@mozilla.org/scriptableinputstream;1", "nsiscriptableinputstream", "init"); let entry = this.getentry(name); let stream = new scriptableinputstream(this.getinputstream(name)); try { // use readbytes to get binary data, read to read a (null-...
nsIServerSocket
etwork/server-socket;1. to create an instance, use: var serversocket = components.classes["@mozilla.org/network/server-socket;1"] .createinstance(components.interfaces.nsiserversocket); method overview void init(in long aport, in boolean aloopbackonly, in long abacklog); void initwithaddress([const] in prnetaddrptr aaddr, in long abacklog);native code only! void close(); void asynclisten(in nsiserversocketlistener alistener); prnetaddr getaddress();native code only! attributes attribute type description port long returns the port of this server socket. read only. methods asynclisten() this method puts the server socket in the listening state. it will asynchronously liste...
... alistener the listener to be notified when client connections are accepted. close() this method closes a server socket. this does not affect already connected client sockets (i.e., the nsisockettransport instances created from this server socket). this will cause the onstoplistening event to asynchronously fire with a status of ns_binding_aborted. void close(); parameters none. native code only!getaddress returns the address to which this server socket is bound. since a server socket may be bound to multiple network devices, this address may not necessarily be specific to a single network device. in the case of an ip socket, the ip address field would be zeroed out to indicate a server socket bound to all network devices. therefore, this method cannot be used to determine the ip ...
...l only respond to connections on the local loopback interface. otherwise, it will accept connections from any interface. to specify a particular network interface, use initwithaddress(). abacklog the maximum length to which the queue of pending connections may grow. this parameter may be silently limited by the operating system. pass -1 to use the default value. the default value is 5. native code only!initwithaddress this method initializes a server socket and binds it to a particular local address (and hence a particular local network interface). void initwithaddress( [const] in prnetaddrptr aaddr, in long abacklog ); parameters aaddr the address to which this server socket should be bound. abacklog the maximum length the queue of pending connections may grow to. this param...
nsISmsRequestManager
arequestid, in long alistid, in nsidommozsmsmessage amessage ); parameters arequestid a number representing the id of the request. alistid a number representing the id of the list. amessage an smsmessage. notifygetsmsfailed() void notifygetsmsfailed( in long arequestid, in long aerror ); parameters arequestid a number representing the id of the request. aerror a number with an error code. see constants. notifygotnextmessage() void notifygotnextmessage( in long arequestid, in nsidommozsmsmessage amessage ); parameters arequestid a number representing the id of the request. amessage an smsmessage. notifygotsms() void notifygotsms( in long arequestid, in nsidommozsmsmessage amessage ); parameters arequestid a number representing the id of the request. amessage an smsme...
...estid a number representing the id of the request. aread a boolean indicating whether a message is read or unread. notifymarkmessagereadfailed() requires gecko 15.0(firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) void notifymarkmessagereadfailed( in long arequestid in long aerror ); parameters arequestid a number representing the id of the request. aerror a number with an error code. see constants. notifynomessageinlist() void notifynomessageinlist( in long arequestid ); parameters arequestid a number representing the id of the request. notifyreadmessagelistfailed() void notifyreadmessagelistfailed( in long arequestid, in long aerror ); parameters arequestid a number representing the id of the request. aerror a number with an error code. see constants. notifysms...
...sdeleted() void notifysmsdeleted( in long arequestid, in bool adeleted ); parameters arequestid a number representing the id of the request. adeleted a boolean indictating whether the sms is deleted. notifysmsdeletefailed() void notifysmsdeletefailed( in long arequestid, in long aerror ); parameters arequestid a number representing the id of the request. aerror a number with an error code. see constants. notifysmssendfailed() void notifysmssendfailed( in long arequestid, in long aerror ); parameters arequestid a number representing the id of the request. aerror a number with an error code. see constants. notifysmssent() void notifysmssent( in long arequestid, in nsidommozsmsmessage amessage ); parameters arequestid a number representing the id of the request. amessag...
nsITransferable
requestingnode nsidomnode the source ...
...converter an nsiformatconverter instance which implements the code needed to convert data into and out of the transferable given the supported flavors. isprivatedata boolean although this is not a read-only attribute, you should generally avoid changing it, since doing so may cause it not to actually reflect the status of the context in which the transferable was created. native code only! requestingnode nsidomnode the source dom node this transferable was created from. native code only! note: currently, this can only be used on windows (in order to support network principal information in drag operations). constants kflavorhasdataprovider (that title needs to be better) constant value description kfla...
... constants kflavorhasdataprovider (that title needs to be better) constant value description kflavorhasdataprovider 0 a description is needed here. common mime types some of these need better descriptions, especially the mozilla-specific ones. constant value description ktextmime text/plain plain text. kunicodemime text/unicode unicode text. kmoztextinternal text/x-moz-text-internal text data that isn't meant to be used by non-mozilla code. khtmlmime text/html html. kaolmailmime aolmail aol mail. need details. kpngimagemime image/png png image. kjpegimagemime image/jpeg jpeg image. kjpgimagemime image/jpg jpe...
nsIWindowWatcher
property as the active window changes. this component should not keep a (xpcom) reference to any windows; the implementation will claim no ownership. windows must notify this component when they are created or destroyed, so only a weak reference is kept. note that there is no interface for such notifications (not a public one, anyway). this is taken care of both in mozilla and by common embedding code. embedding clients need do nothing special about that requirement. this component must be initialized at application startup by calling setwindowcreator(). method overview nsiwebbrowserchrome getchromeforwindow(in nsidomwindow awindow); nsiauthprompt getnewauthprompter(in nsidomwindow aparent); nsiprompt getnewprompter(in nsidomwindow aparent); nsidomwindow ...
...e arguments (but not recursively!). can be null, in which case the window.arguments property will not be set on the new window. as of gecko 1.9 alpha 1, can also be an nsiarray instead. return value an nsidomwindow for the opened window. ...
...) clients of this service can register themselves to be notified when a window is opened or closed (added to or removed from this service). this method adds an nsiobserver to the list of objects to be notified. void registernotification( in nsiobserver aobserver ); parameters note: be careful about generating open/close window events inside nsiobserver.observe(). ...
nsIXMLHttpRequest
tandard properties" the property of channel was read-only. when using the xpcom interface, as seen below in example 2, we can get access to this. the most obvious benefit is that we can set nsirequest - constants in the xhr.channel.loadflags. for instance, as done in example 2, the flag of load_anonymous is added, this strips all user data (cookies, tokens, etc). using event handlers from native code (not sure if it's up-to-date) from native code, the way to set up onload and onerror handlers is a bit different. here is a comment from johnny stenback <jst@netscape.com>: the mozilla implementation of nsixmlhttprequest implements the interface nsidomeventtarget and that's how you're supported to add event listeners. try something like this: nscomptr<nsidomeventtarget> target(do_queryinterfac...
...request, but if you're coding in c++ you should avoid using those. though actually, if you use addeventlistener from c++ weird things will happen too, since the result will depend on what js happens to be on the stack when you do it.... conclusion: do not use event listeners on xmlhttprequest from c++, unless you're aware of all the security implications. and then think twice about it. ...
...n c++ you should avoid using those. though actually, if you use addeventlistener from c++ weird things will happen too, since the result will depend on what js happens to be on the stack when you do it.... conclusion: do not use event listeners on xmlhttprequest from c++, unless you're aware of all the security implications. and then think twice about it. ...
nsIXPCException
ects are the preferred types of exceptions when implementing xpcom interfaces in javascript. ...
...javascript. ...
...ion ainner); xpcexjsval stealjsval(); native code only! void stowjsval(in xpcexjscontextptr cx, in xpcexjsval val); native code only! methods initialize() void initialize( in string amessage, in nsresult aresult, in string aname, in nsistackframe alocation, in nsisupports adata, in nsiexception ainner ); parameters amessage aresult aname alocation adata ainner native code only!stealjsval xpcexjsval stealjsval(); parameters none. return value native code only!stowjsval void stowjsval( in xpcexjscontextptr cx, in xpcexjsval val ); parameters cx val remarks components.exception is a javascript constructor to create nsixpcexception objects. the call signature of the constructor is: components.exception(message, result, stack, data, inner) all parameters ...
nsIXmlRpcFault
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. extensions/xml-rpc/idl/nsixmlrpcclient.idlscriptable an xml-rpc exception. xml-rpc server fault codes are returned wrapped in this; access it using nsixpconnect.getpendingexception->data. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void init(in print32 faultcode, in string faultsring); string tostring(); attributes attribute type description faultcode print32 read only. faultstring string read only. methods init() void getdata( in print32 fa...
...om: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void init(in print32 faultcode, in string faultsring); string tostring(); attributes attribute type description faultcode print32 read only. faultstring string read only. ...
.../ thunderbird 1.5 / seamonkey 1.0) method overview void init(in print32 faultcode, in string faultsring); string tostring(); attributes attribute type description faultcode print32 read only. faultstring string read only. ...
NS_StringContainerInit
inerinit function initializes a nsstringcontainer instance for use as a nsastring. this is a low-level api. #include "nsstringapi.h" nsresult ns_stringcontainerinit( nsstringcontainer& astring ); parameters astring [in] a nsstringcontainer instance to be initialized. return values the ns_stringcontainerinit function returns ns_ok if successful. otherwise, it returns an error code. ...
...on returns ns_ok if successful. otherwise, it returns an error code. remarks the nsstringcontainer structure has unspecified size and layout. its members may not be accessed directly. after a nsstringcontainer object has been initialized, it may be used as an ordinary nsastring object. the internal buffer allocated by a nsstringcontainer is always null-terminated. with ns_stringcontainerinit, the coder is required to call ns_stringcontainerfinish when done with the nsstringcontainer object. therefore, it is generally better to use nsembedstring, to instantiate a nsastring object, since it automatically releases allocated memory when the object goes out of scope. ...
... // be sure to call this function to release any memory owned by |str| when done. ...
nsIAbCard/Thunderbird3
properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible. properties currently supported on the card: names: firstname, lastname phoneticfirstname, phoneticlastname displayname, nickname spousename, familyname primaryemail, secondemail home contact: homeaddress, homeaddress2, homecity, homestate, homezipcode, homecountry homephone, homephonetype work contact. same as home, but with `work' instead of `home' other contact: faxnumber, faxnumbertype pagernumber, pagernumbertype cellularnumber, cellularnumbertype jobtitle, department, company _aimscreenname dates: anniversaryyear, anniversarymonth, anniversaryday birthyear, birthmonth, birthday webpage1 (wo...
...tpropertyasuint32(in string name); [noscript] boolean getpropertyasbool(in string name); returns a property for the given name. these functions convert values in the same manner as the default implementation of nsivariant. of particular note is that boolean variables are converted to integers as in c/c++ (true is a non-zero value), so that false will be converted to a string of 0 and not false<code>. these functions are marked <code>[noscript] since xpcconnect performs automatic type conversion on nsivariant such that they are not needed for scripts, only for c++ callers. parameters name the case-sensitive name of the property to get. return value the value of the attribute asked for. exceptions thrown ns_error_not_available<tt> if the named property does not exist. <tt>n...
... srccard the source card to copy values from. equals() returns true if this card is equal to the other card. the default implementation defines equal as this card pointing to the same object as acard. another implementation defines it as equality of properties and values. the exact nature of equality is still undefined, and actual results may not match theoretical results. most notably, the code a.equals(b) == b.equals(a) might not return true. in particular, calling equals on cards from different address books may return inaccurate results. boolean equals(in nsiabcard card) parameters card the card you are comparing with. return value true if the cards are the same. generatephoneticname() generate a phonetic name from the card, using the firstname and lastname values. as...
XPCOM reference
this reference describes the interfaces and functions provided by the xpcom library. in addition, it details the various helper classes and functions, as well as the components, provided by the xpcom glue library. the contents herein are oriented primarily toward extension developers and people embedding xpcom in other projects. if you're working on a module in the mozilla codebase that's compiled with the mozilla_internal_api flag set, some of these apis -- the string functions and classes in particular -- are not the ones you should be using. see the xpcom internal string guide for documentation of the internal string api used within the mozilla codebase. core xpcom functionsxpcom provides a number of global functions which are used to initialize and shut down the xpcom libr...
...ore constants. for example, to request the 'show all threads' view use the constant:nsstaticmoduleinfothis data structure is used by ns_initxpcom3 to specify static xpcom modules.standard xpcom componentsthere are a number of components provided in the standard implementation of xpcom; these are as follows.xpcom glue classesthese "glue" classes are provided to make it easier to use xpcom from c++ code.xpcom interface referencethis is a reference to the xpcom interfaces provided by the mozilla platform.xpcom interface reference by groupingthis page lists the current (as of dec. 01, 2010) list of mozilla interfaces as listed on the xpcom interface reference page where that page lists items by alphabetical sorting, this page attempts to group them by function. grouping and category names were mad...
...xpcom interface from the table below.xpcom string functionsxpcom provides these low-level string functions to let you work with strings; however, it's often better to use one of the string classes rather than directly using these functions. many xpcom pages return an nsresult. prior to gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16), this was an integer that simply returned an error code. it is now a strongly typed enum when xpcom is built using a c++11 compiler. this causes compile-time errors to occur when improper values are returned as nsresult values, thereby making it easier to catch many bugs. ...
Troubleshooting XPCOM components registration
nd you declared the binary component in your chrome.manifest. see xpcom changes in gecko 2.0 parsing errors in javascript components the most common reason for components written in javascript to fail is that there are parsing errors. these parsing errors should show up in the error console if chrome errors are enabled. to learn more about enabling chrome errors, see "how can i see errors in my code" in the extension faqs. registration failure if the module is loading correctly but doesn't register its components, try adding calls to components.utils.reporterror("debug me!"); in nsgetmodule() and other functions to try and find any errors. general hints you may need to delete compreg.dat in your profile folder to force re-registration. this should not occur if you uninstalled/installed...
...ner, etc.), use the artifacts from that compilation to build your component. if you are testing a build from your linux distribution (or other vendor-supplied build), look for -dev packages from them. remember to check that the directory the component is in is named correctly i.e. $profile/extensions/$plugindirectory/components! double check your guids in your install.rdf with your sourcecode, and then check them again. windows-specific hints use dependency walker to check that your dependent libraries are loaded correctly. in dependency walker, open the options menu and select configure module search order.... in the bottom right corner of the new dialog, click browse... and select the directory firefox.exe (or equivalent) is in. in the bottom left corner, clic...
...h msvc 8.0 (2005) and are attempting to use it on a windows xp machine or later, it will need a manifest embedded to find the runtime. please refer to msdn for details. if you have the option, you can manually copy these dependencies to firefox.exe's directory, to windows\system32, or to any directory is the system's path. a google groups thread on the matter is located here. the dllmain code that msvc 8 (and probably earlier versions too) generates for you doesn't need to be there, you can remove it. you may be able build your component using use_static_libs=1 in order to remove c runtime library dependencies. linux-specific hints check if you have missing dependent libraries: from your firefox (/xulrunner) install directory, run "./run-mozilla.sh `which ldd` -r pa...
Frequently Asked Questions
ropriate answer, there. if you're looking here just to learn about nscomptrs, you'll get a better introduction in the getting started guide. the faq is divided into sections to help you find what you're looking for faster. in most cases, the answer will just refer back into the reference manual, above. no need to explain things twice :-). buildtime errors the build just broke. it's not in your code, or it's not on your platform, but there's an nscomptr on the line where the error is and you're suspicious. you're looking in the right place. comparing an nscomptr to a raw xpcom interface pointer declaring an nscomptr to a forward-declared class not linking to xpcom not including nscomptr.h different settings of nscap_feature_debug_ptr_types runtime errors ns_assertion "queryinterface n...
...n nscomptr leak (for a debug test)? call a getter that uses a raw xpcom interface pointer as an `in/out' parameter? call a getter that fills in an nsifoo*& parameter? call a getter that doesn't addref its result? any xpcom function that returns an interface pointer, i.e., a `getter', must have already addrefed that pointer. if it didn't, you should probably report it as a bug. no matter which code pattern you use to solve this problem, you should comment it, e.g., // warning: this getter doesn't addref() its result. if the getter returns the new pointer as its function result, no worries, general does nscomptr bloat the code? are nscomptrs fast? can i use them in tight loops? bibliography web resources nscomptr.h, and nscomptr.cpp are the source to nscomptr. you can examine the sou...
... some com ownership guidelines. interface pointers considered harmful by don box originally appeared in the september 1995 issue of "the c++ report". ...
XPCOM category image-sniffing-services
note: this category was removed. ...
...note: this category was removed. ...
...note: this category was removed. ...
nsCOMPtr versus RefPtr
(although, confusingly, debug builds don't work this way). this design saves some space in the binary (or at least it used to). since nscomptr stores the pointer as an nsisupports*, it must be possible to unambiguously cast from t* to nsisupports*. ...
...(although, confusingly, debug builds don't work this way). this design saves some space in the binary (or at least it used to). since nscomptr stores the pointer as an nsisupports*, it must be possible to unambiguously cast from t* to nsisupports*. ...
...many concrete classes inherit from nsisupports in more than one way, so they cannot be unambiguously cast to nsisupports*. thus, these concrete classes cannot be used with nscomptr. while is possible to use nscomptr<t> on concrete classes t that only singly inherit from nsisupports, it is best to avoid doing so. in the future, more base classes might be added to t that would then cause unrelated code to break, which would be very confusing. hence, the interface versus concrete class rule of thumb: interfaces will never multiply inherit from nsisupports, so they can always use be used with nscomptr without fear of breaking in the future. concrete classes should only be used with refptr. nscomptr<t> also requires that you can queryinterface to type t. it does this so that it can assert that mr...
The Valgrind Test Job
on linux. it also works on mac, though sometimes not as well. building you need a valgrind-enabled build of firefox. add the following lines to your mozconfig file. ac_add_options --enable-valgrind ac_add_options --disable-jemalloc running to run the valgrind test job locally, run the following command. mach valgrind-test see also the general instructions for using valgrind with mozilla code. understanding errors for each problem that valgrind finds, it emits a message describing the problem, along with a stack trace indicating where the problem occurs. it also prints a suppression, which is a sequence of text that can be put in a suppression file (and specified via valgrind's --suppressions option) if you want valgrind to ignore such errors in future runs. for example, we have a...
...its a message describing the problem, along with a stack trace indicating where the problem occurs. it also prints a suppression, which is a sequence of text that can be put in a suppression file (and specified via valgrind's --suppressions option) if you want valgrind to ignore such errors in future runs. ...
... julian seward can also help with valgrind issues. alternatively, bugs relating to the test job can be filed in the "testing" product, under the "general" component. ...
nsIMsgCloudFileProvider
he remaining storage space available for this account in bytes. if this value is not known, returns -1. filespaceused long long readonly: the total amount of space used by this account. if this value is not known, returns -1. lasterror acstring readonly: the last error message received from the server. constants the following constants are used for the status codes passed to the onstoprequest functions of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no active network connection. autherr 0x8055001e returned when authorizing has failed. uploaderr 0x8055311a returned when ...
...orage being used. void refreshuserinfo(in boolean awithui, in nsirequestobserver acallback); parameters awithui whether or not the provider should prompt the user for credentails in the event that the stored credentials have gone stale. if awithui is false, and the credentials are stale, the onstoprequest of the acallback nsirequestlistener will get the autherr status code passed to it. acallback the nsirequestobserver for monitoring the start and stop states of the refresh operation. deletefile() attempts to delete a file that had previously been uploaded using this instance. void deletefile(in nsilocalfile afile, in nsirequestobserver acallback); parameters afile the file that was previously uploaded using this nsimsgcloudfileprovider ...
...on. createexistingaccount() for an init'ed nsimsgcloudfileprovider, attempts to communicate with the service provider in order to get the proper credentials for starting uploads. void createexistingaccount(in nsirequestobserver acallback); parameters acallback the nsirequestobserver for monitoring the start and stop states of the creation operation. providerurlforerror() for an error code, for example uploadwouldexceedquota, a provider might have a url with information on how to deal with that error. this function translates those error codes into those urls. if the provider has no appropriate url for the error, the method returns the empty string. void providerurlforerror(in unsigned long aerror); parameters aerror an error code to be translated into a url. ...
MailNews Protocols
...
... ...
... ...
Adding items to the Folder Pane
consults the map-generator for the current mode, and that generator returns the necessary data for the folder pane's display. this data is returned in the form of an array of folder-tree-items. listening for folder pane rebuilds every time the folder pane rebuilds, it fires a "maprebuild" event, which is the ideal opportunity for extensions to step in and modify the display data. ...
...-tree-items to the folder pane's _rowmap at the appropriate time. thus, our _insert function becomes _insert: function gne__insert() { // only insert our nodes into the "all" mode if (gfoldertreeview.mode != "all") return; gfoldertreeview._rowmap.push(containerrow); }, right now, clicking on these additional items has no effect. however, the complete example file includes code to display the number selected in thunderbird's main viewing pane, when such a number is selected in the folder pane. a note about the initial rebuild when thunderbird first starts up, the folder pane does an initial rebuild to get the first data it should display. unfortunately, this rebuild will occur before an extension's "load" event fires. thus, extensions may need to do manual insertions ...
...mber is selected in the folder pane. a note about the initial rebuild when thunderbird first starts up, the folder pane does an initial rebuild to get the first data it should display. unfortunately, this rebuild will occur before an extension's "load" event fires. thus, extensions may need to do manual insertions when this load event fires, if they want to add items to the initial display. add_code.js also includes code to accomplish this result. ...
Get Thunderbird version
on thunderbird version 3.0b3pre and later, you can use the following snippet to get the thunderbird version. ...
...thunderbird version 3.0b3pre and later, you can use the following snippet to get the thunderbird version. ...
...components.interfaces.nsixulappinfo).version; else version = components.classes["@mozilla.org/preferences-service; 1"].getservice(components.interfaces.nsiprefbranch).getcharpref ("app.version"); var versionchecker = components.classes["@mozilla.org/xpcom/version- comparator;1"].getservice(components.interfaces.nsiversioncomparator); if ( versionchecker.compare( version, "3.0b3" ) >= 0 ) // code for >= 3.0b3 else // code for < 3.0b3 ...
Using tab-modal prompts
oduces tab modal prompts, which only block the tab with which they're associated. only the window.alert() method gets this by default; you get this by default. tab-modal alert. disabling tab-modal prompts you can disable tab-modal prompts and get back window-modal prompts by setting the prompts.tab_modal.enabled preference to false. ...
... gets this by default; you get this by default. tab-modal alert. disabling tab-modal prompts you can disable tab-modal prompts and get back window-modal prompts by setting the prompts.tab_modal.enabled preference to false. using tab-modal prompts from chrome code currently, nsiprompt defaults to using window-modal prompts. ...
...allowtabmodal", true); var promptargs = ["devmo alert", "omg! an alert!"]; prompt.alert.apply(null, promptargs); nsiprompt will automatically fall back to window-modal prompts when necessary (such as in situations in which tab-modal prompts aren't supported, or for prompts displayed outside the context of a tab).le to use other forms of the prompts of nsipromptservice interface see the example code. then apply it, like in the example below, here we apply the prompt with a checkbox: var window = gbrowser.contentwindow; var promptfact = components.classes['@mozilla.org/prompter;1'].getservice(components.interfaces.nsipromptfactory); var prompt = promptfact.getprompt(window, components.interfaces.nsiprompt); var promptbag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2);...
Break on DOM mutation - Firefox Developer Tools
you set a dom mutation breakpoint in the page inspector. navigate to the dom node in which you are interested and use the context menu to set the breakpoint. there are three choices: subtree modification execution pauses if any of the elementʼs descendant nodes are modified. that means, the script execution is stopped whenever a child node or descendant node deeper in the dom structure is added to or removed from the element the option is set on. examples for when this breakpoint is triggered are calling node.appendchild() and node.removechild(), calling childnode.remove() or setting element.innerhtml on one of the subnodes. ...
...n is removed. examples for when this breakpoint is triggered are calling element.remove() or node.removechild() on its parent node. once you set the breakpoint, go to the debugger. you can see the breakpoint listed in the right-most panel under dom mutation breakpoints. click on the icon following the node name to go back to the page inspector with the node selected. when you execute the code, the debugger will pause execution when the dom mutation occurs. in the following example, the selected node (the unordered list) is modified by adding a new child node. the panel on the right shows that execution is "paused on dom mutation" and you, as with any other breakpoint, you can see the call stack and view any watch expressions you may have set up. inline variable preview new in fir...
... the selected node (the unordered list) is modified by adding a new child node. the panel on the right shows that execution is "paused on dom mutation" and you, as with any other breakpoint, you can see the call stack and view any watch expressions you may have set up. inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
Set an XHR breakpoint - Firefox Developer Tools
an xhr (xmlhttprequest) breakpoint breaks code execution when an xhr request is dispatched so that you can examine the current state of the program. you can break on all requests or on those that include a specific url. to turn on the feature: open the debugger click on "pause on any url" which acts as a wild card, causing the code to pause on any call, or, click the plus sign next to the xhr breakpoints header, enter the url in which you are interested, and press enter. note: if you enter a key word instead of a url, code execution will pause on any call to a url that contains that keyword. ...
...o turn on the feature: open the debugger click on "pause on any url" which acts as a wild card, causing the code to pause on any call, or, click the plus sign next to the xhr breakpoints header, enter the url in which you are interested, and press enter. note: if you enter a key word instead of a url, code execution will pause on any call to a url that contains that keyword. when your code breaks on an xhr request, the righthand pane will have two additional sections: call stack the list of functions that were executed in order ot get to the currently executing code. click on an item in the call stack to jump to the associated line in the code display. scopes a list of the values that are in scope in the function, method, or event handler where the break occurred. inline ...
...hat were executed in order ot get to the currently executing code. click on an item in the call stack to jump to the associated line in the code display. scopes a list of the values that are in scope in the function, method, or event handler where the break occurred. inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through. see set a breakpoint > inline variable preview for more information. ...
UI Tour - Firefox Developer Tools
ons available for individual files and folders or groups; typically viewed by right-clicking on the item. for files, the following context menu options are available: copy source uri copies the full identifier of the file to the clipboard. ignore source causes the debugger to skip the file when "stepping into" functions; this can be helpful for avoiding stepping into libraries used by your code. when a file is ignored, it has a small eye icon next to it in place of its regular icon. download file opens a file dialog so you can save the file locally. for folders and groups, the following context menu options are available: collapse all collapses all subfolders of the item. expand all expands all subfolders of the item. set directory root changes the source list view so that onl...
... toolbar: the toolbar consists of: four buttons to control the debugger's movement through the script: play/pause (f8): pauses or resumes execution of the script you're debugging. when it displays a "play" icon, that means the script is paused, either because you've paused it with this button or because you've hit a breakpoint. step over (f10): steps to the next line of javascript code. step in (f11): steps into the function call on the current line of javascript code. step out (shift-f11): runs the script until the current function exits. a button that deactivates all breakpoints. a settings menu that contains: disable javascript: disables javascript for this tab. this option enables you to see how your web page looks if the user has disabled javascript via ...
...iles, and map them to the generated ones loaded in a page, to ease debugging of translformed sources. see use a source map for details. breakpoints list under the toolbar, you'll see all the breakpoints you've set. next to each breakpoint is a checkbox which you can use to enable/disable it: watch expressions you can add watch expressions in the right pane. they will be evaluated when code execution is paused: variable tooltip hover on a variable show a tooltip with its value inside: call stack when the debugger's paused, you'll see a call stack: each level of the call stack gets a line, with the name of the function and the filename and line number. clicking a line selects the corresponding line in the source pane. note: if you click step over (f10) after changing the s...
Deprecated tools - Firefox Developer Tools
we have added several experimental panels to try out new ideas. not all of these have had wide adoption, and due to the cost of maintenance, seldom used panels are eventually removed. we have created this list of deprecated or removed panels. this page documents the deprecated panels and the bugs that track their removal. although these panels have been removed, you still have access to the old code, and there are alternative webextensions that you can try to get similar functionality. when we deprecate a panel, we begin by getting feedback from the community to determine the impact of removing that panel. once we have decided to remove the panel, we will provide a warning message, and finally, we will remove the panel from the codebase. you may see a warning message, as in the following i...
...age, as in the following image, when trying to activate a deprecated panel: in addition, if you open the panel for one of these tools, you will also see a warning message about its removal. scratchpad scratchpad is deprecated as of firefox 70 (bug 1565380), and will be removed as of firefox 72 (bug 1519103). description scratchpad provided an environment for experimenting with javascript code. you can write, run, and examine the result of code that interacts with the web page. alternatives in firefox 71+, you can write multi-line javascript code in the web console editor mode, making it similar to the scratchpad. the editor mode can be triggered clicking on the icon on the right of the console input, or with ctrl + b (cmd + b on macos) when in editor mode, the enter key adds a ne...
...lar 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 in the console input with ctrl + o (cmd + o on macos), as well as savi...
DevTools API - Firefox Developer Tools
re located in a box we call a toolbox. a toolbox can be hosted within a browser tab (at the bottom or on the side), or in its own window (we say that the toolbox is undocked). a toolbox (and all the tools it contains) is linked to a target, which is the object the tools are debugging. a target is usually a web page (a tab), but can be other things (a chrome window, a remote tab,…). in terms of code, each tool has to provide a tooldefinition object. a definition is a js light object that exposes different information about the tool (like its name and its icon), and a build method that will be used later-on to start an instance of this tool. the gdevtools global object provides methods to register a tool definition and to access tool instances. an instance of a tool is called a toolpanel. th...
... when the tool is highlighted (see e.g. paused, inactive debugger). default: {icon} icononly boolean, optional. if true, the label won't be shown in the tool's tab. default: false inverticonforlighttheme boolean, optional. if true the colors of the icon will be inverted for the light theme. default: false key string, optional. the key used for keyboard shortcut. either key or keycode value. modifiers string, optional. modifiers for the keyboard shortcut. preventclosingonkey boolean, optional. if true the tool won't close if its keybinding is pressed while it is active. default: false inmenu boolean, optional. if true the tool will be shown in the developer menu. default: false menulabel string, optional. a label for the developer menu item. default: {l...
..., layout view). the user can select the tab he wants to see. if the availability of the tabs depends on some tool-related conditions, we might want to not let the user select a tab. this api provides methods to hide the tabstripe. for example, in the web console, there are 2 views (network view and object view). these views are only available in certain conditions controlled by the webconsole code. so it's up the webconsole the hide and show the sidebar, and select the correct tab. if the loaded document exposes a window.setpanel(toolpanel) function, the sidebar will call it once the document is loaded. method description new toolsidebar(xul:tabbox, toolpanel, uid, showtabstripe=true) toolsidebar constructor void addtab(tabid, url, selected=false) ...
Monster example - Firefox Developer Tools
this article describes a very simple web page that we'll use to illustrate some features of the memory tool. you can try the site at https://mdn.github.io/performance-scenarios/js-allocs/alloc.html. ...
...each monster has: a string, for the monster's name a number representing the number of eyes it...
...onsters.fierce.push(new monster()); } for (var i = 0; i &lt; monster_count; i++) { monsters.undecided.push(new monster()); } console.log(monsters); } var makemonstersbutton = document.getelementbyid("make-monsters"); makemonstersbutton.addeventlistener("click", makemonsters); the page contains a button: when you push the button, the code creates some monsters. specifically: the code creates an object with three properties, each an array: one for fierce monsters one for friendly monsters one for monsters who haven't decided yet. for each array, the code creates and appends 5000 randomly-initialized monsters. each monster has: a string, for the monster's name a number representing the number of eyes it has a number representing the number of tenta...
Migrating from Firebug - Firefox Developer Tools
hs firebug allows to search for elements within the html panel via css selectors or xpaths. also the devtools' inspector panel allows to search for css selectors. it even displays a list with matching ids or classes. searching by xpaths is not supported though (see bug 963933. debugger what's the script panel in firebug, is the debugger panel in the devtools. both allow you to debug javascript code executed on a website. switch between sources firebug has a script location menu listing all javascript sources related to the website. those sources can be static, i.e. files, or they can be dynamically generated (i.e. scripts executed via event handlers, eval(), new function(), etc.). in the devtools' debugger panel the scripts are listed at the left side within the sources side panel. dynami...
...r all breakpoints and to remove single breakpoints or all of them at once. they do currently only allow to set script breakpoints. xhr, dom, cookie and error breakpoints are not supported yet (see bug 821610, bug 1004678, bug 895893 and bug 1165010). while there are no breakpoints for single javascript errors, there is a setting pause on exceptions within the debugger panel options. step through code once the script execution is stopped, you can step through the code using the continue (f8), step over (f10), step into (f11) and step out (shift+f11) options. they work the same in both tools. examine call stack when the script execution is paused, firebug displays the function call stack within its stack side panel. in there the functions are listed together with their call parameters. in th...
... of each function call under total time as well as the number of calls under samples, the time spent within the function under self time and the related percentages in reference to the total execution time. note: the times and percentages listed in the devtools' call tree view is not equivalent to the ones shown in firebug, because it uses different apis sampling the execution of the javascript code. jump to function declaration like in firebug's profiler output the call tree view of the devtools' performance tool allows to jump to the line of code where the called javascript function is defined. in firebug the source link to the function is located at the right side of the console panel output while within the devtools the link is placed on the right side within the call tree view. netw...
Examine and edit HTML - Firefox Developer Tools
ger contents. now children are indicated in the tree with this icon: at the right side of some nodes there are markers shown indicating different pieces of information related to it: event the element has one or several event listeners attached to it. clicking the marker opens a tooltip listing the event listeners and allows you for each listener to switch to the line of javascript code in the debugger where the listener is defined. scroll the element is a scroll container, i.e. it has overflow: scroll or overflow: auto applied to it, and it has scrollable overflow. grid the element is a grid container, i.e. it has display: grid applied to it. clicking the marker enables the grid highlighter. flex the element is a flex container, i.e. it has d...
...nline-grid or display: inline grid applied to it. clicking the marker enables the grid highlighter. inline-flex the element is an inline flex container, i.e. it has display: inline-flex or display: inline flex applied to it. clicking the marker enables the flexbox highlighter. custom… the element is a custom element. clicking the marker switches to the line of javascript code in the debugger where the custom element got defined. note: there are some useful keyboard shortcuts that can be used in the html tree — see the html pane keyboard shortcuts list. ::before and ::after you can inspect pseudo-elements added using ::before and ::after: custom element definition when you open the inspector on a page that includes custom elements, you can view the cla...
...added using ::before and ::after: custom element definition when you open the inspector on a page that includes custom elements, you can view the class definition for the custom element in the debugger: inspect the element click on the word custom the source for the element's class will be displayed in the debugger. whitespace-only text nodes web developers don’t write all their code in just one line of text. they use white space such as spaces, returns, or tabs between their html elements because it makes markup more readable. usually this white space seems to have no effect and no visual output, but in fact, when a browser parses html it will automatically generate anonymous text nodes for elements not contained in a node. this includes white space (which is after all a ty...
Examine Event Listeners - Firefox Developer Tools
firefox can display: standard dom events jquery events react eve...
...firefox can display: standard dom events jquery events react eve...
... contains: a right-pointing arrowhead; click to expand the row and show the listener function source code a curved arrow pointing to a stack; click it to show the code for the handler in the debugger the name of the event for which a handler was attached to this element the name and line number for the listener; you can also click here to expand the row and view the listener function source code a label indicating whether the event bubbles a label indicating the system that defines the event. firefox can display: standard dom events jquery events react events ...
The JavaScript input interpreter - Firefox Developer Tools
you can enter multiple lines of javascript by default in this mode, pressing enter after each one. to execute the snippet that is currently in the editing pane, click the run button or press ctrl+enter (or cmd+return on macos). the snippet is echoed under the input prompt (in the right-side pane), followed by the result. you can also select a range of lines in the editing pane, and run just the code on those lines. starting in firefox 76, if the code snippet is more than five lines long, only the first five lines are echoed in the console, preceeded by a disclosure triangle (or "twistie"), and followed by an ellipsis (…). click anywhere in the area containing the echoed code to show the whole snippet; click again in that area to collapse it. you can open files when in multi-line mode, an...
...mode. note that the result might be an error message. expressions that have side effects are not evaluated. you can enable or disable instant evaluation via the settings ("gear") menu in the web console toolbar. the menuitem instant evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. select the menuitem to change the state. execution context code that you have executed becomes part of the execution context, regardless of what editing mode you were in when you executed it. for example, if you type a function definition in the multi-line editor, and click run, you can switch to single-line mode and still use your function. syntax highlighting the text you enter has syntax highlighting as soon as you have typed enough for the highlighter...
...mand line provided by the web console offers a few built-in helper functions that make certain tasks easier. $(selector, element) looks up a css selector string selector , returning the first node descended from element that matches. if unspecified, element defaults to document. equivalent to document.queryselector() or calls the $ function in the page, if it exists. see the queryselector code snippet. $$(selector, element) looks up a css selector string selector, returning an array of dom nodes descended from element that match. if unspecified, element defaults to document. this is like for document.queryselectorall(), but returns an array instead of a nodelist. $0 the currently-inspected element in the page. $_ stores the result of the last expression executed in the console'...
Web Console remoting - Firefox Developer Tools
h changes that have been made since then. the webconsoleactor and the webconsoleclient the webconsoleactor lives in dbg-webconsole-actors.js, in the toolkit/devtools/webconsole folder. the webconsoleclient lives in webconsoleclient.jsm (in toolkit/devtools/webconsole) and it is used by the web console when working with the web console actor. to see how the debugger is used in the web console code, look in browser/devtools/webconsole/webconsole.js, and search for webconsoleconnectionproxy. the new web console actors are: the webconsoleactor allows js evaluation, autocomplete, start/stop listeners, etc. the networkeventactor is used for each new network request. the client can request further network event details - like response body or request headers. to attach to the webconsoleac...
...variable view sends strings like these for evaluation: _self["prop"] = value; the frameactor property is an optional frameactor id. the fa holds a reference to a debugger.frame. this option allows you to evaluate the string in the frame of the given fa. the url property is an optional url to evaluate the script as (new in firefox 25). the default source url for evaluation is "debugger eval code". the selectednodeactor property is an optional nodeactor id, which is used to indicate which node is currently selected in the inspector, if any. this nodeactor can then be referred to by the $0 jsterm helper. the response packet: { "from": "conn0.console9", "input": "document", "result": { "type": "object", "classname": "htmldocument", "actor": "conn0.consoleobj20" "ext...
...23: we renamed the error and errormessage properties to exception and exceptionmessage respectively, to avoid conflict with the default properties used when protocol errors occur. autocomplete and more the autocomplete request packet: { "to": "conn0.console9", "type": "autocomplete", "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 networkeve...
AudioBufferSourceNode.loopEnd - Web APIs
nds = audiobuffersourcenode.loopend; value a floating-point number indicating the offset, in seconds, into the audio buffer at which each loop will loop return to the beginning of the loop (that is, the current play time gets reset to audiobuffersourcenode.loopstart). this property is only used if the loop property is true. the default value is 0. example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and slider controls are used to change the playbackrate, loopstart and loopend properties on the fly. when the audio is played to the end, it loops, but you can control how long the loops last by altering loopstart and loopend. for example, if y...
...ps last by altering loopstart and loopend. for example, if you set their values to 20 and 25, respectively, then begin playback, the sound will play normally until it reaches the 25 second mark. then the current play position will loop back to the 20 second mark and continue playing until the 25 second mark, ad infinitum (or at least until stop() is called). ...
...ad infinitum (or at least until stop() is called). for a full working example, see this code running live, or view the source. ...
AudioBufferSourceNode.loopStart - Web APIs
tart property's default value is 0. syntax audiobuffersourcenode.loopstart = startoffsetinseconds; startoffsetinseconds = audiobuffersourcenode.loopstart; value a floating-point number indicating the offset, in seconds, into the audio buffer at which each loop should begin during playback. this value is only used when the loop parameter is true. example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and slider controls are used to change the playbackrate, loopstart, and loopend properties on the fly. when the audio is played to the end, it loops, but you can control how long the loops last by altering loopstart and loopend. for example, if ...
...ider controls are used to change the playbackrate, loopstart, and loopend properties on the fly. when the audio is played to the end, it loops, but you can control how long the loops last by altering loopstart and loopend. for example, if you set their values to 20 and 25, respectively, the audio will start to loop between 20 and 25 seconds in to the track. ...
...t to loop between 20 and 25 seconds in to the track. for a full working example, see this code running live, or view the source. ...
AudioProcessingEvent - Web APIs
here the output audio data should be written. the number of channels is defined as a parameter, numberofoutputchannels, of the factory method audiocontext.createscriptprocessor(). note the the returned audiobuffer is only valid in the scope of the onaudioprocess function. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white nois...
... each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...utton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); ...
AudioWorkletProcessor - Web APIs
instead, they are created only internally by the creation of an associated audioworkletnodes. the constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures — see constructor page for details. ...
...instead, they are created only internally by the creation of an associated audioworkletnodes. the constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures — see constructor page for details. ...
...gs to. the other end is available under the port property of the node. methods the audioworkletprocessor interface does not define any methods of its own. however, you must provide a process() method, which is called in order to process the audio stream. events the audioworkletprocessor interface doesn't respond to any events. usage notes deriving classes to define custom audio processing code you have to derive a class from the audioworkletprocessor interface. although not defined on the interface, the deriving class must have the process method. this method gets called for each block of 128 sample-frames and takes input and output arrays and calculated values of custom audioparams (if they are defined) as parameters. you can use inputs and audio parameter values to fill the outputs a...
AuthenticatorResponse.clientDataJSON - Web APIs
arraybuffer = authenticatorassertionresponse.clientdatajson; value an arraybuffer. properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created. challenge the base64url encoded version of the cryptographic challenge sent from the relying party's server. the original value is passed via publickeycredentialrequestoptions.challenge or publickeycredentialcreationoptions.challenge. origin the fully qualified origin of the requester which has been given by the client/browser to the authenticator. we should expect the relying party's id to be a suffix of this value. tokenb...
...port token binding but did not negotiate with the relying party or "present" when token binding was used already id: a domstring which is the base64url encoding of the token binding id which was used for the communication. should this property be absent, it would indicate that the client does not support token binding. ...
...buffertostr(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } // pk is a publickeycredential that is the result of a create() or get() promise var clientdatastr = arraybuffertostr(pk.clientdatajson); var clientdataobj = json.parse(clientdatastr); console.log(clientdataobj.type); // "webauthn.create" or "webauthn.get" console.log(clientdataobj.challenge); // base64 encoded string containing the original challenge console.log(clientdataobj.origin); // the window.origin specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'clientdatajson' in that specification. recommendation initial definition. ...
BaseAudioContext.createBuffer() - Web APIs
the createbuffer() method of the baseaudiocontext interface is used to create a new, empty audiobuffer object, which can then be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page. ...
...ect, which can then be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page. note: createbuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createbuffer() was blocking other code execution. the asynchronous method decodeaudiodata() does the same thing — takes compressed audio, say, an mp3 file, and directly gives you back an audiobuffer that you can then set to play via in an audiobuffersourcenode. for simple uses like playing an mp3, decodeaudiodata() is what you should be using. syntax var buffer = baseaudiocontext.createbuffer(numofchannels, length, samplerate); ...
...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 -1.0 and 1.0 for (var channel = 0; channel < myarrayb...
BaseAudioContext.createScriptProcessor() - Web APIs
ts to 2. values of up to 32 are supported. important: webkit currently (version 31) requires that a valid buffersize be passed when calling this method. note: it is invalid for both numberofinputchannels and numberofoutputchannels to be zero. returns a scriptprocessornode. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white nois...
... each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...utton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); ...
BaseAudioContext - Web APIs
baseaudiocontext.currenttime read only returns a double representing an ever-increasing hardware time in seconds used for scheduling. it starts at 0. baseaudiocontext.destination read only returns an audiodestinationnode representing the final destination of all audio in the context. it can be ...
...audiocontext.createbuffer() creates a new, empty audiobuffer object, which can then be populated by data and played via an audiobuffersourcenode. baseaudiocontext.createbuffersource() creates an audiobuffersourcenode, which can be used to play and manipulate audio data contained within an audiobuffer object. audiobuffers are created using audiocontext.createbuffer or returned by audiocontext.decodeaudiodata when it successfully decodes an audio track. baseaudiocontext.createconstantsource() creates a constantsourcenode object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value. baseaudiocontext.createchannelmerger() creates a channelmergernode, which is used to combine channels from multiple audio streams into a...
...context.createscriptprocessor() creates a scriptprocessornode, which can be used for direct audio processing via javascript. baseaudiocontext.createstereopanner() creates a stereopannernode, which can be used to apply stereo panning to an audio source. baseaudiocontext.createwaveshaper() creates a waveshapernode, which is used to implement non-linear distortion effects. baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer. in this case, the arraybuffer is usually loaded from an xmlhttprequest's response attribute after setting the responsetype to arraybuffer. this method only works on complete files, not fragments of audio files. examples basic audio context declaration: const audiocontext = new audiocontext(); cross browser varian...
CSS.escape() - Web APIs
Web › API › CSS › escape
mstring containing the escaped string passed as parameter, mostly for use as part of a css selector. syntax escapedstr = css.escape(str); parameters str the cssomstring to be escaped. ...
...ng containing the escaped string passed as parameter, mostly for use as part of a css selector. syntax escapedstr = css.escape(str); parameters str the cssomstring to be escaped. ...
...rt of a css selector. syntax escapedstr = css.escape(str); parameters str the cssomstring to be escaped. ...
Using the CSS Painting API - Web APIs
as relative to the size of the element — we can use the element's paintsize property to ensure the background image is proportional to the size of the element's box model size. in the above image, the background proportional to the size of the element. the 3rd example has width: 50%; set on the block level element, making the element narrower and therefore the background image narrower. ...
... we've changed the dimensions and positioning of our rectangle to be relative to the size of the element box rather than absolute values. we can pass the second parameter into the paint() function to give us access to the width and the height of the element, via .width and .height p...
...et can also have access to css custom properties and regular css properties. registerpaint('csspaintfunctionname', class { static get inputproperties() { return ['propertyname1', '--custompropertyname2']; } static get inputarguments() { return ['<color>']; } static get contextoptions() { return {alpha: true}; } paint(drawingcontext, elementsize, stylemap) { // paint code goes here. } }); the three parameters of the paint() function include the drawing context, paint size and properties. to be able to access properties, we include the static inputproperties() method, which provides live access to css properties, including regular properties and custom properties, and returns an array of property names. we'll take a look at inputarguments in the last section...
CacheStorage - Web APIs
the cachename, and if found, deletes the cache object and returns a promise that resolves to true. if no cache object is found, it resolves to false. cachestorage.keys() returns a promise that will resolve with an array containing strings corresponding to all of the named cache objects tracked by the cachestorage. use this method to iterate over a list of all the cache objects. examples this code snippet is from the mdn sw-test example (see sw-test running live.) this service worker script waits for an installevent to fire, then runs waituntil to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using cache.addall to add a series of assets to it. in the second code block, we wait for a fetchevent to fire. we construct a custom ...
...e(); caches.open('v1').then(function (cache) { cache.put(event.request, responseclone); }); return response; }).catch(function () { return caches.match('/sw-test/gallery/mylittlevader.jpg'); }); } })); }); this snippet shows how the api can be used outside of a service worker context, and uses the await operator for much more readable code. ...
...g'); }); } })); }); this snippet shows how the api can be used outside of a service worker context, and uses the await operator for much more readable code. // try to get data from the cache, but fall back to fetching it live. ...
CanvasPattern.setTransform() - Web APIs
the canvaspattern.settransform() method uses an svgmatrix or dommatrix object as the pattern's transformation matrix and invokes it on the pattern. syntax void pattern.settransform(matrix); parameters matrix an svgmatrix or dommatrix to use as the pattern's transformation matrix. examples using the settransform method this is just a simple code snippet which uses the settransform method to create a canvaspattern with the specified pattern transformation from an svgmatrix. the pattern gets applied if you set it as the current fillstyle and gets drawn onto the canvas when using the fillrect() method, for example. html <canvas id="canvas"></canvas> <svg id="svg1"></svg> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var svg1 = docu...
... = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); }; note that newer browser versions started to support dommatrix as an input to settransform(), so for example you could replace the svgmatrix in the above example with the following: const matrix = new dommatrix([1, .2, .8, 1, 0, 0]); edit the code below and see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1" style="display:none"></svg> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:120px"> var ...
...c = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); };</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(); }); ed...
CanvasRenderingContext2D.addHitRegion() - Web APIs
function(event) { if(event.region) { alert('ouch, my eye :('); } }); ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi); ctx.arc(130, 80, 10, 0, 2 * math.pi); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi); ctx.stroke(); edit the code below to see your changes update live in the canvas. (if you don't see the full smiley, check the browser compatibility table to see if your current browser supports hit regions already; you might need to activate a preference.) playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edi...
...ll smiley, check the browser compatibility table to see if your current browser supports hit regions already; you might need to activate a preference.) playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:250px"> ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi, false); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.arc(130, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi, false); ctx.stroke();</textarea> var...
...th = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.arc(130, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({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.addevent...
A basic ray-caster - Web APIs
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 is drawn centered over the horizon line. the code i ended up with is a regurgitated amalgam of the raycaster chapters from an old andré lamothetricks of the game programming gurus book (isbn: 0672305070), and a java raycaster i found online, filtered through my compulsion to rename everything so it makes sense to me, and all the tinkering that had to be done to make things work well. results the canvas in safari 2.0.1 performed surprisingly w...
...8 pixels wide, i can run a 320 x 240 window at 24 fps on my apple mini. firefox 1.5 beta 1 is even faster; i can run 320 x 240 at 24 fps with 4 pixel slivers. not exactly a new member of the id software family, but pretty decent considering it's a fully interpreted environment, and i didn't have to worry about memory allocation or video modes or coding inner routines in assembler or anything. the code does attempt to be very efficient, using array look-ups of pre-computed values, but i'm no optimization guru, so things could probably be written faster. also, it leaves a lot to be desired in terms of trying to be any sort of game engine—there are no wall textures, no sprites, no doors, not even any teleporters to get to another level. but i'm pretty confident all those things could be added ...
... level. but i'm pretty confident all those things could be added given enough time. the canvas api supports pixel copying of images, so textures seem feasible. i'll leave that for another article, probably from another person. =) the ray-caster the nice people here have manually copied my files up so you can take a look, and for your hacking enjoyment i've posted the individual file contents as code listings (see below). so there you are, fire up safari 1.3+ or firefox 1.5+ or some other browser that supports the <canvas> element and enjoy! input.js | level.js | player.js | raycaster.html | raycaster.js | trace.css | trace.js see also canvas tutorial ...
console - Web APIs
Web › API › Console
ups in the console you can use nested groups to help organize your output by visually combining related material. to create a new nested block, call console.group(). the console.groupcollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading. to exit the current group, simply call console.groupend(). ...
...s you can start a timer to calculate the duration of a specific operation. to start one, call the console.time() method, giving it a name as the only parameter. to stop the timer, and to get the elapsed time in milliseconds, just call the console.timeend() method, again passing the timer's name as the parameter. up to 10,000 timers can run simultaneously on a given page. ...
...ted in the network panel is just the amount of time required for the header. if you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output. stack traces the console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call console.trace(). given code like this: function foo() { function bar() { console.trace(); } bar(); } foo(); the output in the console looks something like this: specifications specification status comment console api living standard initial definition. ...
CustomElementRegistry.define() - Web APIs
trying to extend is an unknown element. syntaxerror the provided name is not a valid custom element name. typeerror the referenced constructor is not a constructor. note: you'll often get notsupportederrors thrown that seem like define() is failing, but instead it is likely a problem with element.attachshadow(). examples autonomous custom element the following code is taken from our popup-info-box-web-component example (see it live also). // create a class for the element class popupinfo extends htmlelement { constructor() { // always call super first in constructor super(); // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create spans var wrapper = document.createelement('span'); wrapper.setattribu...
... // create a class for the eleme...
...tomelements.define('popup-info', popupinfo); <popup-info img="img/alt.png" text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."> note: constructors for autonomous custom elements must extend htmlelement. customized built-in element the following code is taken from our word-count-web-component example (see it live also). // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.textcontent ...
DirectoryReaderSync - Web APIs
worker thread see the same javascript object; you just need them to access the same files. you can do that by passing a list of filesystem: urls—which are just strings—instead of a list of entries. you can also use the filesystem: url to look up the entry with resolvelocalfilesystemurl(). that gets you back to a directoryentrysync (as well as fileentrysync) object. example in the following code snippet from html5rocks, we create web workers and pass data from it to the main app. // taking care of the browser-specific prefixes. window.resolvelocalfilesystemurl = window.resolvelocalfilesystemurl || window.webkitresolvelocalfilesystemurl; // create web workers var worker = new worker('worker.js'); worker.onmessage = function(e) { var urls = ...
...murl; // create web workers var worker = new worker('worker.js'); worker.onmessage = function(e) { var urls = e.data.entries; urls.foreach(function(url, i) { window.resolvelocalfilesystemurl(url, function(fileentry) { // print out file's name. console.log(fileentry.name); }); }); }; worker.postmessage({'cmd': 'list'}); the following is worker.js code that gets the contents of the directory. // taking care of the browser-specific prefixes. self.requestfilesystemsync = self.webkitrequestfilesystemsync || self.requestfilesystemsync; // global for holding the list of entry file system urls. var paths = []; function getallentries(dirreader) { var entries = dirreader.readentries(); for (var i = 0, entry; entry =...
...); } catch (e) { onerror(e); } }; method overview entrysync readentries () raises (fileexception); method readentries() returns a lost of entries from a specific directory. call this method until an empty array is returned. entrysync readentries ( ) raises (fileexception); returns parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist. invalid_state_err the directory has been modified since the first call to readentries was processed. security_err the browser determined that it was not safe to look up the metadata. browser compatibility the compatibility table on this page is generated from structured...
Document: keydown event - Web APIs
the keydown event is fired when a key is pressed. unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. bubbles yes cancelable yes interface keyboardevent event handler property onkeydown the keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. an uppercase "a" is reported as 65 by all events. since firefox 65, the keydown and keyup events are now fired during ime composition, to improve cross-browser compatibility for cjkt users (bug 354358, also see keydown and keyup events are now fired during ime ...
... reported as 65 by all events. since firefox 65, the keydown and keyup events are now fired during ime composition, to improve cross-browser compatibility for cjkt users (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keydown", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something }); examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key. <p>focus the iframe first (e.g. by clicking in it), then try pressing some ...
...scomposing || event.keycode === 229) { return; } // do something }); examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key. <p>focus the iframe first (e.g. ...
Document: keyup event - Web APIs
for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. an uppercase "a" is reported as 65 by all events. note: if you're looking for a way to react to changes in an input's value, you should use the input event. ...
...e context menu in a text input. since firefox 65, the keydown and keyup events are now fired during ime composition, to improve cross-browser compatibility for cjkt users (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keyup", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something }); examples this example logs the keyboardevent.code value whenever you release a key. addeventlistener keyup example <p>focus the iframe first (e.g. by clicking in it), then try pressing some keys.</...
... return; } // do something }); examples this example logs the keyboardevent.code value whenever you release a key. addeventlistener keyup example <p>focus the iframe first (e.g. ...
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
syntax var nodes = document.nodesfrompoint(x, y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. returns an array of node objects. ...
... ...
... ...
Locating DOM elements using selectors - Web APIs
the selectors api provides methods that make it quick and easy to retrieve element nodes from the dom by matching against a set of selectors. this is much faster than past techniques, wherein it was necessary to, for example, use a loop in javascript code to locate the specific items you needed to find. the nodeselector interface this specification adds two new methods to any objects implementing the document, documentfragment, or element interfaces: queryselector() returns the first matching element node within the node's subtree. if no matching node is found, null is returned. queryselectorall() returns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. note: the nodelist returned by queryselectorall() i...
...o matches are found. note: the nodelist returned by queryselectorall() is not live, which means that changes in the dom are not reflected in the collection. this is different from other dom querying methods that return live node lists. you may find examples and details by reading the documentation for the element.queryselector() and element.queryselectorall() methods, as well as in the article code snippets for queryselector. selectors the selector methods accept one or more comma-separated selectors to determine what element or elements should be returned. for example, to select all paragraph (p) elements in a document whose css class is either warning or note, you can do the following: var special = document.queryselectorall( "p.warning, p.note" ); you can also query by id. for exampl...
...selectors to determine what element or elements should be returned. for example, to select all paragraph (p) elements in a document whose css class is either warning or note, you can do the following: var special = document.queryselectorall( "p.warning, p.note" ); you can also query by id. for example: var el = document.queryselector( "#main, #basic, #exclamation" ); after executing the above code, el contains the first element in the document whose id is one of main, basic, or exclamation. you may use any css selectors with the queryselector() and queryselectorall() methods. ...
Element: keydown event - Web APIs
the keydown event is fired when a key is pressed. unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. bubbles yes cancelable yes interface keyboardevent event handler property onkeydown the keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. an uppercase "a" is reported as 65 by all events. keyboard events are only generated by <inputs>, <textarea> and anything with the contenteditable attribute or with tabindex="-1". since firefox 65, the keydown and keyup events are now fired during ime comp...
...tribute or with tabindex="-1". since firefox 65, the keydown and keyup events are now fired during ime composition, to improve cross-browser compatibility for cjkt users (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keydown", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something }); examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element. <input placeholder="click here, then press down ...
...istener keydown example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element. ...
Element: keyup event - Web APIs
for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. an uppercase "a" is reported as 65 by all events. ...
...is reported as 65 by all events. since firefox 65, the keyup and keydown events are now fired during ime composition, to improve cross-browser compatibility for cjkt users (bug 354358, also see keydown and keyup events are now fired during ime composition for more useful details). to ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keyup", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something }); examples addeventlistener keyup example this example logs the keyboardevent.code value whenever you release a key inside the <input> element. <input placeholder="click here, then press and release ...
...istener keyup example this example logs the keyboardevent.code value whenever you release a key inside the <input> element. ...
FileError - Web APIs
Web › API › FileError
r that occurs while using the filereader interface. note: this interface is obsolete per the latest specification. use the new dom4 domerror interface instead. in the file system api, a fileerror represents error conditions that you might encounter while accessing the file system using the asynchronous api. it extends the fileerror interface described in file writer and adds several new error codes. fileerror objects are passed to error callbacks. the objects have a code that shows the type of error that occurred. best practices most people don't read the page on errors and exceptions unless they're stumped. so the following are a few tips that could help you avoid some pitfalls. error callbacks are not optional for your sanity although error callbacks are optional, you should include...
... as file system, blobbuilder, and filereader) throw errors if you run the app locally from file://. when you're just testing your app, and you don't want to set up a web server, you can bypass the security restriction on chrome. just start chrome with the --allow-file-access-from-files flag. use the flag only for testing purposes. attribute attribute type description code unsigned short the most appropriate error code for the condition. see error codes for possible values. error codes note: do not rely on the numeric values of the constants, which might change as the specifications continue to change. use the constant names instead. constant value description encoding_err 5 the url is malformed. make sure that the url i...
...a was reached and the user declined to give more space to the database. to ask for more storage, see managing html5 offline storage. security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application. too many calls are being made on file resources. other unspecified security error code or situations. type_mismatch_err 11 the app looked up an entry, but the entry found is of the wrong type. for example, the app is asking for a directory, when the entry is really a file. ...
Using the Frame Timing API - Web APIs
e browser should process a frame in about 16.7ms. an application can register a performanceobserver for "frame" performance entry types and the observer will have data about the duration of each frame event. this data can be used to help identify areas that take too long to provide a good user experience. this document describes how to use the performanceframetiming interfaces including example code. for an overview of these interfaces see frame timing api. frame observers the performance observer interfaces allow an application to register an observer for specific performance event types. when one of those event types is added to the browser's performance timeline, the application is notified of the event via the observer's callback function that was specified when the observer was creat...
...this section briefly describes the web performance tools for the firefox and chrome/canary browsers. firefox performance tool firefox's performance tool allows the developer to record a piece of the user's interaction and the data obtained during the recording is used to create a profile of the browser's activity. the profile includes a wa...
... having frame related performance problems (for example, by correlating the recording's minimum rates with their respective waterfall events). the performance tool's flame chart and call tree tabs provide data to help analyze the site's javascript usage. the call tree shows where the application is spending most of its time, whereas the flame chart shows the state of the javascript stack for the code at every millisecond during the performance profile. this provides a way to know exactly which function was executing at any point during the recording, how long it ran, and where it was called from. chrome performance tool the chrome (and canary) browsers also have a performance tool with similar functions as firefox. see performance profiling with the timeline for more information about this ...
Gamepad.buttons - Web APIs
Web › API › Gamepad › buttons
or unpressed (false). the value property is a floating point value used to enable representing analog buttons, such as the triggers on many modern gamepads. the values are normalized to the range 0.0 – 1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. ...
... analog buttons, such as the triggers on many modern gamepads. the values are normalized to the range 0.0 – 1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. ...
...he triggers on many modern gamepads. the values are normalized to the range 0.0 – 1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. syntax readonly attribute gamepadbutton[] buttons; example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stores as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are. ...
GamepadButton - Web APIs
sent the current state of analog buttons, such as the triggers on many modern gamepads. the values are normalized to the range 0.0 —1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. gamepadbutton.pressed read only a boolean value indicating whether the button is currently pressed (true) or unpressed (false). ...
...ues are normalized to the range 0.0 —1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. gamepadbutton.pressed read only a boolean value indicating whether the button is currently pressed (true) or unpressed (false). ...
...range 0.0 —1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. gamepadbutton.pressed read only a boolean value indicating whether the button is currently pressed (true) or unpressed (false). example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stored as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are. ...
GlobalEventHandlers.onanimationend - Web APIs
box to migrate from the top-left corner of the container to the bottom-right corner. .slideanimation { animation: 5s ease-in-out 0s 1 slidebox; } @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the css describes the animation but doesn't connect it to the box, we'll need some javascript code to do that. we'll get to that shortly. javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. function log(msg, event) { let l...
...function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. ...
...on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. ...
GlobalEventHandlers.onanimationstart - Web APIs
box to migrate from the top-left corner of the container to the bottom-right corner. .slideanimation { animation: 5s ease-in-out 0s 1 slidebox; } @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the css describes the animation but doesn't connect it to the box, we'll need some javascript code to do that. we'll get to that shortly. javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. function log(msg, event) { let l...
...function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. ...
...on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. ...
HTMLImageElement.decoding - Web APIs
auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. ...
... auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. ...
... auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. ...
HTMLObjectElement - Web APIs
t to the surrounding context. the possible values are "left", "right", "justify", and "center". htmlobjectelement.archive is a domstring that reflects the archive html attribute, containing a list of archives for resources for this object. htmlobjectelement.border is a domstring that reflects the border html attribute, specifying the width of a border around the object. ...
...list of archives for resources for this object. htmlobjectelement.border is a domstring that reflects the border html attribute, specifying the width of a border around the object. htmlobjectelement.code is a domstring representing the name of an applet class file, containing either the applet's subclass, or the path to get to the class, including the class file itself. htmlobjectelement.codebase is a domstring that reflects the codebase html attribute, specifying the base path to use to resolve relative uris. htmlobjectelement.codetype is a domstring that reflects the codetype html attribute, specifying the content type of the data. htmlobjectelement.contentdocument read only returns a document representing the active document of the object element's nested browsing context...
...e definition of 'htmlobjectelement' in that specification. living standard html5the definition of 'htmlobjectelement' in that specification. recommendation the w3c specification is a latest of a previous version of html living standard technically, the property tabindex is now defined on htmlelement. the following properties are now obsolete: align, archive, border, code, codebase, codetype, declare, hspace, standby, and vspace. the following properties have been added: typemustmatch, contentwindow, willvalidate, validity, and validationmessage. the following methods have been added: checkvalidity() and setcustomvalidity(). document object model (dom) level 2 html specificationthe definition of 'htmlobjectelement' in that specification. obsole...
IDBDatabaseException - Web APIs
message domstring error message describing the exception raised. ...
... message domstring error message describing the exception raised. ...
..._only transaction. timeout_err 10 a lock for the transaction could not be obtained in a reasonable time. transaction_inactive_err 7 a request was made against a transaction that is either not currently active or is already finished. unknown_err 1 the operation failed for reasons unrelated to the database itself, and it is not covered by any other error code--for example, a failure due to disk io errors. ver_err 12 a request to open a database with a version lower than the one it already has. this can only happen with idbopendbrequest. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data ...
IDBTransactionSync - Web APIs
c. methods abort() call this method to signal a need to cancel the effects of the operations performed by this transaction. when this method is called, the browser ignores all the changes performed to the objects of this database since this transaction was created. void abort( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following code: non_transient_err if this transaction has already been committed or aborted. commit() call this method to signal that the transaction has completed normally and satisfactorily. when this method is called, the browser durably stores all the changes performed to the objects of the database since this transaction was created. void commit( ) raises (idbdatabaseexception); exceptions this ...
... committed or aborted. commit() call this method to signal that the transaction has completed normally and satisfactorily. when this method is called, the browser durably stores all the changes performed to the objects of the database since this transaction was created. void commit( ) raises (idbdatabaseexception); exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if this transaction has already been committed or aborted. recoverable_err if this transaction's scope is dynamic, and the browser cannot commit all of the changes due to another transaction. objectstore() returns an object store that has already been added to the scope of this transaction. idbobjectstoresync objectstore( in domstring name ) raises (idbdatabaseexce...
...) returns an object store that has already been added to the scope of this transaction. idbobjectstoresync objectstore( in domstring name ) raises (idbdatabaseexception); parameters name the name of the requested object store. returns idbobjectstoresync an object for accessing the requested object store. exceptions the method can raise an idbdatabaseexception with the following code: not_found_err if the requested object store is not in this transaction's scope. ...
InstallEvent - Web APIs
></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor installevent.installevent() creates a new installevent object. properties inherits properties from its ancestor, event. installevent.activeworker read only returns the serviceworker that is currently controlling the page. methods inherits methods from its parent, extendableevent. ...
... installevent.installevent() creates a new installevent object. properties inherits properties from its ancestor, event. installevent.activeworker read only returns the serviceworker that is currently controlling the page. methods inherits methods from its parent, extendableevent. examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall and delays treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resources have been fetched and cached, or when any exception occurs. the code snippet also shows a best practice for versioning caches used by the service worker. alt...
...ng the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resources have been fetched and cached, or when any exception occurs. the code snippet also shows a best practice for versioning caches used by the service worker. although this example has only one cache, you can use this approach for multiple caches. the code maps a shorthand identifier for a cache to a specific, versioned cache name. note: logging statements are visible in google chrome via the "inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals. var cache_version = 1; var current_caches = { prefetch: 'prefetch-cache-v' + cache_version }; self.addeventlistener('install', function(event) { var url...
KeyboardEvent.initKeyEvent() - Web APIs
d browsers; other browsers implemented keyboardevent.initkeyboardevent based on early drafts of document object model (dom) level 3 events specification. favor the modern constructor structure as the only cross-browser way of building events. syntax event.initkeyevent (type, bubbles, cancelable, viewarg, ctrlkeyarg, altkeyarg, shiftkeyarg, metakeyarg, keycodearg, charcodearg) parameters type is a domstring representing the type of event. bubbles is a boolean indicating whether the event should bubble up through the event chain or not (see bubbles). cancelable is a boolean i indicating whether the event can be canceled (see cancelable). viewarg specifies the uievent.view; this value may be null. ctrlkeyarg is a boolean that is true if the...
...s containing the ctrl key. altkeyarg is a boolean that is true if the virtual key to be generated is a combination of keys containing the alt key. shiftkeyarg a boolean that is true if the virtual key to be generated is a combination of keys containing the shift key. metakeyarg is a boolean that is true if the virtual key to be generated is a combination of keys containing the meta key. keycodearg is a unsigned long representing the virtual key code value of the key which was depressed, otherwise 0. see keyboardevent.keycode for the list of key codes. charcodearg is a unsigned long representingthe unicode character associated with the depressed key otherwise 0. example var event = document.createevent('keyboardevent'); // create a key event // define the event event.initkeyevent("...
... true, // cancelablearg, null, // viewarg, specifies uievent.view. this value may be null. false, // ctrlkeyarg, false, // altkeyarg, false, // shiftkeyarg, false, // metakeyarg, 9, // keycodearg, 0); // charcodearg); document.getelementbyid('blah').dispatchevent(event); specification this implementation of keyboard events is based on the key events spec in the early versions of dom 2 events, later removed from that spec. the initkeyevent is the current gecko equivalent of the dom level 3 events (initially drafted and also deprecated in favor of ke...
LocalFileSystem - Web APIs
storage.) working within a single origin the file system is sandboxed to a single origin. this means that your app cannot read, or write the files of another app's files. your app cannot access files in an arbitrary folder (such as, my pictures, my documents) on the user's hard drive either. for more information about restrictions, see the basic concepts article. example the following is a code snippet that shows how you can request a file system storage. //taking care of the browser-specific prefix window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the error callback /...
...nique name assigned by the browser to the file system. root - the read-only directoryentry object representing the root of the file system. opt_errorcallback the error callback that is called when errors happen or when the request to obtain the file system is denied. its argument is the fileerror object. returns void exceptions this method can raise an fileerror with the following code: exception description security_error the application does not have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemurl() lets you look up the entry for a file or directory with a local url. void resolvelocalfilesystemurl( in domstring url, in ...
...parameters url the url of a local file in the file system. successcallback the success callback that is called when the browser provides the file or directory for the supplied url. errorcallback the error callback that is called when errors happen or when the request to obtain the entry object is denied. returns void exceptions this method can raise an fileerror with the following code: exception description encoding_err the syntax of the url was invalid. not_found_err the url was structurally correct, but refers to a resource that does not exist. security_err the application does not have permission to access the file system interface. browser compatibility the compatibility table on this page is generated from struc...
MediaCapabilitiesInfo - Web APIs
) methods of the mediacapabilities interface fulfills, providing information as to whether the media type is supported, and whether encoding or decoding such media would be smooth and power efficient. properties the mediacapabilitiesinfo interface contains three boolean attribues: supported: given the properties defined in the mediaconfiguration, can the specified piece of media content be encoded (if mediaencodingconfiguration is set) or decode (if mediadecodingconfiguration is set) at all? if yes, supported is true. otherwise, it is false. smooth: given the properties defined in the mediaconfiguration, will the playback of the specified piece of media be high quality? will it be smooth? if supported is true, and playback will be smooth, smooth is true, otherwise, is it false. poweref...
...owerefficient: given the properties defined in the mediaconfiguration, will the playback of the specified piece of media be power efficient? if supported is true, and playback will be power efficient, powerefficient is true, otherwise, is it false. browsers will report a supported media configuration as smooth and powerefficient until stats on this device have been recorded. all supported audio codecs are reported to be power efficient. example // mediaconfiguration to be tested const mediaconfig = { type : 'file', audio : { contenttype : "audio/ogg", channels : 2, bitrate : 132700, samplerate : 5200 }, }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { // result contains the media capabil...
... draft initial definition ...
MediaError - Web APIs
the mediaerror interface represents an error which occurred while handling media in an html media element based on htmlmediaelement, such as <audio> or <video>. a mediaerror object describes the error in general terms using a numeric code categorizing the kind of error, and a message, which provides specific diagnostics about what went wrong. properties this interface doesn't inherit any properties. mediaerror.code a number which represents the general type of error that occurred, as follows: name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having p...
...s the general type of error that occurred, as follows: name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting in an error. media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. mediaerror.message a domstring object containing a human-readable string which provides spec...
... media_err_src_not_supported 4 the associated resource or media provider object (such as a mediastream) has been found to be unsuitable. mediaerror.message a domstring object containing a human-readable string which provides specific diagnostic information to help the reader understand the error condition which occurred; specifically, it isn't simply a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong. this text and its format is not defined by the specification and will vary from one user agent to another. if no diagnostics are available, or no explanation can be provided, this value is an empty string (""). methods this interface doesn't implement or inherit any methods, and has none of its own. spe...
MediaRecorder.isTypeSupported - Web APIs
n value true if the mediarecorder implementation is capable of recording blob objects for the specified mime type. recording may still fail if there are insufficient resources to support the recording and encoding process. if the value is false, the user agent is incapable of recording the specified format. ...
...ementation is capable of recording blob objects for the specified mime type. recording may still fail if there are insufficient resources to support the recording and encoding process. if the value is false, the user agent is incapable of recording the specified format. ...
...bjects for the specified mime type. recording may still fail if there are insufficient resources to support the recording and encoding process. if the value is false, the user agent is incapable of recording the specified format. example var types = ["video/webm", "audio/webm", "video/webm\;codecs=vp8", "video/webm\;codecs=daala", "video/webm\;codecs=h264", "audio/webm\;codecs=opus", "video/mpeg"]; for (var i in types) { console.log( "is " + types[i] + " supported? " + (mediarecorder.istypesupported(types[i]) ? "maybe!" : "nope :(")); } specifications specification status comment mediastream recordingthe definition of 'istypesupported()' in that specification. working draft initi...
MediaSource.MediaSource() - Web APIs
e object with no associated source buffers. syntax var mediasource = new mediasource(); parameters none. ...
.... syntax var mediasource = new mediasource(); parameters none. ...
... mediasource = new mediasource(); parameters none. example the following snippet is taken from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } ... ...
MediaStream Recording API - Web APIs
recorder. you can listen for error events by setting up a onerror event handler. example here, we use an html canvas as source of the mediastream, and stop recording after 9 seconds. var canvas = document.queryselector("canvas"); // optional frames per second argument. var stream = canvas.capturestream(25); var recordedchunks = []; console.log(stream); var options = { mimetype: "video/webm; codecs=vp9" }; mediarecorder = new mediarecorder(stream, options); mediarecorder.ondataavailable = handledataavailable; mediarecorder.start(); function handledataavailable(event) { console.log("data-available"); if (event.data.size > 0) { recordedchunks.push(event.data); console.log(recordedchunks); download(); } else { // ... } } function download() { var blob = new blob(r...
...camera and/or microphone input, you may wish to examine the available input devices before beginning the process of constructing the mediarecorder. to do so, you'll need to call navigator.mediadevices.enumeratedevices() to get a list of the available media devices. you can then examine that list and identify the potential input sources, and even filter the list based on desired criteria. in this code snippet, enumeratedevices() is used to examine the available input devices, locate those which are audio input devices, and create <option> elements that are then added to a <select> element representing an input source picker. navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { let menu = document.getelementbyid("inputdevices"); if (d...
...ing an input source picker. navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { let menu = document.getelementbyid("inputdevices"); if (device.kind == "audioinput") { let item = document.createelement("option"); item.innerhtml = device.label; item.value = device.deviceid; menu.appendchild(item); } }); }); code similar to this can be used to let the user restrict the set of devices they wish to use. for more information to learn more about using the mediastream recording api, see using the mediastream recording api, which shows how to use the api to record audio clips. a second article, recording a media element, describes how to receive a stream from an <audio> or <video> element and use the captured...
Media Capabilities API - Web APIs
different browsers support different media types and new media types are always being developed. with the media capabilities api, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, and os capabilities. whether a device uses hardware or software decoding impacts how smooth and power efficient the video decoding is and how efficient the pl...
...pes are always being developed. with the media capabilities api, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, and os capabilities. whether a device uses hardware or software decoding impacts how smooth and power efficient the video decoding is and how efficient the playback will be. the media capabilities api enables determining which codecs are supported and how performant a media file will be both in terms of smoothness and power efficiency. the media capabilities api provide more powerful features than say mediarecorder.istypesupported() or htmlmediaelement.canplaytype(), which only address general browser support, not performance. the api also provides abilities to access display property information such as supported color g...
...rface's encodinginfo() and decodinginfo() methods. media capabilities information enables websites to enable adaptative streaming to alter the quality of content based on actual user-perceived quality, and react to a pick of cpu/gpu usage in real time. media capabilities interfaces mediacapabilities provides information about the decoding abilities of the device, system and browser based on codecs, profile, resolution, and bitrates. the information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient . mediacapabilitiesinfo the interface of the promise returned by the mediacapabilities's encodinginfo() and decodinginfo() methods; returning whether the media configuration tested is supported, smooth, and powerefficien...
Media Session API - Web APIs
*/ }); ...
...image.com/256x256', sizes: '256x256', type: 'image/png' }, { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' }, { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' }, ] }); navigator.mediasession.setactionhandler('play', function() { /* code excerpted. */ }); navigator.mediasession.setactionhandler('pause', function() { /* code excerpted. */ }); navigator.mediasession.setactionhandler('seekbackward', function() { /* code excerpted. */ }); navigator.mediasession.setactionhandler('seekforward', function() { /* code excerpted. */ }); navigator.mediasession.setactionhandler('previoustrack', function() { /* code excerpted. */ }); navigator.mediasession.setactionhandler('nexttrack', function() { /* code excerpted. */ ...
...let's play audio... audio.play() .then(_ => { /* set up media session controls, as shown above. ...
MouseEvent.pageX - Web APIs
Web › API › MouseEvent › pageX
ling or viewport positioning that may be in effect. this property was originally specified in the touch events specification as a long integer, but was redefined in the cssom view module to be a double-precision floating-point number to allow for subpixel precision. even though numeric types both are represented by number in javascript, they may be handled differently internally in the browser's code, resulting in potential behavior differences. see browser compatibility to learn which browsers have been updated to use the revised data type. example more examples you can also see an example that demonstrates how to access the mouse position information in every available coordinate system. let's take a look at a simple example that shows you the mouse's position relative to the page's ori...
... updatedisplay() simply replaces the contents of the <span> elements meant to contain the x and y coordinates with the values of pagex and pagey. html <div class="box"> <p> move the mouse around in this box to watch its coordinates change. </p> <p...
...ddeventlistener() to register the function updatedisplay() as the event handler for the mousemove, mouseenter, and mouseleave events. updatedisplay() simply replaces the contents of the <span> elements meant to contain the x and y coordinates with the values of pagex and pagey. html <div class="box"> <p> move the mouse around in this box to watch its coordinates change. </p> <p> <code>pagex</code>: <span id="x">n/a</span> </p> <p> <code>pagey</code>: <span id="y">n/a</span> </p> </div> the html is simple; the box we'll be watching for mouse events on is given the class "box". it has two <span> elements, one with the id "x" and one with the id "y". those will be updated each time an event occurs to contain the latest mouse coordinates relative to the page. css th...
PaymentRequest.show() - Web APIs
n a short time or show() being called while payment requests are blocked by parental controls. usage notes the most common patterns for using show() involve either the async/await syntax or the use of show().then().catch() to handle the response and any possible rejection. ...
... the validateresponse() method, below, is called once show() returns, in order to look at the r...
...e in the response and ensures that they're valid, returning true if every field is valid or false if any are not. if and only if every field is valid, the complete() method is called on the response with the string "success", which indicates that everything is valid and that the payment can complete accordingly. if any fields have unacceptable values, or if an exception is thrown by the previous code, complete() is called with the string "fail", which indicates that the payment process is complete and failed. instead of immediately failing, you could choose to call retry() on the response object to ask the user agent to try to process the payment again; this should usually only be done after the user has made any needed corrections to the order. starting the payment process, in the end, is ...
RTCDataChannel: message event - Web APIs
ceived from the remote peer. bubbles no cancelable no interface messageevent event handler property onmessage note: the message event uses as its event object type the messageevent interface defined by the html specification. examples for a given rtcdatachannel, dc, created for a peer connection using its createdatachannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element. dc.addeventlistener("message", ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); }, false);...
... candidate recommendation ...
... candidate recommendation ...
RTCInboundRtpStreamStats - Web APIs
ec packets arrive in-band along with media content; this can happen with opus, for example. fircount an integer value which indicates the total number of full intra request (fir) packets which this receiver has sent to the sender. this is an indicator of how often the stream has lagged, requiring frames to be skipped in order to catch up. this value is only available for video streams. framesdecoded a long integer value indicating the total number of frames of video which have been correctly decoded so far for this media source. this is the number of frames that would have been rendered if none were dropped. only valid for video streams. lastpacketreceivedtimestamp a domhighrestimestamp indicating the time at which the last packet was received for this source. the timestamp property, on ...
...cketsfaileddecryption an integer totaling the number of rtp packets that could not be decrypted. these packets are not counted by packetsdiscarded. perdscppacketsreceived a record of key-value pairs with strings as the keys mapped to 32-bit integer values, each indicating the total number of packets this receiver has received on this rtp stream from this source for each differentiated services code point (dscp). plicount an integer specifying the number of times the receiver has notified the sender that some amount of encoded video data for one or more frames has been lost, using picture loss indication (pli) packets. this is only available for video streams. qpsum a 64-bit value containing the sum of the qp values for every frame decoded by this rtp receiver. you can determine the aver...
...valid only for video streams. receiverid a string indicating which identifies the rtcaudioreceiverstats or rtcvideoreceiverstats object associated with the stream's receiver. this id is stable across multiple calls to getstats(). ...
RTCPeerConnection: icecandidate event - Web APIs
ectioniceevent event handler property rtcpeerconnection.onicecandidate description there are three reasons why the icecandidate event is fired on an rtcpeerconnection. sharing a new candidate the majority of icecandidate events are fired to indicate that a new candidate has been gathered. this candidate needs to be delivered to the remote peer over the signaling channel your code manages. rtcpeerconnection.onicecandidate = (event) => { if (event.candidate) { sendcandidatetoremotepeer(event.candidate) } else { /* there are no more candidates coming during this negotiation */ } } the remote peer, upon receiving the candidate, will add the candidate to its candidate pool by calling addicecandidate(), passing in the candidate string you have passed along usin...
...ansport, it has completed gathering for a generation of candidates. that this has occurred is indicated by an icecandidate event whose candidate string is empty (""). you should deliver this to the remote peer just like any standard candidate, as described under sharing a new candidate above. this ensures that the remote peer is given the end-of-candidates notification as well. as you see in the code in the previous section, every candidate is sent to the other peer, including any that might have an empty candidate string. only candidates for which the event's candidate property is null are not forwarded across the signaling connection. the end-of-candidates indication is described in section 9.3 of the trickle ice draft specification (note that the section number is subject to change as the...
...g that ice gathering is complete once all ice transports have finished gathering candidates and the value of the rtcpeerconnection object's icegatheringstate has made the transition to complete, an icecandidate event is sent with the value of complete set to null. this signal exists for backward compatibility purposes and does not need to be delivered onward to the remote peer (which is why the code snippet above checks to see if event.candidate is null prior to sending the candidate along. if you need to perform any special actions when there are no further candidates expected, you're much better off watching the ice gathering state by watching for icegatheringstatechange events: pc.addeventlistener("icegatheringstatechange", ev => { switch(pc.icegatheringstate) { case "new": ...
RTCPeerConnection.setRemoteDescription() - Web APIs
ifies the remote peer's current offer or answer. this value is an offer or answer received from the remote peer through your implementation of the sessiondescription parameter is technically of type rtcsessiondescriptioninit, but because rtcsessiondescription serializes to be indistinguishable from rtcsessiondescriptioninit, you can also pass in an rtcsessiondescription. ...
...tential errors which might occur, and simplifies the processing you need to do when you receive an offer, by eliminating the need to handle the offer/answer process differently depending on whether the local peer is the caller or callee. note: earlier implementations of webrtc would throw an exception if an offer was set outside a stable or have-remote-offer state. deprecated syntax in older code and documentation, you may see a callback-based version of this function used. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of setremotedescription() instead. the parameters for the older form of setremotedescription() are described below, to aid in updating existing code. pc.setremotedescription(sessiondescrip...
...ollowing exceptions may occur: invalidstateerror the connection's signalingstate is "closed", indicating that the connection is not currently open, so negotiation cannot take place. invalidsessiondescriptionerror the rtcsessiondescription specified by the sessiondescription parameter is invalid. example here we see a function which handles an offer received from the remote peer. this code is derived from the example and tutorial in the article signaling and video calling; take a look at that for more details and a more in-depth explanation of what's going on. function handleoffer(msg) { createmypeerconnection(); mypeerconnection.setremotedescription(msg.description).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(str...
RTCRtpReceiver.getCapabilities() static function - Web APIs
you can, similarly, obtain the capabilities of rtcrtpsenders by calling the static function rtcrtpsender.getcapabilities(). syntax let rtpcapabilities = rtcrtpreceiver.getcapabilities(kind); parameters kind a domstring indicating the type of media for which you wish to get the device's capability to receive. all browsers support the primary media kinds: audio and video. ...
...ork when you actually try to use them. calling rtcrtpreceiver.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supp...
...oolean indicating whether or not the device supports receiving h.264 video on a webrtc connection. since rtcrtpreceiver.getcapabilities() actually only indicates probable support, attempting to receive h.264 video might still fail even after getting a positive response from this function. function canreceiveh264() { let capabilities = rtcrtpreceiver.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { return true; } }); return false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver.getcapabilities()' in that specification. candidate recommendation ...
RTCRtpSender.getCapabilities() static function - Web APIs
you can, similarly, obtain the capabilities of rtcrtpreceivers by calling the static function rtcrtpreceiver.getcapabilities(). syntax let rtpcapabilities = rtcrtpsender.getcapabilities(kind); parameters kind a domstring indicating the type of media for which you wish to get the sender's capability to receive. all browsers support the primary media kinds: audio and video. return value an rtcrtpcapabilities object stating what capabilities the browser has for sending the specified media kind over an rtcpeerconnection. ...
... work when you actually try to use them. calling rtcrtpsender.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supp...
...e the function below returns a boolean indicating whether or not the device supports sending h.264 video on an rtcrtpsender. since rtcrtpsender.getcapabilities() actually only indicates probable support, h.264 support might still fail even after getting a positive response from this function. function cansendh264() { let capabilities = rtcrtpsender.getcapabilities("video"); capabilities.codecs.foreach((codec) => { if (codec.mimetype === "video/h264") { return true; } }); return false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.getcapabilities()' in that specification. candidate recommendation ...
RTCRtpSender.replaceTrack() - Web APIs
with which to replace the rtcrtpsender's current source track. the new track's kind must be the same as the current track's, or the replace track request will fail. return value a promise which is fulfilled once the track has been successfully replaced. the promise is rejected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see things that require negotiation). if newtrack was omitted or was null, replacetrack() simply stops the sender. no negotiation is required in this case. when the promise is fulfilled, the fulfillment handler receives a value of undefined. exceptions if the returned promise is rejected, one of the following exceptions is provided to the rejection handler: invalidm...
...all track replacements require renegotiation. in fact, even changes that seem huge can be done without requiring negotation. here are the changes that can trigger negotiaton: the new track has a resolution which is outside the bounds of the bounds of the current track; that is, the new track is either wider or taller than the current one. the new track's frame rate is high enough to cause the codec's block rate to be exceeded. the new track is a video track and its raw or pre-encoded state differs from that of the original track. the new track is an audio track with a different number of channels fom the original. media sources that have built-in encoders — such as hardware encoders — may not be able to provide the negotiated codec. software sources may not implement the negotiated ...
...c's block rate to be exceeded. the new track is a video track and its raw or pre-encoded state differs from that of the original track. the new track is an audio track with a different number of channels fom the original. media sources that have built-in encoders — such as hardware encoders — may not be able to provide the negotiated codec. software sources may not implement the negotiated codec. examples switching video cameras // example to change video camera, suppose selected value saved into window.selectedcamera navigator.mediadevices .getusermedia({ video: { deviceid: { exact: window.selectedcamera } } }) .then(function(stream) { let videotrack = stream.getvideotracks()[0]; pcs.foreach(function(pc) { var sender = pc.getsenders(...
RTCRtpSender - Web APIs
properties rtcrtpsender.dtmf read only an rtcdtmfsender which can be used to send dtmf tones using telephone-event payloads on the rtp session represented by the rtcrtpsender object. ...
... properties rtcrtpsender.dtmf read only an rtcdtmfsender which can be used to send dtmf tones using telephone-event payloads on the rtp session represented by the rtcrtpsender object. ...
...eturns a rtcrtpparameters object describing the current configuration for the encoding and transmission of media on the track. rtcrtpsender.getstats() returns a promise which is fulfilled with a rtcstatsreport which provides statistics data for all outbound streams being sent using this rtcrtpsender. rtcrtpsender.setparameters() applies changes to parameters which configure how the track is encoded and transmitted to the remote peer. rtcrtpsender.setstreams() sets the mediastream(s) associated with the track being transmitted by this sender. rtcrtpsender.replacetrack() attempts to replace the track currently being sent by the rtcrtpsender with another track, without performing renegotiation. this method can be used, for example, to toggle between the front- and rear-facing cameras on a...
SVGImageElement.decoding - Web APIs
auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. ...
... auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. ...
... auto: default mode, which indicates no preference for the decoding mode. the browser decides what is best for the user. ...
ScriptProcessorNode.bufferSize - Web APIs
g both the input and output buffer size, in sample-frames. its value can be a power of 2 value in the range 256–16384. syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); value an integer. example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white nois...
... each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
... playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } ...
ScriptProcessorNode.onaudioprocess - Web APIs
t is dispatched to scriptprocessornode node types. an event of type audioprocessingevent will be dispatched to the event handler. syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); scriptnode.onaudioprocess = function() { ... } example the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white nois...
... each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...utton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); ...
ScriptProcessorNode - Web APIs
to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface: audioprocess fired when an input buffer of a scriptprocessornode is ready to be processed. also available via the onaudioprocess event handler property. examples the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode. for each channel and each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white nois...
... each sample frame, the scriptnode.onaudioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
... playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } ...
Sensor APIs - Web APIs
fficient for feature detection. the existence of an actual sensor must be confirmed as well. this is where defensive programming is needed. defensive programming requires three strategies. checking for thrown errors when instantiating a sensor object. listening for errors thrown during its use. handling the errors gracefully so that the user experience is enhanced rather than degraded. the code example below illustrates these principles. the try...catch block catches errors thrown during sensor instantiation. it implements a handler for sensor.onerror to catch errors thrown during use. the only time anything is shown to the user is when permissions need to be requested and when the sensor type isn't supported by the device. if a feature policy blocks use of a feature it is because you...
...xample below illustrates these principles. the try...catch block catches errors thrown during sensor instantiation. it implements a handler for sensor.onerror to catch errors thrown during use. the only time anything is shown to the user is when permissions need to be requested and when the sensor type isn't supported by the device. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. let accelerometer = null; try { accelerometer = new accelerometer({ referenceframe: 'device' }); accelerometer.addeventlistener('error', event => { // handle runtime errors. if (event.error.name === 'notallowe...
...et on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. let accelerometer = null; try { accelerometer = new accelerometer({ referenceframe: 'device' }); accelerometer.addeventlistener('error', event => { // handle runtime errors. if (event.error.name === 'notallowederror') { // branch to code for requesting permission. } else if (event.error.name === 'notreadableerror' ) { console.log('cannot connect to the sensor.'); } }); accelerometer.addeventlistener('reading', () => reloadonshake(accelerometer)); accelerometer.start(); } catch (error) { // handle construction errors. if (error.name === 'securityerror') { // see the note abov...
SpeechSynthesisErrorEvent.error - Web APIs
interrupted a speechsynthesis.cancel method call caused the speechsynthesisutterance to be interrupted after it had begun being spoken and before it completed. ...
... interrupted a speechsynthesis.cancel method call caused the speechsynthesisutterance to be interrupted after it had begun being spoken and before it completed. ...
... interrupted a speechsynthesis.cancel method call caused the speechsynthesisutterance to be interrupted after it had begun being spoken and before it completed. ...
SubtleCrypto.decrypt() - Web APIs
ey for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was an error decrypting the ciphertext). supported algorithms the decrypt() method supports the same algorithms as the encrypt() method. examples note: you can try the working examples on github. rsa-oaep this code decrypts ciphertext using rsa-oaep. see the complete code on github. function decryptmessage(privatekey, ciphertext) { return window.crypto.subtle.decrypt( { name: "rsa-oaep" }, privatekey, ciphertext ); } aes-ctr this code decrypts ciphertext using aes in ctr mode. note that counter must match the value that was used for encryption. see the complete code on github. ...
... privatekey, ciphertext ); } aes-ctr this code decrypts ciphertext using aes in ctr mode. note that counter must match the value that was used for encryption. see the complete code on github. function decryptmessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "aes-ctr", counter, length: 64 }, key, ciphertext ); } aes-cbc this code decrypts ciphertext using aes in cbc mode. note that iv must match the value that was used for encryption. see the complete code on github. function decryptmessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "aes-cbc", iv: iv }, key, ciphertext ); } aes-gcm this code decrypts ciphertext using aes in gcm mode. note that iv must match the value...
... that iv must match the value that was used for encryption. see the complete code on github. function decryptmessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "aes-cbc", iv: iv }, key, ciphertext ); } aes-gcm this code decrypts ciphertext using aes in gcm mode. note that iv must match the value that was used for encryption. see the complete code on github. function decryptmessage(key, ciphertext) { return window.crypto.subtle.decrypt( { name: "aes-gcm", iv: iv }, key, ciphertext ); } specifications specification status comment web cryptography apithe definition of 'subtlecrypto.decrypt()' in that specification. recommendation initial definition. ...
SubtleCrypto.deriveBits() - Web APIs
f the algorithm requested for the derived key doesn't define a key length. supported algorithms see the supported algorithms section of the derivekey() documentation. examples note: you can try the working examples on github. ecdh in this example alice and bob each generate an ecdh key pair. we then use alice's private key and bob's public key to derive a shared secret. see the complete code on github. async function derivesharedsecret(privatekey, publickey) { const sharedsecret = await window.crypto.subtle.derivebits( { name: "ecdh", namedcurve: "p-384", public: publickey }, privatekey, 128 ); const buffer = new uint8array(sharedsecret, 0, 5); const sharedsecretvalue = document.queryselector(".ecdh .derived-bits-value"); sharedsecretvalu...
...ntlistener("click", () => { // alice then generates a secret using her private key and bob's public key. // bob could generate the same secret using his private key and alice's public key. derivesharedsecret(aliceskeypair.privatekey, bobskeypair.publickey); }); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2. ...
...blickey); }); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2. see the complete code on github. let salt; /* get some key material to use as input to the derivebits method. the key material is a password supplied by the user. */ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user. */ async function getderivedbits() { const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const derivedbits = await window.crypto.s...
SubtleCrypto.generateKey() - Web APIs
ey algorithms). exceptions the promise is rejected when the following exception is encountered: syntaxerror raised when the result is a cryptokey of type secret or private but keyusages is empty. syntaxerror raised when the result is a cryptokeypair and its privatekey.usages attribute is empty. examples note: you can try the working examples on github. ...
...llowing exception is encountered: syntaxerror raised when the result is a cryptokey of type secret or private but keyusages is empty. syntaxerror raised when the result is a cryptokeypair and its privatekey.usages attribute is empty. examples note: you can try the working examples on github. rsa key pair generation this code generates an rsa-oaep encryption key pair. see the complete code on github. let keypair = window.crypto.subtle.generatekey( { name: "rsa-oaep", moduluslength: 4096, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256" }, true, ["encrypt", "decrypt"] ); elliptic curve key pair generation this code generates an ecdsa signing key pair. see the complete code on github. let keypair = window.crypto.subtle.generatekey( { name: ...
...slength: 4096, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256" }, true, ["encrypt", "decrypt"] ); elliptic curve key pair generation this code generates an ecdsa signing key pair. see the complete code on github. let keypair = window.crypto.subtle.generatekey( { name: "ecdsa", namedcurve: "p-384" }, true, ["sign", "verify"] ); hmac key generation this code generates an hmac signing key. see the complete code on github. let key = window.crypto.subtle.generatekey( { name: "hmac", hash: {name: "sha-512"} }, true, ["sign", "verify"] ); aes key generation this code generates an aes-gcm encryption key. see the complete code on github. let key = window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256 }, true, [...
Using Touch Events - Web APIs
abstract pointer creates a unified input model that can represent a contact point for a finger, pen/stylus or mouse. see the pointer events mdn article. the pointer event model can simplify an application's input processing since a pointer represents input from any input device. ...
...esent a contact point for a finger, pen/stylus or mouse. see the pointer events mdn article. the pointer event model can simplify an application's input processing since a pointer represents input from any input device. additionally, the pointer event types are very similar to mouse event types (for example, pointerdown pointerup) thus code to handle pointer events closely matches mouse handling code. ...
...ent types are very similar to mouse event types (for example, pointerdown pointerup) thus code to handle pointer events closely matches mouse handling code. the implementation status of pointer events in browsers is relatively high with chrome, firefox, ie11 and edge having complete implementations. examples and demos the following documents describe how to use touch events and include example code: touch events overview implement custom gestures introduction to touch events in javascript add touch screen support to your website (the easy way) touch event demonstrations: paint program (by rick byers) touch/pointer tests and demos (by patrick h. lauke) community touch events community group mail list w3c #touchevents irc channel related topics and resources pointer ev...
URL - Web APIs
Web › API › URL
it works by providing properties which allow you to easily read and modify the components of a url. you normally create a new url object by specifying the url as a string when calling its constructor, or by providing a relative url and a base url. you can then easily read the parsed components of the url or make changes to the url. if a browser doesn't yet support the url() constructor, you can access a url object using the window interface's window.url property. be sure to check to see if any of your target browsers require this to be prefixed. note: this feature is available in web workers. ...
...for instance: url.pathname = 'démonstration.html'; console.log(url.href); // "http://www.example.com/d%c3%a9monstration.html" the urlsearchparams interface can be used to build and manipulate the url query string. to get the search params from the current window's url, you can do this: // https://some.site/?id=123 const parsedurl = new url(window.l...
...erface can be used to build and manipulate the url query string. to get the search params from the current window's url, you can do this: // https://some.site/?id=123 const parsedurl = new url(window.location.href); console.log(parsedurl.searchparams.get("id")); // "123" the tostring() method of url just returns the value of the href property, so the constructor can be used to normalize and encode a url directly. const response = await fetch(new url('http://www.example.com/démonstration.html')); specifications specification status comment file apithe definition of 'url' in that specification. working draft added the static methods url.createobjecturl() and url.revokeobjecturl(). urlthe definition of 'api' in that specification. living stand...
URLUtilsReadOnly.hash - Web APIs
syntax string = object.hash; examples // in a web worker, on the page https://developer.mozilla.org/docs/urlutilsreadonly.hash#example var result = window.self.hash; // returns:'#hash' specifications specification status comment urlthe definition of 'urlutilsreadonly.hash' in that specification. living standard initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
...this has been fixed to match the spec.ie no support noopera no support nosafari no support nowebview android no support nochrome android no support nofirefox android ...
...this has been fixed to match the spec.opera android no support nosafari ios no support nosamsung internet android no support nolegend full support full support ...
URL API - Web APIs
Web › API › URL API
the url api is a component of the url standard, which defines what constitutes a valid uniform resource locator and the api that accesses and manipulates urls. the url standard also defines concepts such as domains, hosts, and ip addresses, and also attempts to describe in a standard way the legacy application/x-www-form-urlencoded mime type used to submit web forms' contents as a set of key/value pairs. url concepts and usage the majority of the url standard is taken up by the definition of a url and how it is structured and parsed. also covered are definitions of various terms related to addressing of computers on a network, and the algorithms for parsing ip addresses and dom addresses are specified. more interesting to most developers is the api itself. accessing url components creatin...
... most of the properties of url are settable; you can write new values to them to alter the url represented by the object. for example, to create a url and set its username: let myusername = "someguy"; let addr = new url("https://mysite.com/login"); addr.username = myusername; setting the value of username not only sets that property's value, but it updates the overall url. after executing the code snippet above, the value returned by addr.href is https://someguy@mysite.com/login. this is true for any of the writable properties. queries the search property on a url contains the query string portion of the url. for example, if the url is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. you can also look up the values of indi...
... other functions within urlsearchparams let you change the value of keys, add and delete keys and their values, and even sort the list of parameters. url api interfaces the url api is a simple one, with only a couple of interfaces to its name: url urlsearchparams older versions of the specification included an in...
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
the webglrenderingcontext method enablevertexattribarray(), part of the webgl api, turns on the generic vertex attribute array at the specified index into the list of attribute arrays. you can disable the attribute array by calling disablevertexattribarray(). in webgl, values that apply to a specific vertex are stored in attributes. these are only available to the javascript code and the vertex shader. attributes are referenced by an index number into the list of attributes maintained by the gpu. some vertex attribute indices may have predefined purposes, depending on the platform and/or the gpu. others are assigned by the webgl layer when you create the attributes. either way, since attributes cannot be used unless enabled, and are disabled by default, you need to call enablevertexattri...
...tion(). return value undefined. errors to check for errors after calling enablevertexattribarray(), call geterror(). webglrenderingcontext.invalid_value the specified index is invalid; that is, it's greater than or equal to the maximum number of entries permitted in the context's vertex attribute list, as indicated by the value of webglrenderingcontext.max_vertex_attribs. example this code — a snippet taken from the full example a basic 2d webgl animation example — shows the use of enablevertexarray() to activate the attribute that will be used by the webgl layer to pass individual vertexes from the vertex buffer into the vertex shader function. gl.bindbuffer(gl.array_buffer, vertexbuffer); avertexposition = gl.getattriblocation(shaderprogram, "avertexposition"); gl.enab...
... to pass individual vertexes from the vertex buffer into the vertex shader function. gl.bindbuffer(gl.array_buffer, vertexbuffer); avertexposition = gl.getattriblocation(shaderprogram, "avertexposition"); gl.enablevertexattribarray(avertexposition); gl.vertexattribpointer(avertexposition, vertexnumcomponents, gl.float, false, 0, 0); gl.drawarrays(gl.triangles, 0, vertexcount); this code snippet is taken from the function animatescene() in "a basic 2d webgl animation example." see that article for the full sample and to see the resulting animation in action. this code sets the buffer of vertexes that will be used to draw the triangles of the shape by calling bindbuffer(). then the vertex position attribute's index is obtained from the shader program by calling getattriblocation(...
WebGLRenderingContext.getUniformLocation() - Web APIs
then the three un...
...") gl.uniform2fv(uscalingfactor, currentscale); gl.uniform2fv(urotationvector, currentrotation); gl.uniform4fv(uglobalcolor, [0.1, 0.7, 0.2, 1.0]); this code snippet is taken from the function animatescene() in "a basic 2d webgl animation example." see that article for the full sample and to see the resulting animation in action. after setting the current shading program to shaderprogram, this code fetches the three uniforms "uscalingfactor", "uglobalcolor", and "urotationvector", calling getuniformlocation() once for each uniform. then the three uniforms' values are set: the uscalingfactor uniform — a 2-component vertex — receives the horizontal and vertical scaling factors from the variable currentscale. the uniform urotationvector is set to the contents of the variable currentro...
...component vertex. finally, the uniform uglobalcolor is set to the color [0.1, 0.7, 0.2, 1.0], the components in this 4-component vector represent the values of red, green, blue, and alpha, respectively. having done this, the next time the shading functions are called, their own variables named uscalingfactor, uglobalcolor, and urotationvector will all have the values provided by the javascript code. specifications specification status comment webgl 1.0the definition of 'getuniformlocation' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glgetuniformlocation' in that specification. standard man page of the opengl api. ...
WebGLShader - Web APIs
the webglshader is part of the webgl api and can either be a vertex or a fragment shader. a webglprogram requires both types of shaders. description to create a webglshader use webglrenderingcontext.createshader, then hook up the glsl source code using webglrenderingcontext.shadersource(), and finally invoke webglrenderingcontext.compileshader() to finish and compile the shader. at this point the webglshader is still not in a usable form and must still be attached to a webglprogram. ...
... of shaders. description to create a webglshader use webglrenderingcontext.createshader, then hook up the glsl source code using webglrenderingcontext.shadersource(), and finally invoke webglrenderingcontext.compileshader() to finish and compile the shader. at this point the webglshader is still not in a usable form and must still be attached to a webglprogram. function createshader (gl, sourcecode, type) { // compiles either a shader of type gl.vertex_shader or gl.fragment_shader var shader = gl.createshader( type ); gl.shadersource( shader, sourcecode ); gl.compileshader( shader ); if ( !gl.getshaderparameter(shader, gl.compile_status) ) { var info = gl.getshaderinfolog( shader ); throw 'could not compile webgl program. \n\n' + info; } return shader; } see webglpr...
... gl.compileshader( shader ); if ( !gl.getshaderparameter(shader, gl.compile_status) ) { var info = gl.getshaderinfolog( shader ); throw 'could not compile webgl program. \n\n' + info; } return shader; } see webglprogram for information on attaching the shaders. examples creating a vertex shader note that there are many other strategies for writing and accessing shader source code strings. these example are for illustration purposes only. var vertexshadersource = 'attribute vec4 position;\n' + 'void main() {\n' + ' gl_position = position;\n' + '}\n'; //use the createshader function from the example above var vertexshader = createshader(gl, vertexshadersource, gl.vertex_shader) creating a fragment shader var fragmentshadersource = 'void main() {\n' + ' gl...
WebGL by example - Web APIs
vanced levels. instead of trying to juggle shaders, geometry, and working with gpu memory, already in the first program, the examples here explore webgl in an incremental way. we believe that it leads to a more effective learning experience and ultimately a deeper understanding of the underlying concepts. 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 click...
...color masking and thus limiting the range of displayed colors to specific shades. basic scissoring how to draw simple rectangles and squares with scissoring operations. canvas size 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 ...
...tion fun with scissoring and clearing operations. raining rectangles a simple game that demonstrates clearing with solid colors, scissoring, animation, and user interaction. shader programming basics hello glsl a very basic shader program that draws a solid color square. hello vertex attributes combining shader programming and user interaction through vertex attributes. textures from code a simple demonstration of procedural texturing with fragment shaders. miscellaneous advanced examples video textures this example demonstrates how to use video files as textures. next » ...
Data in WebGL - Web APIs
Web › API › WebGL API › Data
shader programs have access to three kinds of data storage, each of which has a specific use case. each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's javascript code, depending on the specific type of variable. glsl data types <<document the basic types, vectors, etc; see data type (glsl) on the khronos webgl wiki>> glsl variables there are three kinds of "variable" or data storage available in glsl, each of which with its own purpose and use cases: attributes, varyings, and uniforms. attributes attributes are glsl variables which are only available to the vertex shader (as variables) and the javascript code. attributes are typically used to store color information, texture coordinates, and a...
...ilable in glsl, each of which with its own purpose and use cases: attributes, varyings, and uniforms. attributes attributes are glsl variables which are only available to the vertex shader (as variables) and the javascript code. attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the javascript code and the vertex shader. //init colors var vertexcolors = [ vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( ...
...array( vcolor ); //glsl attribute vec4 vcolor; void main() { fcolor = vcolor; } varyings varyings are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader. this is commonly used to share a vertex's normal vector after it has been computed by the vertex shader. <<how to use>> uniforms uniforms are set by the javascript code and are available to both the vertex and fragment shaders. they're used to provide values that will be the same for everything drawn in the frame, such as lighting positions and magnitudes, global transformation and perspective details, and so forth. <<add details>> buffers <<add information>> textures <<add information>> ...
A simple RTCDataChannel sample - Web APIs
text" inputmode="latin" size=60 maxlength=120 disabled> </label> <button id="sendbutton" name="sendbutton" class="buttonright" disabled> send </button> </div> finally, there's the little box into which we'll insert the messages. this <div> block will be the second peer. <div class="messagebox" id="receivebox"> <p>messages received:</p> </div> the javascript code while you can just look at the code itself on github, below we'll review the parts of the code that do the heavy lifting. the webrtc api makes heavy use of promises. they make it very easy to chain the steps of the connection process together; if you haven't already read up on this functionality of ecmascript 2015, you should read up on them. similarly, this example uses arrow functions to simp...
...gain, this would normally be exchanged through a signalling server. finally, the local connection's remote description is set to refer to the remote peer by calling localconnection's rtcpeerconnection.setremotedescription(). the catch() calls a routine that handles any errors that occur. note: once again, this process is not a real-world implementation; in normal usage, there's two chunks of code running on two machines, interacting and negotiating the connection. a side channel, commonly called a “signalling server,” is usually used to exchange the description (which is in application/sdp form) between the two peers. handling successful peer connection as each side of the peer-to-peer connection is successfully linked up, the corresponding rtcpeerconnection's icecandidate event is...
... ...
Using WebRTC data channels - Web APIs
elow for more information. creating a data channel the underlying data transport used by the rtcdatachannel can be created in one of two ways: let webrtc create the transport and announce it to the remote peer for you (by causing it to receive a datachannel event). this is the easy way, and works for a wide variety of use cases, but may not be flexible enough for your needs. write your own code to negotiate the data transport and write your own code to signal to the other peer that it needs to connect to the new channel. let's look at each of these cases, starting with the first, which is the most common. automatic negotiation often, you can allow the peer connection to handle negotiating the rtcdatachannel connection for you. to do this, simply call createdatachannel() without spe...
...ote peer that it should create its own rtcdatachannel with the negotiated property also set to true, using the same id. this will link the two objects across the rtcpeerconnection. let datachannel = pc.createdatachannel("myapp channel", { negotiated: true }); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); requestremotechannel(datachannel.id); in this code snippet, the channel is created with negotiated set to true, then a function called requestremotechannel() is used to trigger negotiation, to create a remote channel with the same id as the local channel. doing this lets you create data channels with each peer using different properties, and to create channels declaratively by simply using the same value for id. buffering webrtc data channels ...
...ntlow here>>> ... understanding message size limits for any data being transmitted over a network, there are size restrictions. at a fundamental level, the individual network packets can't be larger than a certain value (the exact number depends on the network and the transport layer being used). at the application level—that is, within the user agent's implementation of webrtc on which your code is running—the webrtc implementation implements features to support messages that are larger than the maximum packet size on the network's transport layer. this can complicate things, since you don't necessarily know what the size limits are for various user agents, and how they respond when a larger message is sent or received. even when user agents share the same underlying library for handl...
Improving compatibility using WebRTC adapter.js - Web APIs
while the webrtc specification is relatively stable, not all browsers have fully implemented all of its features. in addition, some browsers still have prefixes on some or all webrtc apis. while you can manually code around these issues, there is an easier way. the webrtc organization provides on github the webrtc adapter to work around compatibility issues in different browsers' webrtc implementations. the adapter is a javascript shim which lets your code to be written to the specification so that it will "just work" in all browsers with webrtc support. there's no need to conditionally use prefixed apis or implement other workarounds. note: since there is ongoing fluidity in functionality and naming of api terms in webrtc and supporting browsers, use of this adapter is generally recommende...
... functionality and naming of api terms in webrtc and supporting browsers, use of this adapter is generally recommended. the adapter is provided under a bsd-style license. what adapter.js does for each version of each browser that supports webrtc, adapter.js implements the needed polyfills, establishes the non-prefixed names of apis, and applies any other changes needed to make the browser run code written to the webrtc specification. for example, on firefox versions older than 38, the adapter adds the rtcpeerconnection.urls property; firefox doesn't natively support this property until firefox 38, while on chrome, the adapter adds support for the promise based api is added if it's not present. these are just a couple of examples; there are of course other adjustments made for you by the s...
...ox, google chrome, apple safari, and microsoft edge. using adapter.js in order to use adapter.js, you need to include adapter.js on any page that uses webrtc apis: download a copy of the latest version of adapter.js from github. place it in your site's directory structure (such as in your scripts directory). include adapter.js in your project: <script src="adapter.js"></script> write your code, using webrtc apis per the specification, knowing that your code should work on all browsers. keep in mind that even a good shim like this one doesn't mean you don't need to test your code on different browsers (and ideally different versions of each browser). ...
Writing WebSocket client applications - Web APIs
creating a websocket object in order to communicate using the websocket protocol, you need to create a websocket object; this will automatically attempt to open the connection to the server. ...
...rror occurs while attempting to connect, first a simple event with the name error is sent to the websocket object (thereby invoking its onerror handler), and then the closeevent is sent to the websocket object (thereby invoking its onclose handler) to indicate the reason for the connection's closing. the browser may also output to its console a more descriptive error message as well as a closing code as defined in rfc 6455, section 7.4 through the closeevent. examples this simple example creates a new websocket, connecting to the server at wss://www.example.com/socketserver. a custom protocol of "protocolone" is named in the request for the socket in this example, though this can be omitted. var examplesocket = new websocket("wss://www.example.com/socketserver", "protocolone"); on return...
...g for incoming data, you can do something like this: examplesocket.onmessage = function (event) { console.log(event.data); } receiving and interpreting json objects let's consider the chat client application first alluded to in using json to transmit objects. ...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
there's no magic object provided by either the webgl or the webxr api that represents the viewer that you can simply rotate and move around to automatically change what's seen on the screen. in this guide we show how use webgl to simulate camera movements without having a camera to move. these techniques can be used in any webgl (or webxr) project. ...
...ines that make it much easier to perform not only core matrix and other operations, but often also to simulate these standard cinematography techniques. you should strongly consider using one instead of directly using webgl. this guide uses webgl directly since it's useful to understand to some extent what goes on under the hood, and to aide in the development of libraries or to help you optimize code. reminder: even though we use phrases like "move the camera," what we're really doing is moving the entire world around the camera. this affects the way certain values work, which will be noted as they come up below. zooming among the best known camera effects is the zoom. zooming is performed in a physical camera by altering the focal length of the lens; this is the distance between the cen...
...ght. the xr device then uses screens and lenses to present the left half of the produced image to our left eye and the right half to our right eye. for example, consider a device which uses a 2560x1440 pixel frame buffer. dividing this into two parts—half for each eye—results in each eye's view being drawn at a resolution of 1280x1440 pixels. here's what that looks like conceptually: your code tells the webxr engine that you want to provide the next animation frame by calling the xrsession method requestanimationframe(), providing a callback function that renders a frame of animation. when the browser needs you to render the scene, it invokes the callback, providing as input parameters the current time and an xrframe encapsulating the data needed to render the correct frame. this info...
Fundamentals of WebXR - Web APIs
e webvr relied on the gamepad api to support the controllers. in webxr, the primary select and squeeze actions are directly supported using events, while other controls are available through a special webxr-specific implementation of the gamepad object. basic concepts before getting into too much detail, let's consider some basic concepts that you need to know before you learn how to develop xr code. field of view the term field of view (fov) is one which applies to any visual technology, from old film cameras to modern digital video cameras, including the cameras in computers and mobile devices. what is field of view? the field of view is, at its essence, the extent of the environment you are able to see at any one time. the width of the field of view is measured as the angle defining t...
...sessions, using the same api. which type of session you want to create is specified when creating the session. this is done by specifying the appropriate session mode string 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 f...
... that are built atop webgl to make it more convenient to use. a particular benefit to using a framework rather than directly using the webgl api is that libraries tend to implement virtual camera functionality. opengl (and thus webgl by extension) does not directly offer a camera view, using a library that simulates one on your behalf can make your job much, much easier, especially when building code that allows free movement through your virtual world. since webgl is used for rendering the 3d world into the webxr session, you should first be familiar with webgl's general usage, and with the basics of 3d graphics in general. general-purpose 3d frameworks these frameworks are good for general-purpose programming as well as for game development when you want to do the logic yourself. they're...
WebXR Device API - Web APIs
ct through which the entire webxr device api is then exposed. navigator.xr read only this property, added to the navigator interface, returns the xrsystem object through which the webxr api is exposed. if this property is missing or null, webxr is not available. webxr interfaces xr the navigator.xr property returns the window's instance of xrsystem, which is the mechanism by which your code accesses the webxr api. using the xrsystem interface, you can create xrsessions to represent actual ar and/or vr sessions. xrframe while presenting an xr session, the state of all tracked objects which make up the session are represented by an xrframe. to get an xrframe, call the session's requestanimationframe() method, providing a callback which will be called with the xrframe once available.
...on the web, including both for css transforms and for webgl purposes, as well as to handle the positioning and orientation of objects in webxr contexts. webxr application life cycle an overview of the overall life cycle of a webxr application, from startup to shutdown. this article serves as an introduction to the basics of what's involved in creating a webxr experience without diving into the code in detail. it's a good way to prepare for the next steps. creating a mixed reality experience starting up and shutting down a webxr session before actually presenting a scene using an xr device such as a headset or goggles, you need to create a webxr session bound to a rendering layer that draws the scene for presentation in each of the xr device's displays so that the 3d effect can be pres...
... how to create the illusion of moving a viewer through a world in which the viewer doesn't really move. lighting a webxr setting since webxr rendering is based upon webgl, the same lighting techniques used for any 3d application are applied to webxr scenes. however, there are issues specific to creating augmented and virtual reality settings that need to be considered when writing your lighting code. this article discusses those issues. using bounded reference spaces in this article, we examine how to use a bounded-floor reference space to define the boundaries of where the viewer can safely move about without leaving the area tracked by their xr hardware or colliding with a physical obstacle. on devices which support it, bounded-floor can be a useful tool in your repertoire. making it i...
Using the Web Speech API - Web APIs
ge the background color of the app.</p> <div> <p class="output"><em>...diagnostic messages</em></p> </div> the css provides a very simple responsive styling so that it looks ok across devices. javascript let's look at the javascript in a bit more detail. ...
...the following variable is defined to hold our grammar: var colors = [ 'aqua' , 'azure' , 'beige', 'bisque', 'black', 'blue', 'brown', 'chocolate', 'coral' ... ]; var grammar = '#jsgf v1.0; grammar colors; public <color> = ' + colors.join(' | ') + ' ;' the grammar format used is jspeech grammar format (jsgf) — you can find a lot more about it a...
...ction(event) { var char = event.utterance.text.charat(event.charindex); console.log('speech paused at character ' + event.charindex + ' of "' + event.utterance.text + '", which is "' + char + '".'); } finally, we call blur() on the text input. this is mainly to hide the keyboard on firefox os. inputtxt.blur(); } updating the displayed pitch and rate values the last part of the code simply updates the pitch/rate values displayed in the ui, each time the slider positions are moved. pitch.onchange = function() { pitchvalue.textcontent = pitch.value; } rate.onchange = function() { ratevalue.textcontent = rate.value; } ...
Web Workers API - Web APIs
ead separate from the main execution thread of a web application. the advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the ui) thread to run without being blocked/slowed down. web workers concepts and usage a worker is an object created using a constructor (e.g. worker()) that runs a named javascript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. this context is represented by either a dedicatedworkerglobalscope object (in the case of dedicated workers - workers that are utilized by a single script), or a sharedworkerglobalscope (in the case of shared workers - workers that are shared between multiple scripts). you can run...
... run in the worker thread; workers run in another global context that is different from the current window. this context is represented by either a dedicatedworkerglobalscope object (in the case of dedicated workers - workers that are utilized by a single script), or a sharedworkerglobalscope (in the case of shared workers - workers that are shared between multiple scripts). you can run whatever code you like inside the worker thread, with some exceptions. for example, you can't directly manipulate the dom from inside a worker, or use some default methods and properties of the window object. but you can use a large number of items available under window, including websockets, and data storage mechanisms like indexeddb. see functions and classes available to workers for more details. data is...
...e inside a web worker context. note: as per the web workers spec, worker error events should not bubble (see bug 1188141. this has been implemented in firefox 42. web worker interfaces abstractworker abstracts properties and methods common to all kind of workers (i.e. worker or sharedworker). worker represents a running worker thread, allowing you to pass messages to the running worker code. workerlocation defines the absolute location of the script executed by the worker. sharedworker represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers. workerglobalscope represents the generic scope of any worker (doing the same job as window does for normal web content). different types of worker have scope ...
Window.content - Web APIs
Web › API › Window › content
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. note: since firefox 57 (initially nightly-only), both the content and _content variants are only available to chrome (privileged) code, and not available to the web anymore. returns a window object for the primary content window. this is useful in xul windows that have a <browser> (or tabbrowser or <iframe>) with type="content-primary" attribute on it — the most famous example is firefox main window, browser.xul. in such cases, content returns a reference to the window object for the document currently displayed in the brows...
...in the browser. it is a shortcut for browserref.contentwindow. in unprivileged content (webpages), content is normally equivalent to top (except in the case of a webpage loaded in a sidebar, content still refers to the window of the currently selected tab). note: some examples use _content instead of content. the former has been deprecated for a long time, and you should use content in any new code. syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none. see also working with windows in chrome...
... syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none. see also working with windows in chrome code when accessing content documents from privileged code, be aware of xpcnativewrappers. ...
Window.event - Web APIs
Web › API › Window › event
note: this property can be fragile, in that there may be situations in which the returned event is not the expected value. in addition, window.event is not accurate for events dispatched within shadow trees. ...
... note: this property can be fragile, in that there may be situations in which the returned event is not the expected value. in addition, window.event is not accurate for events dispatched within shadow trees. ...
... note: this property can be fragile, in that there may be situations in which the returned event is not the expected value. in addition, window.event is not accurate for events dispatched within shadow trees. ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
the queuemicrotask() method, which is exposed on the window or worker interface, queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. the microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop. this lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. you can learn more about how to use microtasks and why you might choose to do so in our microtask guide. the importance of microtasks comes in its ability to p...
...pt with queuemicrotask() for more details. microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. queuemicrotask() is exposed on the windoworworkerglobalscope mixin. syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to call your code. enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. return value undefined. examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[u...
...it creates a microtask by using a promise that resolves immediately. if (typeof window.queuemicrotask !== "function") { window.queuemicrotask = function (callback) { promise.resolve() .then(callback) .catch(e => settimeout(() => { throw e; })); // report exceptions }; } specifications speci...
Worker.prototype.postMessage() - Web APIs
ransfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to. transferable objects are instances of classes like arraybuffer, messageport or imagebitmap objects that can be transferred. null is not an acceptable value for transfer. returns void. example the following code snippet shows the creation of a worker object using the worker() constructor. when either of two form inputs (first and second) have their values changed, change events invoke postmessage() to send the value of both inputs to the current worker. var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted...
...e ourbasic dedicated worker example (run dedicated worker). note: postmessage() can only send a single object at once. as seen above, if you want to pass multiple values you can send an array. transfer example this example shows a firefox add-on that transfers an arraybuffer from the main thread to the chromeworker, and then the chromeworker transfers it back to the main thread. ...
...); console.info('arrbuf.bytelength pre transfer:', arrbuf.bytelength); myworker.postmessage( { atopic: 'do_sendworkerarrbuff', abuf: arrbuf // the array buffer that we passed to the transferrable section 3 lines below }, [ arrbuf // the array buffer we created 9 lines above ] ); console.info('arrbuf.bytelength post transfer:', arrbuf.bytelength); worker code self.onmessage = function (msg) { switch (msg.data.atopic) { case 'do_sendworkerarrbuff': sendworkerarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } function sendworkerarrbuff(abuf) { console.info('from worker, pre send back abuf.bytelength:', abuf.bytelength); self.post...
WorkerGlobalScope - Web APIs
online fired when the browser has gained access to the network and the value of navigator.online switched to true. also available via the workerglobalscope.ononline property. languagechange fired at the global/worker scope object when the user's preferred languages change. also available via the workerglobalscope.onlanguagechange property. close is an eventhandler representing the code to be called when the close event is raised. also available via the workerglobalscope.onclose property. rejectionhandled an event handler for handled promise rejection events. also available via the workerglobalscope.onrejectionhandled property. unhandledrejection an event handler for unhandled promise rejection events. also available via the workerglobalscope.onunhandledrejection prop...
...e scripts into the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); non-standard methods workerglobalscope.dump() allows you to write a message to stdout — i.e. in your terminal. this is the same as firefox's window.dump, but for workers. methods implemented from elsewhere windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated execution set using windoworworkerglobalscope.setinterval(). windoworworkerglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobals...
...loop, effectively closing this particular scope. in newer browser versions, close() is available on dedicatedworkerglobalscope and sharedworkerglobalscope instead. this change was made to stop close() being available on service workers, as it isn't supposed to be used there and always throws an exception when called (see bug 1336043). example you won't access workerglobalscope directly in your code; however, its properties and methods are inherited by more specific global scopes such as dedicatedworkerglobalscope and sharedworkerglobalscope. for example, you could import another script into the worker and print out the contents of the worker scope's navigator object using the following two lines: importscripts('foo.js'); console.log(navigator); since the global scope of the worker script...
HTML in XMLHttpRequest - Web APIs
dom using xmlhttprequest. to get an overview of how to use xmlhttprequest in general, see using xmlhttprequest. limitations to discourage the synchronous use of xmlhttprequest, html support is not available in the synchronous mode. also, html support is only available if the responsetype property has been set to "document". this limitation avoids wasting time parsing html uselessly when legacy code uses xmlhttprequest in the default mode to retrieve responsetext for text/html resources. also, this limitation avoids problems with legacy code that assumes that responsexml is null for http error pages (which often have a text/html response body). usage retrieving an html resource as a dom using xmlhttprequest works just like retrieving an xml resource as a dom using xmlhttprequest, except yo...
...iew on jsfiddle character encoding if the character encoding is declared in the http content-type header, that character encoding is used. failing that, if there is a byte order mark, the encoding indicated by the byte order mark is used. failing that, if there is a <meta> element that declares the encoding within the first 1024 bytes of the file, that encoding is used. ...
...ding within the first 1024 bytes of the file, that encoding is used. otherwise, the file is decoded as utf-8. handling html on older browsers xmlhttprequest originally supported only xml parsing. html parsing support is a recent addition. ...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
here is a an example javascript function that prints the security details of an xmlhttprequest sent over ssl. the function is passed the channel property of an xmlhttprequest to extract the following information: was the connection secure? was the used ssl certificate valid and what are its details (owner, expiration, certificate authority, etc.)? notes: this code requires elevated privileges to run; you can only call it from a browser extension or from a xulrunner application. the channel property becomes available only after the request is sent and the connection was established, that is, on readystate loaded, interactive or completed. by setting the mozbackgroundrequest property of the request object and modifying the example appropriately, you can create your own alert dial...
... try { errorclass = nsserrorsservice.geterrorclass(status); } catch (ex) { //catching security protocol exception errorclass = 'securityprotocol'; } if (errorclass == nsinsserrorsservice.error_class_bad_cert) { errtype = 'securitycertificate'; } else { errtype = 'securityprotocol'; } ...
...pterror'; break; default: errname = 'networkerror'; break; } } // xxx we have no tcperror implementation right now because it's really hard to // do on b2g18. on mozilla-central we want a proper tcperror that ideally // sub-classes domerror. bug 867872 has been filed to implement this and // contains a documented tcperror.webidl that maps all the error codes we use in // this file to slightly more readable explanations. let error = cc["@mozilla.org/dom-error;1"].createinstance(ci.nsidomdomerror); error.wrappedjsobject.init(errname); return error; // xxx: errtype goes unused } function dumpsecurityinfo(xhr, error) { let channel = xhr.channel; try { dump("connection status:\n"); if (!error) { dump("\tsucceeded\n"); ...
XMLHttpRequest.sendAsBinary() - Web APIs
nary data and should now be used instead. this method makes it possible to read and upload any type of file and to stringify the raw data. warning: this method is obsolete and should not be used. you should instead simply use the send() method, which now supports binary data in various forms. syntax xmlhttprequest.sendasbinary(binarystring); parameters binarystring a domstring which encodes the binary content to be sent. you can create the binary string using the filereader method readasbinarystring(). the string is converted to binary for transfer by removing the high-order byte of each character. return value undefined. polyfill since sendasbinary() is an experimental feature, here is a polyfill for browsers that don't support the sendasbinary() method but support typed arra...
... |*| :: xmlhttprequest.prototype.sendasbinary() polyfill :: |*| |*| https://developer.mozilla.org/docs/dom/xmlhttprequest#sendasbinary() |*| \*/ if (!xmlhttprequest.prototype.sendasbinary) { xmlhttprequest.prototype.sendasbinary = function (sdata) { var nbytes = sdata.length, ui8data = new uint8array(nbytes); for (var nidx = 0; nidx < nbytes; nidx++) { ui8data[nidx] = sdata.charcodeat(nidx) & 0xff; } /* send as arraybufferview...: */ this.send(ui8data); /* ...or as arraybuffer (legacy)...: this.send(ui8data.buffer); */ }; } note: it's possible to build this polyfill putting two types of data as argument for send(): an arraybuffer (ui8data.buffer – the commented code) or an arraybufferview (ui8data, which is a typed array of 8-bit unsigned integers – un...
... 0xff; } /* send as arraybufferview...: */ this.send(ui8data); /* ...or as arraybuffer (legacy)...: this.send(ui8data.buffer); */ }; } note: it's possible to build this polyfill putting two types of data as argument for send(): an arraybuffer (ui8data.buffer – the commented code) or an arraybufferview (ui8data, which is a typed array of 8-bit unsigned integers – uncommented code). however, on google chrome, when you try to send an arraybuffer, the following warning message will appear: arraybuffer is deprecated in xmlhttprequest.send(). use arraybufferview instead. another possible approach to send binary data is the stringview non native typed arrays superclass in conjunction with the send() method. ...
Web APIs
Web › API
below is a list of all the apis and interfaces (object types) that you may be able to use while developing your web app or site. web apis are typically used with javascript, although this doesn't always have to be the case. specifications this is a list of all the apis that are available. ...
...le rtciceserver rtcicetcpcandidatetype rtcicetransport rtcicetransportstate rtcidentityassertion rtcidentityerrorevent rtcidentityevent rtcinboundrtpstreamstats rtcnetworktype rtcofferansweroptions rtcofferoptions rtcoutboundrtpstreamstats rtcpeerconnection rtcpeerconnectioniceerrorevent rtcpeerconnectioniceevent rtcremoteoutboundrtpstreamstats rtcrtcpparameters rtcrtpcapabilities rtcrtpcodeccapability rtcrtpcodecparameters rtcrtpcontributingsource rtcrtpencodingparameters rtcrtpparameters rtcrtpreceiveparameters rtcrtpreceiver rtcrtpsendparameters rtcrtpsender rtcrtpstreamstats rtcrtpsynchronizationsource rtcrtptransceiver rtcrtptransceiverdirection rtcrtptransceiverinit rtcsctptransport rtcsessiondescription rtcsessiondescriptioncallback rtcstats rtcstatsicecandidatepairstate...
...recognitionresultlist speechsynthesis speechsynthesiserrorevent speechsynthesisevent speechsynthesisutterance speechsynthesisvoice staticrange stereopannernode storage storageestimate storageevent storagemanager storagequota stylepropertymap stylepropertymapreadonly stylesheet stylesheetlist submitevent subtlecrypto syncevent syncmanager t taskattributiontiming text textdecoder textencoder textmetrics textrange texttrack texttrackcue texttracklist timeevent timeranges touch touchevent touchlist trackdefault trackdefaultlist trackevent transferable transformstream transitionevent treewalker typeinfo u uievent ulongrange url urlsearchparams urlutilsreadonly usb usbalternateinterface usbconfiguration usbdevice usbendpoint usbintransferresult usbinterfac...
Using the alert role - Accessibility
hether it's speech or braille) and immediately announce or display the alert message. screen magnifiers may visually indicate that an alert occurred and what the alert text was. note: opinons may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: adding the role in the html code the snippet below shows how the alert role is added directly into the html source code. the moment the element finishes loading the screen reader should be notified of the alert. if the element was already in the original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title. <h2 role="alert">your form could not be submitted beca...
...ynamically creates an element with an alert role and adds it to the document structure. let myalert = document.createelement("p"); myalert.setattribute("role", "alert"); let myalerttext = document.createtextnode("you must agree with our terms of service to create an account."); myalert.appendchild(myalerttext); document.body.appendchild(myalert); note: the same result can be achieved with less code when using a script library like jquery: $("<p role='alert'>you must agree with our terms of service to create an account.</p>").appendto(document.body); example 3: adding alert role to an existing element sometimes it's useful to add an alert role to an element that is already visible on the page rather than creating a new element. this allows the developer to reiterate information that has ...
...ent that is already visible on the page rather than creating a new element. this allows the developer to reiterate information that has become more relevant or urgent to the user. for example, a form control may have instruction about the expected value. if a different value is entered, role="alert can be added to the instruction text so that the screen reader announces it as an alert. ...
ARIA: button role - Accessibility
th type="button" should be used for buttons: <button id="savechanges">save</button> note: if using role="button" instead of the semantic <button> or <input type="button"> elements, you will need to make the element focusable and have to define event handlers for click and keydown events, including the enter and space keys, in order to process the user's input. see the official wai-aria example code. description the button role identifies an element as a button to screen readers. a button is a widget used to perform actions such as submitting a form, opening a dialog, cancelling an action, or performing a command such as inserting a new record or displaying information. a common convention to inform users a button will launch a dialog is to append "…" (ellipsis) to the button's label, ...
... false and back again. html <button type="button" onclick="handlebtnclick()" onkeydown="handlebtnkeydown()"> mute audio </button> <span role="button" tabindex="0" aria-pressed="false" onclick="handlebtnclick(event)" onkeydown="handlebtnkeydown(event)"> mute audio </span> <audio id="audio" src="https://udn.realityripple.com/samples/41/191d072707.mp3"> your browser does not support the <code>audio</code> element. </audio> css button, [role="button"] { padding: 3px; border: 2px solid transparent; } button:active, button:focus, [role="button"][aria-pressed="true"] { border: 2px solid #000; } javascript function handlebtnclick(event) { togglebutton(event.target); } function handlebtnkeydown(event) { // check to see if space or enter were pressed if (event.key ...
...ications (wai-aria) 1.1the definition of 'button' in that specification. recommendation wai-aria authoring practicesthe definition of 'button' in that specification. working draft notes aria attributes used button aria-pressed aria-expanded aria-haspopup additional resources strong native semantics in html5 notes on using aria in html official wai-aria example code aria menubutton role ...
Cognitive accessibility - Accessibility
guided by four principles: websites must be perceivable, operable, understandable, and robust. to this end, they define 17 specific guidelines, of which six are especially relevant for cognitive accessibility. all of the following guidelines help more than just people with cognitive disabilities. for example, being able to extend the expiration time on an application requiring an authentication code sent to a mobile device via text message helps with the following scenarios: people with attention or anxiety disorders. people who have a poor short-term memory, or who are multitasking. people who are less technologically literate. people who have poor wireless reception. people who have motor control issues. adaptability guideline 1.3 states "content should be adaptable." create cont...
...to request content updates rather than updating automatically. also, enable a way to make nonessential alerts optional. ensure that people can continue an activity without loss of data after re-authenticating an expired session, for example, saving the state of a questionnaire. make sure to save data in such a way that it can be modified after a user re-authenticates. before re-authenticating, encode the data as hidden or encrypted. providing warnings about inactivity that could result in data loss. when a timeout is used, tell people exactly how much time will cause the session to time out and result in lost data. the exception to this is preserving data for more than 20 hours when no actions are taken. navigation guideline 2.4 states "provide ways to help users navigate, find content, a...
...<fieldset>, and <legend> elements to do so. labels should be descriptive and positioned close to the input they relate to. when requiring a specific format for input, provide an example formatted in the proper way. additionally, consider performing server-side validation to help format input data, to aid in the ease of user input. if a form control is required, indicate it both visually and via code. if a form control changes context, describe what will happen in a way that the user will understand it before they cause the context change to happen. error suggestion provide suggested input to the user if an input error is automatically detected and suggestions for correction are known (unless doing so would jeopardize the security or purpose of the content). prevent catastrophes...
@font-face - CSS: Cascading Style Sheets
computer. to provide the browser with a hint as to what format a font resource is — so it can select a suitable one — it is possible to include a format type inside a format() function: src: url(ideal-sans-serif.woff) format("woff"), url(basic-sans-serif.ttf) format("truetype"); the available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg". unicode-range the range of unicode code points to be used from the font. description if the local() function is provided, specifying a font name to look for on the user's computer, and the user agent finds a match, that local font is used. otherwise, the font resource specified using the url() function is downloaded and used. by allowing authors to provide their own fonts, @font-face makes it possib...
...tion. @font-face cannot be declared within a css selector. ...
...e cannot be declared within a css selector. ...
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
ted in an experimental way in several web browsers. at the time the method of creating experimental implementations was to use a vendor prefix. the idea of these prefixes was to allow implementations of the spec to be tested and explored by browser engineers and web developers alike without clashing with other implementations. the idea was not to use the experimental implementations in production code. however, prefixes ultimately were used in production code, and changes to the experimental specification caused people to need to update their sites to keep up. in 2009, the specification looked quite different. to create a flex container you would use display: box and there were a number of box-* properties, which did things that you will recognise from flexbox today. there was an update to t...
... property. use of vertical-align enables vertical alignment prior to flexbox. the property is ignored by flexbox and so you can use it in conjunction with display: table-cell or display: inline-block as a fallback and then safely use box alignment properties in flexbox instead. feature queries and flexbox you can use feature queries to detect flexbox support: @supports (display: flex) { // code for supporting browsers } note that internet explorer 11 does not support feature queries yet does support flexbox. if you decide the ie11 implementation is too buggy and you wish to serve it the fallback layout then you could use feature queries to serve flexbox rules only to those browsers with good flexbox support. remember that if you want to include versions of browsers that had vendor-pref...
...box rules only to those browsers with good flexbox support. remember that if you want to include versions of browsers that had vendor-prefixed flexbox you would need to include the prefixed version in your feature query. the following feature query would include uc browser, which supports feature queries and old flexbox syntax, prefixed: @supports (display: flex) or (display: -webkit-box) { // code for supporting browsers } for more information about using feature queries see using feature queries in css on the mozilla hacks blog. conclusion while i’ve spent some time in this guide going through potential issues and fallbacks, flexbox is very much ready for you to be using in production work. this guide will help you in those cases where you do come across an issue or have the requirem...
OpenType font features guide - CSS: Cascading Style Sheets
to use the standard properties shown above wherever possible. there a huge number of possible features. you can see examples of a number of them above, and there are several resources available for finding more of them. ...
...own above wherever possible. there a huge number of possible features. you can see examples of a number of them above, and there are several resources available for finding more of them. ...
...2sc"; } according to the specification you can either supply just the 4-character feature code or supply a 1 following the code (for enabling that feature) or a 0 (zero) to disable it. this is helpful if you have a feature like ligatures enabled by default but you would like to turn them off, like so: .no-ligatures { font-feature-settings: "liga" 0, "dlig" 0; } more on font-feature-settings codes 'the complete css demo for opentype features' (can't vouch for the truth of the name, but it's pretty big) a list of opentype features on wikipedia using css feature detection for implementation since not all properties are evenly implemented, it's good practice to set up your css using feature detection to utilize the correct properties, with font-feature-settings as the fallback. for e...
Variable fonts guide - CSS: Cascading Style Sheets
g css attributes, and in one case introduced a new one, which you'll see below. custom axes are in fact limitless: the typeface designer can define and scope any axis they like, and are just required to give it a four-letter tag to identify it within the font file format itself. you can use these four-letter tags in css to specify a point along that axis of variation, as will be show in the code examples below. registered axes and existing css attributes in this section we'll demonstrate the five registered axes defined with examples and the corresponding css. where possible, both the standard and lower-level syntax are included. the lower-level syntax (font-variation-settings) was the first mechanism implemented in order to test the early implementations of variable font support, a...
... if you have set values using font-variation-settings and want to change one of those values, you must redeclare all of them (in the same way as when you set opentype font features using font-feature-settings). you can work around this limitation by using css custom properties (css variables) for the individual values, and simply modifying the value of an individual custom property. example code follows at the end of the guide. weight weight (represented by the wght tag) defines the design axis of how thin or thick (light or heavy, in typical typographic terms) the strokes of the letterforms can be. for a long time in css there has existed the ability to specify this via the font-weight property, which takes numeric values ranging from 100 to 900 in increments of 100, and keywords l...
...ndensed or extended, in typographic terms) the letterforms can be. this is typically set in css using the font-stretch property, with values expressed as a percentage above or below ‘normal’ (100%), any number greater than 0 is technically valid—though it is far more likely that the range would fall closer to the 100% mark, such as 75%-125%. if a number value supplied is outside the range encoded in the font, the browser should render the font at the closest value allowed. note: the % symbol is not used when utilizing font-variation-settings. font-stretch: 115%; font-variation-settings: 'wdth' 115; the following live example's css can be edited to allow you to play with font width values. italic the italic (ital) axis works differently in that it is either on or off; there is ...
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
ld or non-supporting browsers to contend with. in this guide we will walk through a variety of strategies for support. the supporting browsers other than in internet explorer, css grid layout is unprefixed in safari, chrome, opera, firefox and edge. support for all the properties and values detailed in these guides is interoperable across browsers. this means that if you write some grid layout code in firefox, it should work in the same way in chrome. this is no longer an experimental specification, and you are safe to use it in production. the internet explorer and edge situation it should be remembered that the original implementation of css grid layout happened in internet explorer 10. this early specification did not contain all of the properties and values that the up-to-date specifi...
...les/89/f993f273dd.png" alt="placeholder"></div> <div class="text">this is a media object example. i am using floats for older browsers and grid for new ones.</div> </div> the image below shows the media object in a non-supporting browser on the left, and a supporting one on the right: using feature queries the above example is very simple, and we can get away without needing to write code that would be a problem to browsers that do not support grid, and legacy code is not an issue to our grid supporting browsers. however, things are not always so simple. in this next example, i have a set of floated cards. i have given the cards a width, in order to float them. to create gaps between the cards, i use a margin on the items, and then a negative margin on the container: * {box-si...
...) { .wrapper { /* do anything for grid supporting browsers here. */ } } feature queries have excellent browser support, and all of the browsers that support the updated grid specification support feature queries too. you can use them to deal with the issue we have with our enhanced: floated layout. i use an @supports rule to check for support of display: grid. i then do my grid code on the <ul>, set my width and min-height on the <li> to auto. i also remove the margins and negative margins, and replace the spacing with the grid-gap property. this means i don’t get a final margin on the last row of boxes. the layout now works, even if there is more content in one of the cards, than the others: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; bor...
Linear-gradient Generator - CSS: Cascading Style Sheets
ribute('data-state')="==" (update_output)="" *="" **="" +="" ++i)="" 4)="" 500);="" :="" <="" activeaxis.deleteactivepoint();="" activeaxis.updatepointcolor(color);="" activeaxis.updatepointposition(color);="" add_axis_btn.removeattribute('data-state');="" axes_menu="getelembyid('gradient-axes');" axesmanager.init();="" box="" button="getelembyid('canvas-bg');" button.addeventlistener('click',="" code="prefix" container="" container.setattribute('data-alpha',="" container;="" createstartaxis(-18);="" createstartaxis(18);="" delete_point_btn="getelembyid('delete-point');" delete_point_btn.addeventlistener('click',="" delete_point_btn.setattribute('data-state',="" dropdownmanager.init();="" dropdownmanager.subscribe('axis-unit',="" for(var="" function="" function()="" functions="" general="" gra...
...background="gradient.join('," i="" i++)="" if="" init="function" init()="" init,="" inputslidermanager.init();="" inputslidermanager.subscribe('point-position',="" k="0;" len="lg_axes.length;" len;="" lg_axes[i].shortcut.style.left="60" lg_axes[i].updateabsoluteposition();="" lg_axes[i].updateonresize();="" methods="" output="getelembyid('output');" output.children[index].children[1].textcontent="code;" output.children[index].style.height="output.children[index].children[1].scrollheight" output;="" point="" pre="" prefix)="" resizecontainer="function" resizecontainer()="" resizecontainer);="" resizecontainer,="" resizeend="function" resizeend()="" resizeend);="" return="" return;="" setaddaxisbutton();="" setaxisunit);="" setdeleteaxisbutton();="" setdeletebuttonstate="function" setdeletebutto...
...setdeletepointbutton="function" setdeletepointbutton()="" setdeletepointbutton();="" settogglealphabackground="function" settogglealphabackground()="" settogglealphabackground();="" slidermanager.init();="" slidermanager.subscribe('axis-rotation',="" state="true;" state);="" this.setattribute('data-alpha',="" this.setattribute('data-state',="" tool="" tool()="" tool.init();="" tool.updateoutputcsscode(gradient);="" uicolorpicker.init();="" uicolorpicker.subscribe('picker',="" uicomponent.makeresizable(gradient_container,="" update_output="settimeout(" updateaxisrotation);="" updatecssgradient="function" updatecssgradient();="" updatecssgradient,="" updateoutputcsscode="function" updateoutputcsscode(gradient)="" updateoutputcsscode:="" updateoutputelem="function" updateoutputelem(0,="" updateou...
border-collapse - CSS: Cascading Style Sheets
sed-border table rendering model). separate adjacent cells have distinct borders (the separated-border table rendering model). ...
...). separate adjacent cells have distinct borders (the separated-border table rendering model). ...
...</th></tr> <tr><td class="fx">firefox</td> <td class="gk">gecko</td></tr> <tr><td class="ed">edge</td> <td class="tr">edgehtml</td></tr> <tr><td class="sa">safari</td> <td class="wk">webkit</td></tr> <tr><td class="ch">chrome</td> <td class="bk">blink</td></tr> <tr><td class="op">opera</td> <td class="bk">blink</td></tr> </tbody> </table> <table class="collapse"> <caption><code>border-collapse: collapse</code></caption> <tbody> <tr><th>browser</th> <th>layout engine</th></tr> <tr><td class="fx">firefox</td> <td class="gk">gecko</td></tr> <tr><td class="ed">edge</td> <td class="tr">edgehtml</td></tr> <tr><td class="sa">safari</td> <td class="wk">webkit</td></tr> <tr><td class="ch">chrome</td> <td class="bk">blink</td></tr> <tr><td class="op">ope...
direction - CSS: Cascading Style Sheets
Web › CSS › direction
ibute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note that text direction is usually defined within a document (e.g., with html's dir attribute) rather than through direct use of the direction property. ...
... syntax /* keyword values */ direction: ltr; direction: rtl; /* global values */ direction: inherit; direction: initial; direction: unset; values ltr text and other elements go from left to right. this is the default value. rtl text and other elements go from right to left. ...
...ed by the all shorthand property. syntax /* keyword values */ direction: ltr; direction: rtl; /* global values */ direction: inherit; direction: initial; direction: unset; values ltr text and other elements go from left to right. this is the default value. rtl text and other elements go from right to left. for the direction property to have any effect on inline-level elements, the unicode-bidi property's value must be embed or override. formal definition initial valueltrapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax ltr | rtl examples setting right-to-left direction blockquote { direction: rtl; } specifications specification status comment css writing modes module level 3the definition of 'di...
overflow-x - CSS: Cascading Style Sheets
if content overflows. ...
... formal definition initial valuevisibleapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto examples html <ul> <li><code>overflow-x:hidden</code> — hides the text outside the box <div id="div1"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-x:scroll</code> — always adds a scrollbar <div id="div2"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-x:visible</code> — displays the text outside the box if needed <div id="div3"...
...yzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-x:scroll</code> — always adds a scrollbar <div id="div2"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-x:visible</code> — displays the text outside the box if needed <div id="div3"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-x:auto</code> — on most browsers, equivalent to <code>scroll</code> <div id="div4"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> </ul> css #div1, #div2, #div3, #div4 { border: 1px solid black; width: 250px; margin-bottom: 12px; } #div1 { overflow-x: hidden;} #div2 { overflow-x: scroll;} #div3 { overflow-x: visible;} #div4 { overflow-x: auto...
Live streaming web audio and video - Developer guides
(smaller) chunks for the next segment. this technology also allows an advertising segment to be appended/inserted into the stream. note: you can also use webm with the mpeg dash adaptive streaming system. hls hls or http live streaming is a protocol invented by apple inc and supported on ios, safari and the latest versions of android browser / chrome. hls is also adaptive. hls can also be decoded using javascript, which means we can support the latest versions of firefox, chrome and internet explorer 10+. see this http live streaming javascript player. at the start of the streaming session, an extended m3u (m3u8) playlist is downloaded. this contains the metadata for the various sub-streams that are provided. streaming file format support browser dash hls opus (audio...
... 11 ✓ [2] android ✓ [1] via javascript and mse [2] via javascript and a cors proxy video fallbacks between dash and hls we can cover a significant portion of modern browsers but we still need a fallback if we want to support the rest. one popular approach is to use a flash fallback that supports rtmp. of course, we then have the issue that we need to encode in three different formats. audio streaming file formats there are also some audio formats beginning to see support across browsers. opus opus is a royalty-free and open format that manages to optimize quality at various bit-rates for different types of audio. music and speech can be optimized in different ways and opus uses the silk and celt codecs to achieve this. currently, opus is suppor...
...technologies in order to stream live audio and video, you will need to run specific streaming software on your server or use third-party services. gstreamer gstreamer is an open source cross-platform multimedia framework that allows you to create a variety of media-handling components, including streaming components. through its plugin system, gstreamer provides support for more than a hundred codecs (including mpeg-1, mpeg-2, mpeg-4, h.261, h.263, h.264, realvideo, mp3, wmv, and flv.) gstreamer plugins such as souphttpclientsink and shout2send exist to stream media over http. you can also integrate with python's twisted framework or use something like flumotion (open source streaming software). for rtmp transfer you can use the nginx rtmp module. shoutcast shoutcast is a cross-platform...
Media buffering, seeking, and time ranges - Developer guides
ontext.fillrect(startx, 0, width, mycanvas.height); context.rect(startx, 0, width, mycanvas.height); context.stroke(); } }); } this works better with longer pieces of audio or video, but press play and click about the player progress bar and you should get something like this. each red filled white rectangle represents a time range. note: you can see the timerange code running live on js bin. seekable the seekable attribute returns a timeranges object and tells us which parts of the media can be played without delay; this is irrespective of whether that part has been downloaded or not. some parts of the media may be seekable but not buffered if byte-range requests are enabled on the server. byte range requests allow parts of the media file to be delivered fr...
...is ready to be played. in practice a good way to do this is use the seekable attribute, although as we have seen above seekable parts of the media are not neccessarily contiguous — they often are however and we can safely approximate this information to give the user an indication of which parts of the media can be played directly. we can find this point in the media using the following line of code: var seekableend = myaudio.seekable.end(myaudio.seekable.length - 1); note: myaudio.seekable.end(myaudio.seekable.length - 1) actually tells us the end point of the last time range that is seekable (not all seekable media). in practice this is good enough as the browser either enables range requests or it doesn't. if it doesn't then audio.seekable will be equivalent to audio.buffered, which wi...
...his is a good event to react to if we want to display download or buffering progress. the timeupdate event is fired 4 times a second as the media plays and that's where we increment our playing progress bar. this should give you results similar to the following, where the light grey bar represents the buffered progress and green bar shows the played progress: note: you can see the buffering code running live on js bin. a quick word about played it’s worth mentioning the played property — this tells us which time ranges have been played within the media. for example: var played = audio.played; // returns a timeranges object this could be useful for establishing the parts of your media that are most listened to or watched. ...
Content categories - Developer guides
, or convey other out of band information. elements belonging to this category are <base>, <command>, <link>, <meta>, <noscript>, <script>, <style> and <title>. flow content elements belonging to the flow content category typically contain text or embedded content. ...
...d from the w3c html specification prior to html 5 being finalized, but is still part of the whatwg specification and is at least partially supported by most browsers. phrasing content phrasing content defines the text and the mark-up it contains. runs of phrasing content make up paragraphs. elements belonging to this category are <abbr>, <audio>, <b>, <bdo>, <br>, <button>, <canvas>, <cite>, <code>, <command>, <data>, <datalist>, <dfn>, <em>, <embed>, <i>, <iframe>, <img>, <input>, <kbd>, <keygen>, <label>, <mark>, <math>, <meter>, <noscript>, <object>, <output>, <picture>, <progress>, <q>, <ruby>, <samp>, <script>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <svg>, <textarea>, <time>, <var>, <video>, <wbr> and plain text (not only consisting of white spaces characters). a few ot...
...ins <input>, <keygen>, <output>,<select>, and <textarea>. secondary categories there are some secondary classifications of elements that can be useful to be aware of as well. script-supporting elements script-supporting elements are elements which don't directly contribute to the rendered output of a document. instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts. the script-supporting elements are: <script> <template> transparent content model if an element has a transparent content model, then its contents must be structured such that they would be valid html 5, even if the transparent element were removed and replaced by the child elements. for example, the <del> and <ins> elements a...
Separate sites for mobile and desktop - Developer guides
t its drawbacks. for starters, you are now maintaining two different pages for every page on your site that you would like to expose to mobile users. if you are using a cms, it is possible to arrange your site templates in a way that minimizes this duplication. however any time that there is a difference between the mobile and desktop templates, there is a potential source of complication in your code. similarly, this increases the implementation time of any new site features, since you must now code two sets of front-end logic. even more important than that, though, is the fact that user-agent detection is inherently flawed, and anything but future-proof. every time a new browser comes out, you must adjust your algorithm to accommodate it. and false positives are particularly scary — it cou...
...d be embarrassing to serve desktop users your mobile site accidentally. when it is right to choose this option firstly, if your target audience includes users on older or low-end feature phones, it is worth noting that you may need to employ this strategy to some degree no matter what. this is because the default browsers on some feature-phones do not support the same markup that you would use to code a website targeted at the desktop, but instead understand formats like xhtml-mp or the older wml. this factor aside, there is one case where this strategy really shines over other methods. if the functionality you would like to provide to your users on mobile devices is extremely different from that on a desktop, then using separate sites is simply likely to be the most practical choice. this is ...
...p site, and need to have a 100% separate mobile site. though it’s not ideal, at least you have this option. examples most of the major web applications you see in the wild have chosen this path, including facebook, youtube, digg, and flickr. in fact, mozilla picked this strategy for the mobile versions of addons.mozilla.org (amo) and support.mozilla.org (sumo). if you’d like to see the source code behind an example of this approach in action, feel free to check out the github repository for amo or sumo. approaches to mobile web development see the following articles for background and other approaches to developing for mobile platforms. what is mobile-friendliness? responsive design a hybrid approach original document information this article was originally published on 13 may...
Parsing and serializing XML - Developer guides
ng = '<a id="a"><b id="b">hey!</b></a>'; var oparser = new domparser(); var odom = oparser.parsefromstring(smystring, "application/xml"); // print the name of the root element or error message console.log(odom.documentelement.nodename == "parsererror" ? ...
...o a dom tree: var xhr = new xmlhttprequest(); xhr.onload = function() { dump(xhr.responsexml.documentelement.nodename); } xhr.onerror = function() { dump("error while getting xml."); } xhr.open("get", "example.xml"); xhr.responsetype = "document"; xhr.send(); the value returned in the xhr object's responsexml field is a document constructed by parsing the xml. if the document is html, the code shown above will return a document. if the document is xml, the resulting object is actually a xmldocument. the two types are essentially the same; the difference is largely historical, although differentiating has some practical benefits as well. note: there is in fact an htmldocument interface as well, but it is not necessarily an independent type. in some browsers it is, while in others it i...
...erty (if you want just the descendants of the specified node) or the element.outerhtml property if you want the node and all its descendants. var dochtml = document.documentelement.innerhtml; as a result, dochtml is a domstring containing the html of the contents of the document; that is, the <body> element's contents. you can get html corresponding to the <body> and its descendants with this code: var dochtml = document.documentelement.outerhtml; ...
HTML attribute reference - HTML: Hypertext Markup Language
, <script> declares the character encoding of the page or script. checked <command>, <input> indicates whether the element should be checked on page load. cite <blockquote>, <del>, <ins>, <q> contains a uri which points to the source of the quote or change. class global attribute often used with css to style elements with common properties. code <applet> specifies the url of the applet's class file to be loaded and executed. codebase <applet> this attribute gives the absolute or relative url of the directory where applets' .class files referenced by the code attribute are stored. color <basefont>, <font>, <hr> this attribute sets the text color using either a named color or a color specified in th...
...curity policy that an embedded document must agree to enforce upon itself. data <object> specifies the url of the resource. data-* global attribute lets you attach custom attributes to an html element. datetime <del>, <ins>, <time> indicates the date and time associated with the element. decoding <img> indicates the preferred method to decode the image. default <track> indicates that the track should be enabled unless the user's preferences indicate something different. defer <script> indicates that the script should be executed after the page has been parsed. dir global attribute defines the text direction. allowed values are ltr (left-to-right) or rtl (right-to-left) dirname <...
...gacy attribute, in which case the css width property should be used instead. wrap <textarea> indicates whether the text should be wrapped. content versus idl attributes in html, most attributes have two faces: the content attribute and the idl (interface definition language) attribute. the content attribute is the attribute as you set it from the content (the html code) and you can set it or get it via element.setattribute() or element.getattribute(). the content attribute is always a string even when the expected value should be an integer. for example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setattribute("maxlength", "42") on that element. the idl attribute is also known as a javascript property. these are th...
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › figure
g are mandatory. permitted parents any element that accepts flow content. implicit aria role figure permitted aria roles with no figcaption descendant: any, otherwise no permitted roles dom interface htmlelement attributes this element only includes the global attributes. usage notes usually a <figure> is an image, illustration, diagram, code snippet, etc., that is referenced in the main flow of a document, but that can be moved to another part of the document or to an appendix without affecting the main flow. being a sectioning root, the outline of the content of the <figure> element is excluded from the main outline of the document. a caption can be associated with the <figure> element by inserting a <figcaption> inside it (as the...
...e is presented as the figure's caption. ...
...just an image --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> </figure> <!-- image with a caption --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> <figcaption>mdn logo</figcaption> </figure> code snippets <figure> <figcaption>get browser details using <code>navigator</code>.</figcaption> <pre> function navigatorexample() { var txt; txt = "browser codename: " + navigator.appcodename + "; "; txt+= "browser name: " + navigator.appname + "; "; txt+= "browser version: " + navigator.appversion + "; "; txt+= "cookies enabled: " + navigator.cookieenabled + "; "; txt+= "platform: " + navigator.platform + "; "; txt+= "user-agent header: " +...
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
used as the button's label. <input type="button" value="click me"> if you don't specify a value, you get an empty button: <input type="button"> using buttons <input type="button"> elements have no default behavior (their cousins, <input type="submit"> and <input type="reset"> are used to submit and reset forms, respectively). to make buttons do anything, you have to write javascript code to do the work. a simple button we'll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph): <form> <input type="button" value="start machine"> </form> <p>the machine is stopped.</p> const button = document.queryselector('input'); const paragraph = document.queryselector...
...bal attribute on it, like so: <input type="button" value="disable me" disabled> you can enable and disable buttons at run time by simply setting disabled to true or false. in this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true. a settimeout() function is then used to reset the button back to its enabled state after two seconds. ...
...s all at once by enclosing them in a container such as a <fieldset> element, and then setting disabled on the container. the example below shows this in action. this is very similar to the previous example, except that the disabled attribute is set on the <fieldset> when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed. ...
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
rief hint to the user as to what kind of information is expected in the field. it should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. the text must not include carriage returns or line feeds. if the control's content has one directionality (ltr or rtl) but needs to present the placeholder in the opposite directionality, you can use unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see overriding bidi using unicode control characters in the unicode bidirectional text algorithm for those characters. note: avoid using the placeholder attribute if you can. it is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your cont...
...r attribute if you can. it is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. see labels and placeholders in <input>: the input (form input) element for more information. readonly a boolean attribute which, if present, means this field cannot be edited by the user. its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property. note: because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. step the step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. only values which are equal to the basis for ste...
...> validation.) important: html form validation is not a substitute for server-side scripts that ensure that the entered data is in the proper format! it's far too easy for someone to make adjustments to the html that allow them to bypass the validation, or to remove it entirely. it's also possible for someone to bypass your html and submit the data directly to your server. if your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth). pattern validation <input type="number"> elements do not support use of the pattern attribute for making entered values conform to a specific regex pattern. the rationale for this is that number inputs won't be valid if the...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
g indicating the url to which to submit the data. this takes precedence over the action attribute on the <form> element that owns the <input>. this attribute is also available on <input type="image"> and <button> elements. formenctype a string that identifies the encoding method to use when submitting the form data to the server. there are three permitted values: application/x-www-form-urlencoded this, the default value, sends the form data as a string after url encoding the text using an algorithm such as encodeuri(). multipart/form-data uses the formdata api to manage the data, allowing for files to be submitted to the server. you must use this encoding type if your form includes any <input> elements of type file (<input type="file">). text/plain plain text; mostly useful only for...
... <input type="image"> and <button> elements. formmethod a string indicating the http method to use when submitting the form's data; this value overrides any method attribute given on the owning form. permitted values are: get a url is constructed by starting with the url given by the formaction or action attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by formenctype or the form's enctype attribute. this url is then sent to the server using an http get request. this method works well for simple forms that contain only ascii characters and have no side effects. this is the default value. post the form's data is included in the body of the request that is sent to the url given by the formaction or action attribute using an http po...
...bel> <input id="example" type="text" name="text"> </div> <div> <input type="submit" value="send"> </div> </form> this renders like so: try entering some text into the text field, and then submitting the form. upon submitting, the data name/value pair gets sent to the server. in this instance, the string will be text=usertext, where "usertext" is the text entered by the user, encoded to preserve special characters. where and how the data is submitted depends on the configuration of the <form>; see sending form data for more details. adding a submit keyboard shortcut keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. to add a keyboard shortcut to a submit button — just a...
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
the <script> element can also be used with other languages, such as webgl's glsl shader programming language and json. content categories metadata content, flow content, phrasing content. permitted content dynamic script such as text/javascript. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts metadata content, or any element that accepts phrasing content. ...
...line metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. see subresource integrity. nomodule this boolean attribute is set to indicate that the script should not be executed in browsers that support es2015 modules — in effect, this can be used to serve fallback scripts to older browsers that do not support modular javascript code. nonce a cryptographic nonce (number used once) to whitelist scripts in a script-src content-security-policy. the server must generate a unique nonce value each time it transmits a policy. it is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial. referrerpolicy indicates which referrer to send when fetching the script, or resources fetched...
...the type of script represented. the value of this attribute will be in one of the following categories: omitted or a javascript mime type: this indicates the script is javascript. the html5 specification urges authors to omit the attribute rather than provide a redundant mime type. in earlier browsers, this identified the scripting language of the embedded or imported (via the src attribute) code. javascript mime types are listed in the specification. module: causes the code to be treated as a javascript module. the processing of the script contents is not affected by the charset and defer attributes. for information on using module, see our javascript modules guide. unlike classic scripts, module scripts require the use of the cors protocol for cross-origin fetching. any other value:...
<tr>: The Table Row element - HTML: Hypertext Markup Language
Web › HTML › Element › tr
xamples and an in-depth tutorial, see the html tables series in our learn web development area, where you'll learn how to use the table elements and their attributes to get just the right layout and formatting for your tabular data. attributes this element includes the global attributes. there are also several deprecated attributes, which you should avoid but may need to know when reading older code. deprecated attributes the following attributes may still be implemented in browsers but are no longer part of the html specification and may be missing or may not work as expected. they should be avoided. alignobsolete since html5 a domstring which specifies how the cell's context should be aligned horizontally within the cells in the row; this is shorthand for using align on every cell in...
...note the use of rowspan on to make the "name", "id", and "balance" headers occupy two rows instead of just one, and the use of colspan to make the "membership dates" header cell span across two columns. the css is unchanged from before. table { border: 1px solid black; } th, td { border: 1px solid black; } explicitly specifying table content groups before really getting into sty...
...note the use of rowspan on to make the "name", "id", and "balance" headers occupy two rows instead of just one, and the use of colspan to make the "membership dates" header cell span across two columns. once again, we haven't touched the css. table { border: 1px solid black; } th, td { border: 1px solid black; } result the output is entirely unchanged, despite the addition of us...
<var>: The Variable element - HTML: Hypertext Markup Language
Web › HTML › Element › var
mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. ...
... permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. ...
...ding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. usage notes related elements other elements that are used in contexts in which <var> is commonly used include: <code>: the html code element <kbd>: the html keyboard input element <samp>: the html sample output element if you encounter code that is mistakenly using <var> for style purposes rather than semantic purposes, you should either use a <span> with appropriate css or, an appropriate semantic element among the following: <em> <i> <q> default style most browsers apply font-style to "italic" when rendering <var>. this can be overridden in css, like this: var { font: bold 15px "courier", "courier new", monospace; } ex...
lang - HTML: Hypertext Markup Language
not valid according to bcp47, it is set to invalid. language tag syntax the full bcp47 syntax is in-depth enough to mark extremely specific language dialects, but most usage is much simpler. a language tag is made of hyphen-separated language subtags, where each subtag indicates a certain property of the language. the 3 most common subtags are: language subtag required. a 2-or-3-character code that defines the basic language, typically written in all lowercase. for example, the language code for english is en, and the code for badeshi is bdz. script subtag optional. this subtag defines the writing system used for the language, and is always 4 characters long, with the first letter capitalized. for example, french-in-braille is fr-brai and ja-kana is japanese written with the katakana...
... capitalized. for example, french-in-braille is fr-brai and ja-kana is japanese written with the katakana alphabet. if the language is written in a highly typical way, like english in the latin alphabet, there is no need to use this subtag. region subtag optional. ...
... even if the lang attribute is set, it may not be taken into account, as the xml:lang attribute has priority. for the css pseudo-class :lang, two invalid language names are different if their names are different. so while :lang(es) matches both lang="es-es" and lang="es-419", :lang(xyzzy) would not match lang="xyzzy-zorp!". ...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
ng a mime type <link> elements can accept a type attribute, which contains the mime type of the resource the element points to. this is especially useful when preloading resources — the browser will use the type attribute value to work out if it supports that resource, and will only download it if so, ignoring it if not. ...
...you can successfully preload cross-origin resources as long as you set a crossorigin attribute on your <link> element. one interesting case where this applies, even if the fetch is not cross-origin, is font files. because of various reasons, these have to be fetched using anonymous mode cors (see font fetching requirements). let's use this case as an example. ...
...t only are we providing the mime type hints in the type attributes, but we are also providing the crossorigin attribute to handle the cors issue. including media one nice feature of <link> elements is their ability to accept media attributes. ...
Access-Control-Allow-Credentials - HTTP
credentials are cookies, authorization headers or tls client certificates. when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. ...
... credentials are cookies, authorization headers or tls client certificates. when used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. ...
...t returned with the resource, the response is ignored by the browser and not returned to web content. the access-control-allow-credentials header works in conjunction with the xmlhttprequest.withcredentials property or with the credentials option in the request() constructor of the fetch api. for a cors request with credentials, in order for browsers to expose the response to frontend javascript code, both the server (using the access-control-allow-credentials header) and the client (by setting the credentials mode for the xhr, fetch, or ajax request) must indicate that they’re opting in to including credentials. header type response header forbidden header name no syntax access-control-allow-credentials: true directives true the only valid value for t...
CSP: base-uri - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples meta tag configuration <meta http-equiv="content-security-policy" content="base-uri 'self'"> apache configuration <ifmodule mod_headers.c> header set content-security-policy "base-uri 'self'"; </ifmodule> nginx configuration add_header content-security-policy "base-uri 'self';" violation case since your domain isn't example.com, a <base>...
CSP: default-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples no inheritance with default-src if there are other directives specified, default-src does not influence them. the following header: content-security-policy: default-src 'self'; script-src https://example.com is the same as: content-security-policy: connect-src 'self'; font-src 'self'; frame-...
CSP: form-action - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples meta tag configuration <meta http-equiv="content-security-policy" content="form-action 'none'"> apache configuration <ifmodule mod_headers.c> header set content-security-policy "form-action 'none'; </ifmodule> nginx configuration add_header content-security-policy "form-action 'none';" violation case using a <form> element with an action...
CSP: img-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples violation cases given this csp header: content-security-policy: img-src https://example.com/ the following <img> is blocked and won't load: <img src="https://not-example.com/foo.jpg" alt="example picture"> specifications specification status comment content security policy level 3the definition of 'img-src' in ...
CSP: navigate-to - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples meta tag configuration <meta http-equiv="content-security-policy" content="navigate-to 'none'"> violation case using a <form> element with an action set to inline javascript will result in a csp violation. <meta http-equiv="content-security-policy" content="navigate-to 'none'"> <form action="javascript:alert('foo')" id="form1" method="pos...
CSP: prefetch-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. example prefetch resources do not match header ...
...tter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. example prefetch resources do not match header given a page with the following content security policy: content-security-policy: prefetch-src https://example.com/ fetches for the following code will return network errors, as the urls provided do not match prefetch-src's source list: <link rel="prefetch" src="https://example.org/"></link> <link rel="prerender" src="https://example.org/"></link> specification specification status comment content security policy level 3the definition of 'prefetch-src' in that specification. working draft initial definit...
CSP: script-src-attr - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples fallback to script-src if script-src-attr is absent, user agent falls back to the script-src directive, and if that is absent as well, to default-src. todo: add comprehensive examples. specifications specification status comment content security policy level 3the definition of 'script-src-attr' in that specific...
CSP: script-src-elem - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'strict-dynamic' the strict-dynamic source ...
...mic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. at the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. see script-src for an example. 'report-sample' requires a sample of the violating code to be included in the violation report. examples fallback to script-src if script-src-elem is absent, user agent falls back to the script-src directive, and if that is absent as well, to default-src. todo: add comprehensive examples. specifications specification status comment content security policy level 3the definition of 'script-src-elem' in that specific...
CSP: style-src-attr - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'report-sample' requires a sample of the viol...
... of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'report-sample' requires a sample of the violating code to be included in the violation report. examples todo: add examples specifications specification status comment content security policy level 3the definition of 'style-src-attr' in that specification. working draft initial definition. ...
CSP: style-src-elem - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'report-sample' requires a sample of the viol...
... of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. 'report-sample' requires a sample of the violating code to be included in the violation report. examples todo: add examples specifications specification status comment content security policy level 3the definition of 'style-src-elem' in that specification. working draft initial definition. ...
Warning - HTTP
Web › HTTP › Headers › Warning
://github.com/httpwg/http-core/issues/139) and warning: header & stale-while-revalidate (https://github.com/whatwg/fetch/issues/913) for more details. the warning general http header contains information about possible problems with the status of the message. more than one warning header may appear in a response. warning header fields can in general be applied to any message, however some warn-codes are specific to caches and can only be applied to response messages. header type general header forbidden header name no syntax warning: <warn-code> <warn-agent> <warn-text> [<warn-date>] directives <warn-code> a three-digit warning number. the first digit indicates whether the warning is required to be deleted from a stored response after validation. 1...
...ecific to caches and can only be applied to response messages. header type general header forbidden header name no syntax warning: <warn-code> <warn-agent> <warn-text> [<warn-date>] directives <warn-code> a three-digit warning number. the first digit indicates whether the warning is required to be deleted from a stored response after validation. 1xx warn-codes describe the freshness or validation status of the response and will be deleted by a cache after deletion. 2xx warn-codes describe some aspect of the representation that is not rectified by a validation and won't be deleted by a cache after validation unless a full response is sent. <warn-agent> the name or pseudonym of the server or software adding the warning header (might be ...
...dation and won't be deleted by a cache after validation unless a full response is sent. <warn-agent> the name or pseudonym of the server or software adding the warning header (might be "-" when the agent is unknown). <warn-text> advisory text describing the error. <warn-date> optional. if more than one warning header is sent, include a date that matches the date header. warning codes the http warn codes registry at iana.org defines the namespace for warn codes. code text description 110 response is stale a response provided by a cache is stale (the expiration time set for it has passed). 111 revalidation failed an attempt to validate the response failed, due to an inability to reach the server. 112 disconnected o...
A typical HTTP session - HTTP
Web › HTTP › Session
in client-server protocols, like http, sessions consist of three phases: the client establishes a tcp connection (or the appropriate connection if the transport layer is not tcp). the client sends its request, and waits for the answer. the server processes the request, sending back its answer, providing a status code and appropriate data. as of http/1.1, the connection is no longer closed after completing the third phase, and the client is now granted a further request: this means the second and third phases can now be performed any number of times. establishing a connection in client-server protocols, it is the client which establishes the connection. opening a connection in http means initiating a connection in the underlying transport layer, usually this is tcp. with tcp the defa...
...k from the header block. as there is no content-length provided in an http header, this data block is presented empty, marking the end of the headers, allowing the server to process the request the moment it receives this empty line. for example, sending the result of a form: post /contact_form.php http/1.1 host: developer.mozilla.org content-length: 64 content-type: application/x-www-form-urlencoded name=joe%20user&request=send%20me%20one%20of%20your%20catalogue request methods http defines a set of request methods indicating the desired action to be performed upon a resource. although they can also be nouns, these requests methods are sometimes referred as http verbs. the most common requests are get and post: the get method requests a data representation of the specified resource. ...
...thu, 06 dec 2018 17:35:13 gmt expires: thu, 06 dec 2018 17:35:13 gmt server: meinheld/0.6.1 strict-transport-security: max-age=63072000 x-content-type-options: nosniff x-frame-options: deny x-xss-protection: 1; mode=block vary: accept-encoding,cookie x-cache: error from cloudfront <!doctype html... (contains a site-customized page helping the user to find the missing resource) response status codes http response status codes indicate if a specific http request has been successfully completed. responses are grouped into five classes: informational responses, successful responses, redirects, client errors, and servers errors. 200: ok. the request has succeeded. 301: moved permanently. this response code means that the uri of requested resource has been changed. 404: not found. the serv...
Concurrency model and the event loop - JavaScript
this model is quite different from models in other languages like c and java. runtime concepts the following sections explain a theoretical model. modern javascript engines implement and heavily optimize the described semantics. visual representation stack function calls form a stack of frames. ...
...itformessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled). "run-to-completion" each message is processed completely before any other message is processed. this offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). this differs from c, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread. a downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. the browser mitigates ...
...fter the given interval. the execution depends on the number of waiting tasks in the queue. in the example below, the message ''this is just a message'' will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time). basically, the settimeout needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your settimeout. (function() { console.log('this is the start'); settimeout(function cb() { console.log('callback 1: this is a msg from call back'); }); // has a default time value of 0 console.log('this is just a message'); settimeout(function cb1() { console.log('callback 2: this is a ms...
Keyed collections - JavaScript
« previousnext » this chapter introduces collections of data which are indexed by a key; map and set objects contain elements which are iterable in the order of insertion. maps map object ecmascript 2015 introduces a new data structure to map values to values. a map object is a simple key/value map and can iterate its elements in insertion order. the following code shows some basic operations with a map. see also the map reference page for more examples and the complete api. you can use a for...of loop to return an array of [key, value] for each iteration. let sayings = new map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); //...
...e a target of garbage collection (gc) if there is no other reference to the object anymore. the weakmap api is the same as the map api. one difference to map objects is that weakmap keys are not enumerable (i.e., there is no method giving you a list of the keys). if they were, the list would depend on the state of garbage collection, introducing non-determinism. for more information and example code, see also "why weakmap?" on the weakmap reference page. one use case of weakmap objects is to store private data for an object, or to hide implementation details. the following example is from nick fitzgerald's blog post "hiding implementation details with ecmascript 6 weakmaps". the private data and methods belong inside the object and are stored in the privates weakmap object. everything expos...
...private data goes here }; privates.set(this, me); } public.prototype.method = function () { const me = privates.get(this); // do stuff with private data in `me`... }; module.exports = public; sets set object set objects are collections of values. you can iterate its elements in insertion order. a value in a set may only occur once; it is unique in the set's collection. the following code shows some basic operations with a set. see also the set reference page for more examples and the complete api. let myset = new set(); myset.add(1); myset.add('some text'); myset.add('foo'); myset.has(1); // true myset.delete('foo'); myset.size; // 2 for (let item of myset) console.log(item); // 1 // "some text" converting between array and set you can create an array from a set using array...
Character classes - JavaScript
a-z0-9_]. for example, /\w/ matches "a" in "apple", "5" in "$5.28", and "3" in "3d". \w matches any character that is not a word character from the basic latin alphabet. equivalent to [^a-za-z0-9_]. for example, /\w/ or /[^a-za-z0-9_]/ matches "%" in "50%". \s matches a single white space character, including space, tab, form feed, line feed, and other unicode spaces. equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches " bar" in "foo bar". \s matches a single character other than white space. equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. for example, /\s\w*/ matches "foo" in "foo bar". \t matches a horizon...
...s a linefeed. \v matches a vertical tab. \f matches a form-feed. [\b] matches a backspace. if you're looking for the word-boundary character (\b), see boundaries. \0 matches a nul character. do not follow this with another digit. \cx matches a control character using caret notation, where "x" is a letter from a–z (corresponding to codepoints u+0001–u+001f). for example, /\cm/ matches "\r" in "\r\n". \xhh matches the character with the code hh (two hexadecimal digits). \uhhhh matches a utf-16 code-unit with the value hhhh (four hexadecimal digits). \u{hhhh} or \u{hhhhh} (only when the u flag is set.) matches the character with the unicode value u+hhhh or u+hhhhh (hexadecimal digits). ...
......
Working with objects - JavaScript
= 'even an empty string'; console.log(myobj); please note that all keys in the square bracket notation are converted to string unless they're symbols, since javascript object property names (keys) can only be strings or symbols (at some point, private names will also be added as the class fields proposal progresses, but you won't use them with [] form). for example, in the above code, when the key obj is added to the myobj, javascript will call the obj.tostring() method, and use this result string as the new key. you can also access properties by using a string value that is stored in a variable: var propertyname = 'make'; mycar[propertyname] = 'ford'; propertyname = 'model'; mycar[propertyname] = 'mustang'; you can use the bracket notation with for...in to iterate over ...
...ame attribute of "myform", you can refer to the form as document.forms[1] or document.forms["myform"] or document.forms.myform. defining properties for an object type you can add a property to a previously defined object type by using the prototype property. this defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. the following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1. car.prototype.color = null; car1.color = 'black'; see the prototype property of the function object in the javascript reference for more information. defining methods a method is a function associated with an object, or, simply put, a method is a property of an object that is ...
...ializer when defining a prototype you will probably most of the time choose the first form. this form is more compact and natural. however, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. the second form probably best represents the dynamic nature of javascript — but it can make the code hard to read and understand. deleting properties you can remove a non-inherited property by using the delete operator. the following code shows how to remove a property. // creates a new object, myobj, with two properties, a and b. var myobj = new object; myobj.a = 5; myobj.b = 12; // removes the a property, leaving myobj with only the b property. delete myobj.a; console.log ('a' in myobj); /...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
the javascript warning about string generics occurs in firefox versions prior to 68. string generics have been removed starting with firefox 68. ...
... the javascript warning about string generics occurs in firefox versions prior to 68. string generics have been removed starting with firefox 68. ...
...) { 'use strict'; var i, // we could also build the array of methods with the following, but the // getownpropertynames() method is non-shimable: // object.getownpropertynames(string).filter(function(methodname) { // return typeof string[methodname] === 'function'; // }); methods = [ 'contains', 'substring', 'tolowercase', 'touppercase', 'charat', 'charcodeat', 'indexof', 'lastindexof', 'startswith', 'endswith', 'trim', 'trimleft', 'trimright', 'tolocalelowercase', 'normalize', 'tolocaleuppercase', 'localecompare', 'match', 'search', 'slice', 'replace', 'split', 'substr', 'concat', 'localecompare' ], methodcount = methods.length, assignstringgeneric = function(methodname) { var method = string.prototype[methodname...
SyntaxError: illegal character - JavaScript
the javascript exception "illegal character" occurs when there is an invalid or unexpected token that doesn't belong at this position in the code. message syntaxerror: invalid character (edge) syntaxerror: illegal character (firefox) syntaxerror: invalid or unexpected token (chrome) error type syntaxerror what went wrong? there is an invalid or unexpected token that doesn't belong at this position in the code. use an editor that supports syntax highlighting and carefully check your code against mismatches like a minus sign ( - ) versus a dash ( – ) or simple quotes ( " ) vs non-standard quotation marks ( “ ). examples mismatched characters some characters look similar, but will cause the parser to fail interpreting your code. famous examples of this are quotes, the minus or semi...
... // – is not - but looks like this var foo = 'bar'; // syntaxerror: illegal character // <37e> is not ; but looks like this this should work: "this is actually a string"; 42 - 13; var foo = 'bar'; some editors and ides will notify you or at least use a slightly different highlighting for it, but not all. ...
...happens to your code and you're not able to find the source of the problem, it's often best to just delete the problematic line and retype it. forgotten characters it's easy to forget a character here or there. var colors = ['#000', #333', '#666']; // syntaxerror: illegal character add the missing quote for '#333'. var colors = ['#000', '#333', '#666']; hidden characters when copy pasting code from external sources, there might be invalid characters. watch out! var foo = 'bar';​ // syntaxerror: illegal character when inspecting this code in an editor like vim, you can see that there is actually a zero-width space (zwsp) (u+200b) character. var foo = 'bar';​<200b> ...
JavaScript error reference - JavaScript
script. these errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. 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. list of errors in this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). together, these two properties provide a starting point toward understanding and resolving the error. for more information, follow the links ...
...t of errors in this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). together, these two properties provide a starting point toward understanding and resolving the error. ...
...turierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return statement ...
arguments.callee - JavaScript
rguments.callee was added so you could do [1, 2, 3, 4, 5].map(function(n) { return !(n > 1) ? ...
...!== global) { alert('this is: ' + this); } else { alert('this is the global'); } } sillyfunction(); ecmascript 3 resolved these issues by allowing named function expressions. for example: [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ? 1 : factorial(n - 1)*n; }); this has numerous benefits: the function can be called like any other from inside your code it does not create a variable in the outer scope (except for ie 8 and below) it has better performance than accessing the arguments object another feature that was deprecated was arguments.callee.caller, or more specifically function.caller. why is this? well, at any point in time you can find the deepest caller of any function on the stack, and as i said above looking at the call stack has o...
...not possible to inline f. basically it means that any call site that may have been trivially inlinable accumulates a large number of guards: function f(a, b, c, d, e) { return a ? b * c : d * e; } if the javascript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. however in many cases that's just not possible and therefore it becomes impossible to inline. examples using arguments.callee in an anonymous recursive function a recursive function must be able to refer to...
Functions - JavaScript
like the program itself, a function is composed of a sequence of statements called the function body. values can be passed to a function, and the function will return a value. in javascript, functions are first-class objects, because they can have properties and methods just like any other object. what distinguishes them from other objects is that functions can be called. in brief, they are function objects. for more examples and explanations, see also the javascript guide about functions. description every function in javascript is a function object. ...
...on declaration (see function expression for details). a function expression may be a part of a larger expression. one can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code. function [name]([param[, param[, ... param]]]) { statements } name the function name. can be omitted, in which case the function becomes known as an anonymous function. param the name of an argument to be passed to the function. statements the statements comprising the body of the function. here is an example of an anonymous function expression (the name is not used): var myfu...
...ression function c() {} } } block-level functions in strict mode, starting with es2015, functions inside blocks are now scoped to that block. prior to es2015, block-level functions were forbidden in strict mode. 'use strict'; function f() { return 1; } { function f() { return 2; } } f() === 1; // true // f() === 2 in non-strict mode block-level functions in non-strict code in a word: don't. in non-strict code, function declarations inside blocks behave strangely. for example: if (shoulddefinezero) { function zero() { // danger: compatibility risk console.log("this is zero."); } } es2015 says that if shoulddefinezero is false, then zero should never be defined, since the block never executes. however, it's a new part of the standard. historicall...
Array.prototype.concat() - JavaScript
string, number, and boolean objects): concat copies the values of strings and numbers into the new array. note: concatenating array(s)/value(s) will leave the originals untouched. furthermore, any operation on the new array (except operations on elements which are object references) will have no effect on the original arrays, and vice versa. ...
...y operation on the new array (except operations on elements which are object references) will have no effect on the original arrays, and vice versa. ...
...]; const numbers = [1, 2, 3]; letters.concat(numbers); // result in ['a', 'b', 'c', 1, 2, 3] concatenating three arrays the following code concatenates three arrays: const num1 = [1, 2, 3]; const num2 = [4, 5, 6]; const num3 = [7, 8, 9]; const numbers = num1.concat(num2, num3); console.log(numbers); // results in [1, 2, 3, 4, 5, 6, 7, 8, 9] concatenating values to an array the following code concatenates three values to an array: const letters = ['a', 'b', 'c']; const alphanumeric = letters.concat(1, [2, 3]); console.log(alphanumeric); // results in ['a', 'b', 'c', 1, 2, 3] concatenating nested arrays the following code concatenates nested arrays and demonstrates retention of references: const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.lo...
Array.prototype.forEach() - JavaScript
array.prototype.findindex() array methods: every(), some(), find(), and findindex() test the array elements with a predicate returning a truthy value to determine if further iteration is required. foreach expects a synchronous function foreach does not wait for promises. kindly make sure you are aware of the implications while using promises(or async functions) as foreach callback. ...
...i = 0; i < items.length; i++) { copyitems.push(items[i]) } // after items.foreach(function(item){ copyitems.push(item) }) printing the contents of an array note: in order to display the content of an array in the console, you can use console.table(), which prints a formatted version of the array. the following example illustrates an alternative approach, using foreach(). the following code logs a line for each element in an array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element) } // notice that index 2 is skipped, since there is no item at // that position in the array... [2, 5, , 9].foreach(logarrayelements) // logs: // a[0] = 2 // a[1] = 5 // a[3] = 9 using thisarg the following (contrived) example updates an object's propert...
...5, 9]) obj.count // 3 obj.sum // 16 since the thisarg parameter (this) is provided to foreach(), it is passed to callback each time it's invoked. the callback uses it as its this value. note: if passing the callback function uses an arrow function expression, the thisarg parameter can be omitted, since all arrow functions lexically bind the this value. an object copy function the following code creates a copy of a given object. there are different ways to create a copy of an object. the following is just one way and is presented to explain how array.prototype.foreach() works by using ecmascript 5 object.* meta property functions. function copy(obj) { const copy = object.create(object.getprototypeof(obj)) const propnames = object.getownpropertynames(obj) propnames.foreach((name)...
Array.prototype.sort() - JavaScript
the sort() method sorts the elements of an array in place and returns the sorted array. the default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of utf-16 code units values. the time and space complexity of the sort cannot be guaranteed as it depends on the implementation. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arr.sort([comparefunction]) parameters comparefunction optional specifies a function that defines the sort order. if omitted, the array elements are converted to strings, then sorted according to each character's unicode code point value. firstel the first element for comparison. secondel the second element for comparison. return value the sorted array. note that the array is sorted in place, and no copy is made. description if comparefunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in utf-16 code units order. for example,...
...ay. note that the array is sorted in place, and no copy is made. description if comparefunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in utf-16 code units order. for example, "banana" comes before "cherry". in a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the unicode order. all undefined elements are sorted to the end of the array. note : in utf-16, unicode characters above \uffff are encoded as two surrogate code units, of the range \ud800-\udfff. the value of each code unit is taken separately into account for the comparison. thus the character formed by the surrogate pair \ud655\ude55 will be sorted before the character \uff3a. if comparefunction is su...
AsyncFunction - JavaScript
argn names to be used by the function as formal argument names. ...
... separated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. description async function objects created with the asyncfunction constructor are parsed when the function is created. this is less efficient than declaring an async function with an async function expression and calling it within your code, because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. note: async functions created with the asyncfunction constructor do not create closures to their creation contexts; they are always created in the global scope. whe...
...hich they are passed. note: async functions created with the asyncfunction constructor do not create closures to their creation contexts; they are always created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the asyncfunction constructor was called. this is different from using eval with code for an async function expression. invoking the asyncfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. examples creating an async function from an asyncfunction() constructor function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunctio...
GeneratorFunction - JavaScript
object.getprototypeof(function*(){}).constructor syntax new generatorfunction ([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ... argn names to be used by the function as formal argument names. ...
...rated with a comma; for example "x", "thevalue", or "a,b". functionbody a string containing the javascript statements comprising the function definition. description generator function objects created with the generatorfunction constructor are parsed when the function is created. this is less efficient than declaring a generator function with a function* expression and calling it within your code, because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. note: generator function created with the generatorfunction constructor do not create closures to their creation contexts; they are always created in the global scop...
...re passed. note: generator function created with the generatorfunction constructor do not create closures to their creation contexts; they are always created in the global scope. when running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the generatorfunction constructor was called. this is different from using eval with code for a generator function expression. invoking the generatorfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. examples creating a generator function from a generatorfunction() constructor var generatorfunction = object.getprototypeof(function*(){}).constructor var g = new generatorfunction('a', 'yield a * 2'); var iterator...
Intl.Collator.prototype.resolvedOptions() - JavaScript
ttps://github.com/mdn/interactive-examples and send us a pull request. syntax collator.resolvedoptions() return value a new object with properties reflecting the locale and collation options computed during the initialization of the given collator object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. ...
...if the implementation does not support these properties, they are omitted. ...
...if the implementation does not support these properties, they are omitted. ...
Object.seal() - JavaScript
revents them from being converted from data properties to accessor properties and vice versa, but it does not prevent the values of data properties from being changed. attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail, either silently or by throwing a typeerror (most commonly, although not exclusively, when in strict mode code). the prototype chain remains untouched. however, the __proto__ property is sealed as well. comparison to object.freeze() existing properties in objects frozen with object.freeze() are made immutable. objects sealed with object.seal() can have their existing properties changed. examples using object.seal var obj = { prop: function() {}, foo: 'bar' }; // new properties may be added, exi...
... ...
...eit' }); // changes existing property value non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a sealed ordinary object by simply returning it. object.seal(1); // typeerror: 1 is not an object (es5 code) object.seal(1); // 1 (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.seal' in that specification. ...
Promise() constructor - JavaScript
the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new promise(executor) parameters executor a function to be executed by the constructor, during the process of constructing the promiseobj. the executor is custom code that ties an outcome to a promise. you, the programmer, write the executor. the signature of this function is expected to be: function(resolutionfunc, rejectionfunc){ // typically, some asynchronous operation. } at the time when the constructor generates the new promiseobj, it also generates a corresponding pair of functions for resolutionfunc and rejectionfunc; these are "tethered" t...
.... you, the programmer, write the executor. the signature of this function is expected to be: function(resolutionfunc, rejectionfunc){ // typically, some asynchronous operation. } at the time when the constructor generates the new promiseobj, it also generates a corresponding pair of functions for resolutionfunc and rejectionfunc; these are "tethered" to the promiseobj. therefore, the code within the executor has the opportunity to perform some operation and then reflect the operation's outcome(if the value is not another promise object) as either "fulfilled" or "rejected" by terminating with an invocation of either the resolutionfunc or the rejectionfunc, respectively. the executor has no meaningful return value. it communicates via the side-effect caused by resolutionfunc or rej...
... of either the resolutionfunc or the rejectionfunc, respectively. the executor has no meaningful return value. it communicates via the side-effect caused by resolutionfunc or rejectionfunc. the side-effect is that the promiseobj becomes "resolved." typically, it works like this: the operation within executor is asynchronous and provides a callback. the callback is defined within the executor code. the callback terminates by invoking resolutionfunc. the invocation of resolutionfunc includes a value parameter. the value is passed back to the tethered promiseobj. the promiseobj (asynchronously) invokes any .then() associated with it. the value received by promiseobj.then() is passed to the invocation of handlefulfilled as an input parameter (see "chained promises" section). the executor m...
Promise.any() - JavaScript
); }); promise.any([perr]).catch((err) => { console.log(err); }) // expected output: "aggregateerror: no promise in promise.any was resolved" displaying the first image loaded in this example, we have a function that fetches an image and returns a blob. we use promise.any() to fetch a couple of images and display the first one available (i.e. whose promise has resolved). ...
...hat fetches an image and returns a blob. we use promise.any() to fetch a couple of images and display the first one available (i.e. whose promise has resolved). ...
... we use promise.any() to fetch a couple of images and display the first one available (i.e. whose promise has resolved). ...
RegExp - JavaScript
gular expression against all possible matches in a string, or only against the first. regexp.prototype.ignorecase whether to ignore case while attempting a match in a string. regexp.prototype.multiline whether or not to search in strings across multiple lines. regexp.prototype.source the text of the pattern. regexp.prototype.sticky whether or not the search is sticky. regexp.prototype.unicode whether or not unicode features are enabled. instance methods regexp.prototype.compile() (re-)compiles a regular expression during execution of a script. regexp.prototype.exec() executes a search for a match in its string parameter. regexp.prototype.test() tests for a match in its string parameter. regexp.prototype.tostring() returns a string representing the specified object. overri...
...le.log(r, "and re.lastindex", re.lastindex); // [ '1', index: 0, input: '123 456', groups: undefined ] and re.lastindex 1 // [ '2', index: 1, input: '123 456', groups: undefined ] and re.lastindex 2 // [ '3', index: 2, input: '123 456', groups: undefined ] and re.lastindex 3 // ... and no more match. with the global flag g, all 6 digits would be matched, not just 3. regular expression and unicode characters \w and \w only matches ascii based characters; for example, a to z, a to z, 0 to 9, and _. to match characters from other languages such as cyrillic or hebrew, use \uhhhh, where hhhh is the character's unicode value in hexadecimal. this example demonstrates how one can separate out unicode characters from a word. let text = 'Образец text на русском языке' let r...
...ers from a word. let text = 'Образец text на русском языке' let regex = /[\u0400-\u04ff]+/g let match = regex.exec(text) console.log(match[0]) // logs 'Образец' console.log(regex.lastindex) // logs '7' let match2 = regex.exec(text) console.log(match2[0]) // logs 'на' [did not log 'text'] console.log(regex.lastindex) // logs '15' // and so on the unicode property escapes feature introduces a solution, by allowing for a statement as simple as \p{scx=cyrl}. extracting sub-domain name from url let url = 'http://xxx.domain.com' console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx' instead of using regular expressions for parsing urls, it is usually better to use the browsers built-in url parser by using the url api. specifications ...
WebAssembly.Module() constructor - JavaScript
however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile(). ...
...however, the primary way to get a module is through an asynchronous compilation function like webassembly.compile(). ...
...ompile(). syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times. new webassembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes...
WebAssembly.compile() - JavaScript
return value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. ...
...ompile() function compiles webassembly binary code into a webassembly.module object. this function is useful if it is necessary to a compile a module before it can be instantiated (otherwise, the webassembly.instantiate() function should be used). syntax promise<webassembly.module> webassembly.compile(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. return value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. ...
...the binary code of the .wasm module you want to compile. return value a promise that resolves to a webassembly.module object representing the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more efficient than compile(). ...
escape() - JavaScript
rds"), it is defined in annex b of the ecma-262 standard, whose introduction states: … all of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. … … programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code. ...
...iting new ecmascript code. … the escape() function computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. note: this function was used mostly for url queries (the part of a url following ?)—not for escaping ordinary string literals, which use the format "\xhh". (hh are two hexadecimal digits, and the form \xhh\xhh is used for higher-plane unicode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function. syntax escape(str) parameters str a string to be encoded. return value a new string in which certain characters have been escaped. description the escape function is a property of the global object. ...
...higher-plane unicode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function. syntax escape(str) parameters str a string to be encoded. return value a new string in which certain characters have been escaped. description the escape function is a property of the global object. special characters are encoded with the exception of: @*_+-./ the hexadecimal form for characters, whose code unit value is 0xff or less, is a two-digit escape sequence: %xx. for characters with a greater code unit, the four-digit format %uxxxx is used. examples using escape escape('abc123'); // "abc123" escape('äöü'); // "%e4%f6%fc" escape('ć'); // "%u0107" // special characters escape('@*_+-./')...
instanceof - JavaScript
windows, and passing objects from one context to another via functions, this will be a valid and strong issue. for instance, you can securely check if a given object is, in fact, an array using array.isarray(myobj) for example, checking if a nodes is a svgelement in a different context, you can use mynode instanceof mynode.ownerdocument.defaultview.svgelement. note for mozilla developers: in code using xpcom, instanceof has special effect: obj instanceof xpcominterface (e.g. components.interfaces.nsifile) calls obj.queryinterface(xpcominterface) and returns true if queryinterface succeeded. a side effect of such call is that you can use xpcominterface's properties on obj after a successful instanceof test. unlike standard javascript globals, the test obj instanceof xpcominterface works a...
...nd returns true if queryinterface succeeded. a side effect of such call is that you can use xpcominterface's properties on obj after a successful instanceof test. unlike standard javascript globals, the test obj instanceof xpcominterface works as expected, even if obj is from a different scope. examples demonstrating that string and date are of type object and exceptional cases the following code uses instanceof to demonstrate that string and date objects are also of type object (they are derived from object). however, objects created with the object literal notation are an exception here: although the prototype is undefined, instanceof object returns true. let simplestr = 'this is a simple string' let mystring = new string() let newstr = new string('string created with constructor'...
...the instanceof operator demonstrates that the mycar object is of type car and of type object. function car(make, model, year) { this.make = make; this.model = model; this.year = year; } let mycar = new car('honda', 'accord', 1998) let a = mycar instanceof car // returns true let b = mycar instanceof object // retur...
yield - JavaScript
nnot be called from nested functions or from callbacks. the yield keyword causes the call to the generator's next() method to return an iteratorresult object with two properties: value and done. the value property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed. once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's new value. the next time next() is called, execution resumes with the statement immediately after the yield. ...
...d done is true. a return statement is reached. in this case, execution of the generator ends and an iteratorresult is returned to the caller in which the value is the value specified by the return statement and done is true. if an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. ...
... function* countapplesales () { let salelist = [3, 7, 5] for (let i = 0; i < salelist.length; i++) { yield salelist[i] } } once a generator function is defined, it can be used by constructing an iterator as shown. ...
break - JavaScript
h, or label statement that the break statement is intended to break out of. examples break in while loop the following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } return i * x; } break in labeled blocks the following code uses break statements with labeled blocks. a break statement must be nested within any label it references. notice that inner_block is nested within outer_block. outer_block: { inner_block: { console.log('1'); break outer_block; // breaks out of both inner_block and outer_block console.log(':-('); // skipped } console.log('2'); // skipped } break in labeled blocks that throw ...
...tements with labeled blocks. a break statement must be nested within any label it references. notice that inner_block is nested within outer_block. outer_block: { inner_block: { console.log('1'); break outer_block; // breaks out of both inner_block and outer_block console.log(':-('); // skipped } console.log('2'); // skipped } break in labeled blocks that throw the following code also uses break statements with labeled blocks, but generates a syntaxerror because its break statement is within block_1 but references block_2. a break statement must always be nested within any label it references. block_1: { console.log('1'); break block_2; // syntaxerror: label not found } block_2: { console.log('2'); } break within functions syntaxerrors are also generated in the...
...break statements with labeled blocks, but generates a syntaxerror because its break statement is within block_1 but references block_2. a break statement must always be nested within any label it references. block_1: { console.log('1'); break block_2; // syntaxerror: label not found } block_2: { console.log('2'); } break within functions syntaxerrors are also generated in the following code examples which use break statements within functions that are nested within a loop, or labeled block that the break statements are intended to break out of. function testbreak(x) { var i = 0; while (i < 6) { if (i == 3) { (function() { break; })(); } i += 1; } return i * x; } testbreak(1); // syntaxerror: illegal break statement block_1: { console.log...
try...catch - JavaScript
ck, the enclosing try statement's catch-block is used instead. you can also use the try statement to handle javascript exceptions. see the javascript guide for more information on javascript exceptions. unconditional catch-block when a catch-block is used, the catch-block is executed when any exception is thrown from within the try-block. for example, when the exception occurs in the following code, control transfers to the catch-block. try { throw 'myexception'; // generates an exception } catch (e) { // statements to handle any exceptions logmyerrors(e); // pass exception object to error handler } the catch-block specifies an identifier (e in the example above) that holds the value of the exception; this value is only available in the scope of the catch-block. conditional catch-...
...execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. note that the finally-block executes regardless of whether an exception is thrown. also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception. the following example shows one use case for the finally-block. the code opens a file and then executes statements that use the file; the finally-block makes sure the file always closes after it is used even if an exception was thrown. openmyfile(); try { // tie up a resource writemyfile(thedata); } finally { closemyfile(); // always close the resource } examples nested try-blocks first, let's see what happens with this: try { try { throw new error('...
...) { console.error('inner', ex.message); throw ex; } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "inner" "oops" // "finally" // "outer" "oops" any given exception will be caught only once by the nearest enclosing catch-block unless it is rethrown. of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that throws), will be caught by the "outer" block. returning from a finally-block if the finally-block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch-blocks. this includes exceptions thrown inside of the catch-block: (function() { try { try { thr...
JavaScript shells - JavaScript
standalone javascript shells the following javascript shells are stand-alone environments, like perl or python. node.js - node.js is a platform for easily building fast, scalable network applications. jsdb - a standalone javascript shell, with compiled binaries for windows, mac, and linux. javalikescript - a standalone, extensible javascript shell including both native and javascript libraries. gluescript - a standalone javascript shell for writing cross-platform javascript applications. ...
... with mozilla. firefox has a built-in javascript console, which support multi-line editing. javascript shell (js) - a command line interpreter for javascript xpcshell is an xpconnect - enabled shell, sometimes useful for mozilla development. babel repl - a browser-based repl for experimenting with future javascript. es6console.com - an open-source javascript console to test ecmascript 2015 code inside the browser. jsconsole.com -- an open-source javascript console with the ability to easily link to particular expressions javascript shell (web page) - also available as part of the extension developer's extension jash: javascript shell - a dhtml based shell that gives you command line access to a web page. mozrepl - connect to firefox and other mozilla apps, explore and modify them fr...
... xqjs - simple console for firefox. ...
JavaScript typed arrays - JavaScript
ow, 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 array.isarray() on a typed array returns false. moreover, not all met...
...e array just like a normal array: for (let i = 0; i < int32view.length; i++) { int32view[i] = i * 2; } this fills out the 4 entries in the array (4 entries at 4 bytes each makes 16 total bytes) with the values 0, 2, 4, and 6. multiple views on the same data things start to get really interesting when you consider that you can create multiple views onto the same data. for example, given the code above, we can continue like this: let int16view = new int16array(buffer); for (let i = 0; i < int16view.length; i++) { console.log('entry ' + i + ': ' + int16view[i]); } here we create a 16-bit integer view that shares the same buffer as the existing 32-bit view and we output all the values in the buffer as 16-bit integers. now we get the output 0, 0, 2, 0, 4, 0, 6, 0. you can go a step fa...
...t due with amountdueview[0]. note: the data structure alignment in a c structure is platform-dependent. take precautions and considerations for these padding differences. conversion to normal arrays after processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the array prototype. this can be done using array.from(), or using the following code where array.from() is unsupported. let typedarray = new uint8array([1, 2, 3, 4]), normalarray = array.prototype.slice.call(typedarray); normalarray.length === 4; normalarray.constructor === array; specifications specification ecmascript (ecma-262)the definition of 'typedarray objects' in that specification. ...
JavaScript
as follows: javascript first steps answers some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", along with discussing key javascript features such as variables, strings, numbers, and arrays. javascript building blocks continues our coverage of javascript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events. introducing javascript objects the object-oriented nature of javascript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. asynchronous javascript discusses asynchronous javascript, why it is important, and ...
...erators instanceof, typeof, new, this, the operator precedence, and more. statements and declarations learn how do-while, for-in, for-of, try-catch, let, var, const, if-else, switch, and more javascript statements and keywords work. functions learn how to work with javascript's functions to develop your applications. tools & resources helpful tools for writing and debugging your javascript code. firefox developer tools web console, javascript profiler, debugger, and more. javascript shells a javascript shell allows you to quickly test snippets of javascript code. learn javascript an excellent resource for aspiring web developers — learn javascript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. the first 40 lessons are f...
...s. jsfiddle edit javascript, css, html and get live results. use external resources and collaborate with your team online. plunker plunker is an online community for creating, collaborating on and sharing your web development ideas. edit your javascript, css, html files and get live results and file structure. jsbin js bin is an open-source collaborative web development debugging tool. codepen codepen is another collaborative web development tool used as a live result playground. stackblitz stackblitz is another online playground/debugging tool, which can host and deploy full-stack applications using react, angular, etc. ...
Autoplay guide for media and Web Audio APIs - Web media technologies
o track are considered to be audible, and autoplay blocking applies to them. inaudible media are not affected by autoplay blocking. autoplay and autoplay blocking the term autoplay refers to any feature that causes audio to begin to play without the user specifically requesting that playback begin. this includes both the use of html attributes to autoplay media as well as the user of javascript code to start playback outside the context of handling user input. that means that both of the following are considered autoplay behavior, and are therefore subject to the browser's autoplay blocking policy: <audio src="/music.mp4" autoplay> and audioelement.play(); the following web features and apis may be affected by autoplay blocking: the html <audio> and <video> elements the web audio ap...
...failure to autoplay media when you use the play() method to start it. play() returns a promise which is resolved once the media successfully begins to play, and is rejected when playback fails to begin (such as if autoplay is denied). when autoplay fails, you likely will want to offer a way for the user to manually tell the browser to ask the user to grant permission to play media. you might use code like this to accomplish the job: let startplaypromise = videoelem.play(); if (startplaypromise !== undefined) { startplaypromise.then(() => { // start whatever you need to do only after playback // has begun. }).catch(error => { if (error.name === "notallowederror") { showplaybutton(videoelem); } else { // handle a load or playback error } }); } the first...
...; } else { // handle a load or playback error } }); } the first thing we do with the result of play() is make sure it's not undefined. we check for this because in earlier versions of the html specification, play() didn't return a value. returning a promise to allow you to determine success or failure of the operation was added more recently. checking for undefined prevents this code from failing with an error on older versions of web browsers. if the promise returned by play() is resolved without error, the then() clause is run and can begin whatever needs to be done when autoplay has begun. we then add a catch() handler to the promise. this looks at the error's name to see if it's notallowederror. this indicates that playback failed due to a permission issue, such as auto...
Add to Home screen - Progressive web apps (PWAs)
ow. a2hs makes this possible. what browsers support a2hs? a2hs is supported in all mobile browsers, except ios webview. it's also supported in some chromium desktop browsers. firefox has had mobile support since v58 and is working on desktop support. see caniuse.com for exact details. how do you use it? we've written a very simple example web site (see our demo live, and also see the source code) that doesn't do much, but was developed with the necessary code to allow it to be added to a home screen, as well as a service worker to enable it to be used offline. the example displays a series of fox pictures. if you have firefox for android available, use it to navigate to our demo at https://mdn.github.io/pwa-examples/a2hs/. you'll see fox pictures, but more important, you'll see a "home"...
...nd data to your device and make the app available offline, or anything like that. to make your app work offline, you have to use the service worker api to handle storing the assets offline, and if required, web storage or indexeddb to store its data. in our example app, we've just used a service worker to store all necessary files. the service worker is registered against the site with the final code block in the index.js file. we then cache all the site's assets using the cache api, and serve them from the cache instead of the network using the code in the sw.js file. a2hs on desktop while originally intended to improve user experience on mobile oses, there is movement to make pwas installable on desktop platforms too. note: at the time of writing, the functionality described below was o...
... appears. if the user selects install, the app is installed (available as standalone desktop app), and the install button no longer shows (the onbeforeinstallprompt event no longer fires if the app is already installed). when you open the app, it will appear in its own window: if the user selects cancel, the state of the app goes back to how it was before the button was clicked. note: the code for this section was mostly taken from app install banners/add to home screen by pete lepage. ...
Progressive web app structure - Progressive web apps (PWAs)
png" alt="js13kgames"></a></p> </header> <main> <h1>js13kgames a-frame entries</h1> <p class="description">list of games submitted to the <a href="http://js13kgames.com/aframe">a-frame category</a> in the <a href="http://2017.js13kgames.com">js13kgames 2017</a> competition. ...
...].twitter) .replace(/website/g,games[i].website) .replace(/github/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getelementbyid('content').innerhtml = content; next, it registers a service worker: if('serviceworker' in navigator) { navigator.serviceworker.register('/pwa-examples/js13kpwa/sw.js'); }; the next code block requests permission for notifications when a button is clicked: var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if(result === 'granted') { randomnotification(); } }); }); the last block creates notifications that display a randomly-selected ite...
...-cyberspace' }, { slug: 'vernissage', name: 'vernissage', author: 'platane', twitter: 'platane_', website: 'github.com/platane', github: 'github.com/platane/js13k-2017' }, // ... { slug: 'emma-3d', name: 'emma-3d', author: 'prateek roushan', twitter: '', website: '', github: 'github.com/coderprateek/emma-3d' } ]; every entry has its own image in the data/img folder. this is our content, loaded into the content section with javascript. next up in the next article we will look in more detail at how the app shell and the content are cached for offline use with the help from the service worker. previous overview: progressive web apps next ...
Introduction to progressive web apps - Progressive web apps (PWAs)
those features are unavailable. presenting a trusted website with a good performance is a consequence of using these enhancements; this in turn means building web apps which follow better practices. this way everybody will be able to use the app, but those with modern browsers will benefit from pwa features even more. ...
... for now, let's move to the second part of this series, where we’ll be looking at the structure of our example app. ...
... for now, let's move to the second part of this series, where we’ll be looking at the structure of our example app. ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
hing, or let them know about new content being available in the app. push example push needs the server part to work, so we're not able to include it in the js13kpwa example hosted on github pages, as it offers hosting of static files only. it is all explained in the service worker cookbook — see the push payload demo. this demo consists of three files: index.js, which contains the source code of our app server.js, which contains the server part (written in node.js) service-worker.js, which contains the service worker-specific code. let's explore all of these index.js the index.js file starts by registering the service worker: navigator.serviceworker.register('service-worker.js') .then(function(registration) { return registration.pushmanager.getsubscription() .then(async fun...
...subscription) { // registration part }); }) .then(function(subscription) { // subscription part }); it is a little bit more complicated than the service worker we saw in the js13kpwa demo. in this particular case, after registering, we use the registration object to subscribe, and then use the resulting subscription object to complete the whole process. in the registration part, the code looks like this: if(subscription) { return subscription; } if the user has already subscribed, we then return the subscription object and move to the subscription part. if not, we initialize a new subscription: const response = await fetch('./vapidpublickey'); const vapidpublickey = await response.text(); const convertedvapidkey = urlbase64touint8array(vapidpublickey); the app fetches the...
...there's a big collection of working examples showing general use, but also web push, caching strategies, performance, working offline, and more. previous overview: progressive next ...
Getting started - SVG: Scalable Vector Graphics
then open the file in firefox. it will render as shown in the following screenshot. ...
...then open the file in firefox. it will render as shown in the following screenshot. ...
...rvers for svg, there may be ways to do it yourself. see the server configuration page on the w3.org for a range of simple solutions. server misconfiguration is a very common reason for svg failing to load, so make sure you check yours. if your server is not configured to send the correct headers with the svg files it serves, then firefox will most likely show the markup of the files as text or encoded garbage, or even ask the viewer to choose an application to open them. « previousnext » ...
SVG fonts - SVG: Scalable Vector Graphics
this bears an id attribute, to enable it to be referenced via a uri (see below). the horiz-adv-x attribute determines how wide a character is on average compared to the path definitions of the single glyphs.
...p-height="600" x-height="400" ascent="700" descent="300" alphabetic="0" mathematical="350" ideographic="400" hanging="500"> <font-face-src> <font-face-name name="super sans bold"/> </font-face-src> </font-face> <missing-glyph><path d="m0,0h200v200h-200z"/></missing-glyph> <glyph unicode="!" horiz-adv-x="300"><!-- outline of exclam. pt. glyph --></glyph> <glyph unicode="@"><!-- outline of @ glyph --></glyph> <!-- more glyphs --> </font> we start with the <font> element. this bears an id attribute, to enable it to be referenced via a uri (see below). the horiz-adv-x attribute determines how wide a character is on average compared to the path definitions of the single glyphs. the value 1000 sets a reasonable value to work with. there are several accompanying ...
...hows how glyphs are created: by simply adding any graphical svg content inside. you can use literally any other svg elements in here, even <filter>, <a> or <script>. for simple glyphs, however, you can simply add a d attribute — this defines a shape for the glyph exactly like how standard svg paths work. the actual glyphs are then defined by <glyph> elements. the most important attribute is unicode. it defines the unicode codepoint represented by this glyph. if you also specify the lang attribute on a glyph, you can further restrict it to certain languages (represented by xml:lang on the target) exclusively. again, you can use arbitrary svg to define the glyph, which allows for great effects in supporting user agents. there are two further elements that can be defined inside font: <hkern> ...
Using templates and slots - Web Components
med <slot> will be filled with all of the custom element's top-level child nodes that do not have the slot attribute. this includes text nodes. and that's it for our trivial example. if you want to play with it some more, you can find it on github (see it running live also). a more involved example to finish off the article, let's look at something a little less trivial. ...
...font-weight: bold; color: #217ac0; font-size: 120%} h4 { margin: 10px 0 -8px 0; } h4 span { background: #217ac0; padding: 2px 6px 2px 6px } h4 span { border: 1px solid #cee9f9; border-radius: 4px } h4 span { color: white } .attributes { margin-left: 22px; font-size: 90% } .attributes p { margin-left: 16px; font-style: italic } </style> <details> <summary> <span> <code class="name">&lt;<slot name="element-name">need name</slot>&gt;</code> <i class="desc"><slot name="description">need description</slot></i> </span> </summary> <div class="attributes"> <h4><span>attributes</span></h4> <slot name="attributes"><p>none</p></slot> </div> </details> <hr> </template> that <template> element has several features: the <templa...
...: 120%} h4 { margin: 10px 0 -8px 0; } h4 span { background: #217ac0; padding: 2px 6px 2px 6px } h4 span { border: 1px solid #cee9f9; border-radius: 4px } h4 span { color: white } .attributes { margin-left: 22px; font-size: 90% } .attributes p { margin-left: 16px; font-style: italic } </style> <details> <summary> <span> <code class="name">&lt;<slot name="element-name">need name</slot>&gt;</code> <i class="desc"><slot name="description">need description</slot></i> </span> </summary> <div class="attributes"> <h4><span>attributes</span></h4> <slot name="attributes"><p>none</p></slot> </div> </details> <hr> </template> <element-details>...
lang - XPath
Web › XPath › Functions › lang
returns true if the context node matches the given languages. otherwise, false. notes a node's language is determined by its xml:lang attribute. ...
... returns true if the context node matches the given languages. otherwise, false. notes a node's language is determined by its xml:lang attribute. ...
...is determined by its xml:lang attribute. if the current node does not have an xml:lang attribute, then the value of the xml:lang attribute of the nearest ancestor that has an xml:lang attribute will determine the current node's language. if the language cannot be determined (no ancestor has an xml:lang attribute), this function will return false. if the given string does not specify a country code, this function will match nodes of that language with any country code. the converse is not true. given this fragment of xml: <p xml:lang="en">i went up a floor.</p> <p xml:lang="en-gb">i took the lift.</p> <p xml:lang="en-us">i rode the elevator.</p> and this part of an xsl template: <xsl:value-of select="count(//p[lang('en')])" /> <xsl:value-of select="count(//p[lang('en-gb')])" /> <xsl:va...
XPath snippets - XPath
node-specific evaluator function the following custom utility function can be used to evaluate xpath expressions on given xml nodes. the first argument is a dom node or document object, while the second is a string defining an xpath expression. ...
... node-specific evaluator function the following custom utility function can be used to evaluate xpath expressions on given xml nodes. the first argument is a dom node or document object, while the second is a string defining an xpath expression. ...
...denver" state="co" country="usa"/> </person> </people> you can now "query" the document with xpath expressions. although walking the dom tree can achieve similar results, using xpath expressions is much quicker and more powerful. if you can rely on id attributes, document.getelementbyid() is still powerful, but it's not nearly as powerful as xpath. here are some examples. ...
2015 MDN Fellowship Program - Archive of obsolete content
to accelerate the involvement of highly-skilled and experienced web developers with the open web. who web and mobile developers with an established track record of contributions and expertise in a specific web technology, function or domain who wish to increase the effectiveness of their teaching and communications. what seven weeks of partnering closely with mozilla to (1) build curriculum, code, or likely both; and (2) receive coaching, training and best practices for effectively communicating and educating with technical information. we expect this to be between 5-10 hours of your time per week. specific projects (we encourage you to target one of these in your application): testthewebforward brief project description mozilla participates in an important w3c open testing initiati...
...ing and network layers preferred. mentor information harald kirschner, web craftsman. github: digitarald twitter: @digitarald curriculum development brief project description mdn serves as a trusted resource for literally millions of developers on a regular basis. in 2015, mdn will expand the impact of this content by developing kits of key learning materials, including such elements as code samples, videos and other elements being finalized. activities and deliverables act as lead curator for technical curriculum addressing a key web technology, developing code samples, videos, interactive exercises and other components to be determined. you may propose your own subject area (examples: virtual reality on the web, network security, css, etc.) or we will work with you to match you t...
Communicating With Other Scripts - Archive of obsolete content
ts: communicating with the add-on: content script to content script. page scripts if a page includes its own scripts using <script> tags, either embedded in the page or linked to it using the src attribute, there are a couple of ways a content script can communicate with it: using the dom postmessage() api using custom dom events using the dom postmessage api note that before firefox 31 code in content scripts can't use window to access postmessage() and addeventlistener() and instead must use document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). messaging from content script to page script suppose we have a page called "listen.html" hosted at "my-domain.org...
...e document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). messaging from content script to page script suppose we have a page called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page. ...
Interacting with page scripts - Archive of obsolete content
package.json, and set it to true. "permissions": { "unsafe-content-script": true } this is only a temporary migration aid, and will be removed eventually. communicating with page scripts there are two different ways a content script can communicate with a page script: using the dom postmessage() api using custom dom events using the dom postmessage api note that before firefox 31 code in content scripts can't use window to access postmessage() and addeventlistener() and instead must use document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). content script to page script suppose we have a page called "listen.html" hosted at "my-domain.org", and we want ...
...instead must use document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). content script to page script suppose we have a page called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page. ...
self - Archive of obsolete content
s property of self: // main.js const tabs = require("sdk/tabs"); tabs.open({ url: "./page.html", onready: function(tab) { tab.attach({ contentscriptfile: "./content-script.js", contentscriptoptions: { a: "blah" } }); } }); // content-script.js alert(self.options.a); port you can use port to receive messages from, and send messages to, the main add-on code. see the documentation for port. methods the self object has four methods, which enable the content script to send messages to, and receive messages from, the main add-on code. this is an older api than the api provided by port, and for most purposes the port api is a better choice. the exception is the context-menu module, which still uses postmessage. postmessage() send a message from a ...
...self object has four methods, which enable the content script to send messages to, and receive messages from, the main add-on code. this is an older api than the api provided by port, and for most purposes the port api is a better choice. the exception is the context-menu module, which still uses postmessage. postmessage() send a message from a content script to a listener in the main add-on code: self.postmessage(contentscriptmessage); this takes a single parameter, the message payload, which may be any json-serializable value. on() start listening to messages from the main add-on code: self.on("message", function(addonmessage) { // handle the message }); this takes two parameters: the name of the event, and the handler function. the handler function is passed the message payload...
Contributor's Guide - Archive of obsolete content
es to inherit state and behavior from an existing classes, known as the base class. unlike languages like c++ and java, javascript does not have native support for classical inheritance. instead, it uses something called prototypal inheritance. as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code. content processes a content process was supposed to run all the code associated with a single tab. conversely, an add-on process was supposed to run all the code associated with a single add-on. neither content or add-on proceses were ever actually implemented, but by the time they were cancelled, the sdk was already designed with them in mind. to understand this article, it's probably best to...
... with a single add-on. neither content or add-on proceses were ever actually implemented, but by the time they were cancelled, the sdk was already designed with them in mind. to understand this article, it's probably best to read it as if content and add-on processes actually exist. getting started learn how to contribute to the add-on sdk. modules a module is a self-contained unit of code, which is usually stored in a file, and has a well defined interface. the use of modules greatly improves the maintainability of code, by splitting it up into independent components, and enforcing logical boundaries between them. unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscript...
SDK API Lifecycle - Archive of obsolete content
apis when they're no longer optimal or supported by the underlying platform. the api lifecycle aims to balance these competing demands. it has two main components: a stability index that defines how stable each module is a deprecation process that defines when and how stable sdk apis can be changed or removed from future versions of the sdk while giving developers enough time to update their code. stability index the stability index is adopted from node.js. the sdk uses only four of the six values defined by node.js: experimental the module is not yet stabilized. you can try it out and provide feedback, but we may change or remove it in future versions without having to pass through a formal deprecation process. unstable the api is in the process of settling, b...
...ice should point developers at a migration guide. migration the deprecation period defaults to 18 weeks (that is, three releases) although in some cases, generally those out of our control, it might be shorter than this. during this time, the module will be in the deprecated state. the sdk team will track usage of deprecated modules on addons.mozilla.org and support developers migrating their code. the sdk will continue to provide warnings: api documentation will inform users that the module is deprecated. attempts to use a deprecated module at runtime will log an error to the error console. the amo validator will throw errors when deprecated modules are used, and these add-ons will therefore fail amo review. all warnings should include links to further information about what to use...
Testing the Add-on SDK - Archive of obsolete content
th cfx (which is part of the addon-sdk repo), we can run the first test suite which was produced for the add-on sdk. this includes: cfx testcfx: a suite of python tests which test cfx itself (which is written in python). this suite basically tests cfx xpi's ability to produce the xpi files that we expect it to. cfx testex --filter <addon_example_folder_name>: a suite of tests which run test code for some example add-ons. this suite builds the example code, then runs these example add-on's test code. cfx testaddons --filter <addon_folder_name>: a suite of tests which run add-ons, which are themseleves tests. this suite builds add-ons which are tests (ie: their main.js script's merely run tests and close firefox when their tests are done), and runs them as cfx run would. cfx testpkgs ...
...all of the tests with gulp test. with travis if you merely make a pull request for the mozilla/addon-sdk then all of the jpm tests mentioned above will be run on travis-ci automatically and you will see the pass/fail results with a link to the log in the github pull request. only on a linux machine at the moment. from mozilla-central repository with a checkout of the mozilla-central source code, one can always cd addon-sdk/source and use any of the methods described above, but in addtion to that there are a couple of mach commands available, and ofcourse there is the try server if you have access to that. with mach there are two commands: ./mach mochitest -f jetpack-addon <optional_addon_path>: this runs the test add-ons mentioned for cfx testaddons and gulp test:addons with the o...
Working with Events - Archive of obsolete content
the add-on sdk supports event-driven programming. objects emit events on state changes that might be of interest to add-on code, such as browser windows opening, pages loading, network requests completing, and mouse clicks. by registering a listener function to an event emitter an add-on can receive notifications of these events. we talk about content scripts in more detail in the working with content scripts guide. additionally, if you're using content scripts to interact with web content, you can define your own events and use them to communicate between the main add-on code and the content scripts. in this case one end of the conversation emits the events, and the other end listens to them. so there are two main ways you will interact with the eventemitter framework: listening to...
...de and the content scripts. in this case one end of the conversation emits the events, and the other end listens to them. so there are two main ways you will interact with the eventemitter framework: listening to built-in events emitted by objects in the sdk, such as tabs opening, pages loading, mouse clicks sending and receiving user-defined events between content scripts and add-on code this guide only covers the first of these; the second is explained in the working with content scripts guide. adding listeners you can add a listener to an event emitter by calling its on(type, listener) method. it takes two parameters: type: the type of event we are interested in, identified by a string. many event emitters may emit more than one type of event: for example, a browse...
tabs - Archive of obsolete content
owser.contentdocument.body.innerhtml); // get the high-level tab back from the xul tab var highleveltab = modelfor(lowleveltab); console.log(highleveltab.url); } tabs.on("ready", maphighleveltolowlevel); note that directly accessing xul objects and web content like this means you're no longer protected by the compatibility guarantees made by the sdk's high-level apis. in particular, your code might not work with multiprocess firefox. globals functions open(options) opens a new tab. the new tab will open in the active window or in a new window, depending on the innewwindow option. example var tabs = require("sdk/tabs"); // open a new tab on active window and make tab active. tabs.open("http://www.mysite.com"); // open a new tab in a new window and make it active. tabs.open({ ...
...id red";' }); }); parameters options : object optional options: name type contentscriptfile string,array the local file urls of content scripts to load. content scripts specified by this option are loaded before those specified by the contentscript option. optional. contentscript string,array a string or an array of strings of code to be evaluated in the context. content scripts specified by this option are loaded after those specified by the contentscriptfile option. optional. contentscriptoptions object you can use this option to define read-only values for your content scripts. the option consists of an object literal listing name:value pairs for the values you want to provide to the content ...
url - Archive of obsolete content
s are present, a '?' followed by the parameters of the url, as a string. mirrors window.location.search. for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.search); // ?example=true&visible=yes dataurl methods tostring() returns a string representation of the data url. if base64 is true, the data property is encoded using base-64 encoding. returns string : the url as a string. properties mimetype the mime type of the data. by default is an empty string. parameters an hashmap that contains the parameters of the data url. by default is an empty object. base64 defines the encoding for the value in data property. data the string that contains the data in the data url. if the uri given to the construc...
... url as a string. properties mimetype the mime type of the data. by default is an empty string. parameters an hashmap that contains the parameters of the data url. by default is an empty object. base64 defines the encoding for the value in data property. data the string that contains the data in the data url. if the uri given to the constructor contains base64 parameter, this string is decoded. ...
content/loader - Archive of obsolete content
provides one of the building blocks for those modules that use content scripts to interact with web content, such as panel and page-mod. usage the module exports a constructor for the loader object, which inherits on(), once(), and removelistener() functions that enable its users to listen to events. loader adds code to initialize and validate a set of properties for managing content scripts: contenturl contentscript contentscriptfile contentscriptwhen contentscriptoptions allow when certain of these properties are set, the loader emits a propertychange event, enabling its users to take the appropriate action. the loader is used by modules that use content scripts but don't themselves load content, such as page-mod. modules that load their own content, such as panel and page-...
...g its users to take the appropriate action. the loader is used by modules that use content scripts but don't themselves load content, such as page-mod. modules that load their own content, such as panel and page-worker, use the symbiont module instead. symbiont inherits from loader but contains its own frame into which it loads content supplied as the contenturl option. ...
content/mod - Archive of obsolete content
experimental provides functions to modify a page content. globals constructors functions attachto(modification, window) function applies given modification to a given window. for example, the following code applies a style to a content window, adding a border to all divs in page: var attachto = require("sdk/content/mod").attachto; var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); parameters modification : object the modification we want to apply to the target. window : nsidomwindow the window to be modified. detachfrom(modification, window) function removes attached modification from a given window. if window is not spe...
... we want to modify attachto(style, window); parameters modification : object the modification we want to apply to the target. window : nsidomwindow the window to be modified. detachfrom(modification, window) function removes attached modification from a given window. if window is not specified, modification is removed from all the windows it's being attached to. for example, the following code applies and removes a style to a content window, adding a border to all divs in page: var { attachto, detachfrom } = require("sdk/content/mod"); var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); // ... detachfrom(style, window); parameter...
content/worker - Archive of obsolete content
globals constructors worker(options) creates a content worker. ...
... globals constructors worker(options) creates a content worker. ...
core/promise - Archive of obsolete content
side or outside handlers. flat chaining you can use then for chaining intermediate operations on promises (var data = readasync().then(parse).then(extract)). you can chain multiple then functions, because then returns a promise resolved to a return value of an operation and errors propagate through the promise chains. in general good rule of thumb is to prefer then based flat chaining. it makes code easier to read and make changes later: var data = readasync(url). // read content of url asynchronously then(parse). // parse content from the url then(extractquery). // extract sql query then(readdbasync); // exectue extracted query against db nested chaining flat chaining is not always an option though, as in some cases you may want to capture interme...
...ndler, it will not be be caught by the error handler. readasync(url).then(function (value) { throw new error("can't bar."); }, function (error) { // we only get here if `readasync` fails. }); to see why this is, consider the parallel between promises and try/catch. we are try-ing to execute readasync(): the error handler represents a catch for readasync(), while the value handler represents code that happens after the try/catch block. that code then needs its own try/catch block to handle errors there. in terms of promises, this means chaining your error handler: readasync(url). then(parse). then(null, function handleparseerror(error) { // handle here both `readasync` and `parse` errors. }); consuming promises in general, the whole purpose of promises is to avoid the so-calle...
dev/panel - Archive of obsolete content
="content"></div> </body> <script src="./my-panel.js"></script> </html> it doesn't have access to any privileged apis, including the add-on sdk apis. however, it can receive messages from the add-on that created it, and the add-on can pass it the debuggee so it can communicate with the debugger server the developer tools are targeting. ...
... targeting. communicating with the panel document the main add-on code can't directly access the panel document or any scripts loaded by the panel document. however it can send messages to the panel document using the postmessage method of panel. this is closely modeled on window.postmessage. you can only send the panel document message after you've received the ready event. ...
net/xhr - Archive of obsolete content
and the internet. threat model the xmlhttprequest object can be used by an add-on to "phone home" and transmit potentially sensitive user data to third parties. if access to the filesystem isn't prevented, it could easily be used to access sensitive user data, though this may be inconsequential if the client can't access the network. if access to local area networks isn't prevented, malicious code could access sensitive data. if transmission of cookies isn't prevented, malicious code could access sensitive data. attenuating access based on a regular expression may be ineffective if it's easy to write a regular expression that looks safe but contains a special character or two that makes it far less secure than it seems at first glance. possible attenuations before being exposed to unpr...
...cess sensitive data. if transmission of cookies isn't prevented, malicious code could access sensitive data. attenuating access based on a regular expression may be ineffective if it's easy to write a regular expression that looks safe but contains a special character or two that makes it far less secure than it seems at first glance. possible attenuations before being exposed to unprivileged code, this object needs to be attenuated in such a way that, at the very least, it can't access the user's filesystem. this can probably be done most securely by white-listing the protocols that can be used in the url passed to the open() method, and limiting them to http:, https:, and possibly a special scheme that can be used to access the add-on's packaged, read-only resources. finally, we need to...
test/assert - Archive of obsolete content
ass, because the types are different exports["test strict equality"] = function(assert) { assert.notstrictequal(1, "1", "test strict equality between 1 and '1'"); } parameters actual : object the actual result. expected : object the expected result. message : string optional message to log, providing extra information about the test. throws(block, error, message) assert that a block of code throws the expected exception. this method takes an optional error argument: to check that the exception thrown is of the expected type, pass a constructor function: the exception thrown must be an instance of the object returned by that function. to check that the exception thrown contains a specific message, pass a regular expression here: the message property of the exception thro...
... error : function|regexp either a constructor function returning the type of exception expected, or a regular expression expected to match the exception's message property. message : string optional message to log, providing extra information about the test. ...
ui/button/toggle - Archive of obsolete content
tton.state("tab").label; to learn more about this, see the api documentation for state(). updating checked you can update a toggle button's checked property in just the same way you update its other properties, but there's one extra thing you need to keep in mind. the checked property is not only updated directly by assignment, but is also updated when the user clicks the button (or when some code calls button.click()). when that happens, the button is updated for the window whose button was clicked. because window-specific state overrides global state, if you try to update checked by direct assignment to the button, this will be overridden by the user clicking the button. if you want to change this default behavior, you can delete the window-specific state in your button's onchange hand...
... listener to the first occurrence only of an event emitted by the button. the listener is automatically removed after the first time the event is emitted. parameters event : string the event to listen for. toggle buttons emit two types of event, "click" and "change". listener : function function that will be called on the event. removelistener() removes an event listener. for example, this code is equivalent to once(): button.on("click", handleclick) function handleclick(state) { console.log("button '" + state.label + "' was clicked"); button.removelistener("click", handleclick); } parameters event : string the event to listener is listening for. toggle buttons emit two types of event, "click" and "change". listener : function the listener to remove. destroy() destroy the ...
cfx to jpm - Archive of obsolete content
when you want to use the "utils" module in "main.js", you should use a path relative to "main.js", and prefix the path with "./" to indicate that it's a relative path: var utils = require("./utils"); however, with cfx you are also allowed to omit the "./": var utils = require("utils"); // this will not work with jpm! this second form will not work with jpm. ...
...ils = require("./utils"); however, with cfx you are also allowed to omit the "./": var utils = require("utils"); // this will not work with jpm! this second form will not work with jpm. ...
jpm - Archive of obsolete content
jpm is a command-line tool that enables you to test, run, and package add-ons. this is the reference page for jpm. see also jpm tutorial for getting started. jpm usage is: jpm [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -v, --version - print the jpm version number --addon-dir - directory for your source code, defaulting to the current directory installation jpm is distributed with the node package manager npm. installing npm there are two ways to get npm. download and install node.js from nodejs.org. node.js includes npm. or, if you have a package manager like apt, install npm via that. for example, in an ubuntu or debian terminal window, enter sudo apt-get install nodejs ...
... disables the copying of the profile used, which allows one to reuse a profile. jpm test use this command to run an add-on's unit tests. the command: looks for a directory called "test" within the current directory (or --addon-dir). opens every file in there whose name starts with "test-". make note of the hyphen after "test" in the filename. jpm test include a file called "test-mycode.js", but will exclude files called "test_mycode.js" or "testmycode.js") call every function exported from that file whose name starts with "test". jpm test see the tutorial on unit testing and the reference documentation for the assert module for more details on this. jpm test accepts the following options: -b --binary binary use the version of firefox specified in binary.
Displaying annotations - Archive of obsolete content
).parent().find( ':contains(' + annotation.anchortext + ')').last(); $(annotationanchor).addclass('annotated'); $(annotationanchor).attr('annotation', annotation.annotationtext); } save this in data as matcher.js. ...
...le> </head> <body> <div id="annotation"> </div> </body> </html> save this in data/annotation as annotation.html. annotation panel content script the annotation panel has a minimal content script that sets the text: self.on('message', function(message) { $('#annotation').text(message); }); save this in data/annotation as annotation.js. updating main.js finally, update main.js with the code to construct the annotation panel: var annotation = panels.panel({ width: 200, height: 180, contenturl: data.url('annotation/annotation.html'), contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('annotation/annotation.js')], onshow: function() { this.postmessage(this.content); } }); execute cfx run one last time. activate the annotator and enter ...
Overview - Archive of obsolete content
itionally, we use the notifications module to notify the user when the add-on's storage quota is full. working with the dom we'll use two page-mods to interact with the doms of pages that the user has opened. the selector enables the user to choose an element to annotate. ...
... working with data we'll use the simple-storage module to store annotations. because we are recording potentially sensitive information, we want to prevent the user creating annotations when in private browsing mode. the simplest way to do this is to omit the "private-browsing" key from the add-on's "package.json" file. ...
Storing annotations - Archive of obsolete content
tation = new annotation(annotationtext, anchor); simplestorage.storage.annotations.push(newannotation); } this function calls a constructor for an annotation object, which we also need to supply: function annotation(annotationtext, anchor) { this.annotationtext = annotationtext; this.url = anchor[0]; this.ancestorid = anchor[1]; this.anchortext = anchor[2]; } now we need to link this code to the annotation editor, so that when the user presses the return key in the editor, we create and store the new annotation: var annotationeditor = panels.panel({ width: 220, height: 220, contenturl: data.url('editor/annotation-editor.html'), contentscriptfile: data.url('editor/annotation-editor.js'), onmessage: function(annotationtext) { if (annotationtext) handlenewannotat...
...notation-text { border: solid 1px #eee; } #annotation-list .annotation-text { font-style: italic; } body { background-color: #f5f5f5; font: 100% arial, helvetica, sans-serif; } h1 { font-family: georgia,serif; font-size: 1.5em; text-align:center; } save these in data/list as annotation-list.html and annotation-list.css respectively. updating main.js here's the code to create the panel, which can go in the main function. var annotationlist = panels.panel({ width: 420, height: 200, contenturl: data.url('list/annotation-list.html'), contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('list/annotation-list.js')], contentscriptwhen: 'ready', onshow: function() { this.postmessage(simplestorage.storage.annotations);...
Logging - Archive of obsolete content
you don't have to require() anything to get access to the console. it is automatically made available to you. ...
...d"); try it out: create a new directory, and navigate to it execute jpm init, accepting all the defaults open "index.js" and add the line above execute jpm run firefox will start, and the following line will appear in the command window you used to execute jpm run: info: hello world! console in content scripts you can use the console in content scripts as well as in your main add-on code. the following add-on logs the html content of every tab the user loads, by calling console.log() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentscript: "console.log(document.body.innerhtml);" }); }); console output if you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages...
Bootstrapped extensions - Archive of obsolete content
-xhtml-xul. here is an example showing how to use a localized html page as an options page: github :: l10n-html-options. you can go to about:config and change the value of the preference general.useragent.locale to en-us and then to en-gb and then reload the open pages to see the localization change. further reading how to convert an overlay extension to restartless a step by step guide. ...
...gent.locale to en-us and then to en-gb and then reload the open pages to see the localization change. further reading how to convert an overlay extension to restartless a step by step guide. some code samples are provided. the page is based on and expanded from dave garrett's step-by-step guide to convert an old overlay based extension into a restartless addon. dave townsend provides a basic code base to load ui for each opened window in a bootstrapped extension. mark finkle provides some simple example code for restartless add-ons in mobile firefox, adding resources (like the options window) to bootstrapped extensions and using default preferences without a default/preferences/prefs.js file. kris maglione writes about the requirements for the cleanup procedures in bootstrapped extensio...
Examples and demos from articles - Archive of obsolete content
possible and minimalist example of such abstraction, which for this reason we named minidaemon. [article] image preview before upload [html] the filereader.prototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also our crossbrowser possible solution for image preview. determine if an element has been totally scrolled [html] this example shows how to determine whether a user has completely scrolled an element or not. [article] css pure-css dropdown menu [html] with the :hover pseudo-class you can create complex cascade algorithms. this is a common technique used, for example, in order to ...
...rticle] pure-css editable (pseudo)<select> [html] this example shows how it's possible to simulate an editable <select> through a fieldset of radioboxes and textboxes. [article] expandable elements [html] this example shows how it is possible to show/hide classes of elements in pure css. in this demo there is also an example of a "toggle button" rendered through a <label> element. [article] code snippets and tutorials javascript complete cookies reader/writer with full unicode support this little framework consists of a complete cookies reader/writer with unicode support. xml to json conversion snippets (jxon) jxon (lossless javascript xml object notation) is a generic name by which is defined the representation of javascript objects using xml. there are no real standards for this...
JavaScript Debugger Service - Archive of obsolete content
iring the service we acquire the service by calling the xpcom object. var jsd = components.classes["@mozilla.org/js/jsd/debugger-service;1"] .getservice(components.interfaces.jsdidebuggerservice); jsd.on(); // enables the service till firefox 3.6, for 4.x use asyncon if (jsd.ison) jsd.off(); // disables the service hooks jsd operates using the events hook mechanism. next, we add code to the various hooks. jsd.scripthook = { onscriptcreated: function(script) { // your function here }, onscriptdestroyed: function(script) { // your function here } }; jsd.errorhook = { onerror: function(message, filename, lineno, colno, flags, errnum, exc) { // your function here } }; // triggered when jsd.errorhook[onerror] returns false jsd.debughook = { onexecute: function(fra...
...er (jsdifilter filter, jsdifilter after) to insert the filter after a particular filter; you can pass null for jsdifilter after to insert at the head of the list. you can also use swapfilters (jsdifilter filter_a, jsdifilter filter_b) to swap filters, and removefilter(jsdifilter filter) to remove a filter. learning more a quick and dirty introduction by lei venkman javascript debugger source code firebug service source code jsd architecture (old) ...
LookupPrefix - Archive of obsolete content
efix which should work cross-browser. note that all gecko-based browsers (including firefox) support node.lookupprefix. this function is not necessary for gecko-based browsers when used in xhtml. ...
...ment.contenttype; // mozilla only // depends on private function _lookupnamespaceprefix() below and on https://developer.mozilla.org/en/code_snippets/lookupnamespaceuri // http://www.w3.org/tr/dom-level-3-core/core.html#node3-lookupnamespaceprefix // http://www.w3.org/tr/dom-level-3-core/namespaces-algorithms.html#lookupnamespaceprefixalgo // (the above had a few apparent 'bugs' in the pseudo-code which were corrected here) if (node.lookupprefix && htmlmode !== 'text/html') { // shouldn't use this in text/html for mozilla as will return null return node.lookupprefix(namespaceuri); } if (namespaceuri === null || namespaceuri === '') { return null; } switch (node.nodetype) { case 1: // node.element_node return _lookupnamespaceprefix(namespaceuri, node); case 9: // node.docu...
Page Loading - Archive of obsolete content
page loading on page load how to execute code each time a new page is loaded in browser/mail progress listeners progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. ...
... page loading on page load how to execute code each time a new page is loaded in browser/mail progress listeners progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events. ...
Post data to window - Archive of obsolete content
nputstream (because they eventually call nsiwebnavigation.loaduri()) while post data can be created using nsimimeinputstream. most of the time, post data starts as a data string in the form of "name1=data1&name2=data2&...", so you must convert it before passing the data to one of the methods. here is an example: var datastring = "name1=data1&name2=data2"; // post method requests must wrap the encoded text in a mime // stream const cc = components.classes; const ci = components.interfaces; var stringstream = cc["@mozilla.org/io/string-input-stream;1"]. createinstance(ci.nsistringinputstream); if ("data" in stringstream) // gecko 1.9 or newer stringstream.data = datastring; else // 1.8 or older stringstream.setdata(datastring, datastring.length); var postdata = cc["@moz...
... createinstance(ci.nsistringinputstream); if ("data" in stringstream) // gecko 1.9 or newer stringstream.data = datastring; else // 1.8 or older stringstream.setdata(datastring, datastring.length); var postdata = cc["@mozilla.org/network/mime-input-stream;1"]. createinstance(ci.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); // postdata is ready to be used as apostdata argument ... posting data to the current tab there is a convenience method in global scope (in firefox, chrome://browser/content/browser.js): loaduri(auri, areferrer, apostdata, aallowthirdpartyfixup); posting data to a new window window.opendialog('chrome://browser/content',...
Running applications - Archive of obsolete content
there are two ways to run programs. using nsiprocess the recommended way is to use the nsiprocess interface because it is crossplatform. using nsilocalfile.launch() this method is not implemented on all platforms, especially not on unix/linux! see nsilocalfile.launch() for details and make sure that all your target platforms support this method! this method has the same effect as if you double-clicked the file, so for executable files—it will just run the file without any parameters. for more information on nsifile/nsilocalfile, see file i/o. ...
......
xml:base support in old browsers - Archive of obsolete content
however, it is working in some of the cases tested. ...
...however, it is working in some of the cases tested. ...
Common Pitfalls - Archive of obsolete content
the first couple of items deal with loading content from a uri. it's important to create the uri correctly, and then check that it's secure to load. this will shield you from loading <tt>javascript:</tt> or <tt>chrome:</tt> uris when you shouldn't. ...
...it's something the user typed in the url bar). the one exception to all of the above, tha...
Listening to events in Firefox extensions - Archive of obsolete content
each of them. it also provides some use cases that may be of specific interest. types of events there are multiple types of events that application and extension authors can use to receive notifications from <xul:browser> and <xul:tabbrowser> elements to hear about changes relating to loads of the content contained within them. simple dom events registering for a dom event is done using with code such as the following: function callback(evt) { // do your processing here. check evt.target for the target of the event. } b.addeventlistener("event", callback, false) where b is the browser or tabbrowser you wish to watch for events from. keep in mind that the events may come from any frame within the browser or, for a tabbrowser, any of the browsers within it. some of the more interesti...
...re information about web loads a web progress listener can be used; these provide more details about the progress of loading data from the web. both browser and tabbrowser elements support the following: var progresslistener = { // add nsiwebprogressimplementation here } b.addprogresslistener(progresslistener); where b is the browser or tabbrowser you want to listen to events for. there are code snippets available that give more detail on using web progress listeners. for a tabbrowser, the above code will only get events from the browser that is currently displayed at the time the event occurs. in order to listen to events from all browsers, including those not currently being displayed, the following example can be used: var tabsprogresslistener = { // add tabs progress listener imp...
Offering a context menu for form controls - Archive of obsolete content
s to establish an overlay over the chrome for the window in which you want to allow context menus on form controls. <overlay id="formcontrolcontextmenu-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://formcontrolcontextmenu/content/overlay.js"/> </overlay> change the right-click behavior the overlaid code is responsible for adjusting the behavior of right-clicking on form controls. window.addeventlistener("load", function() { let settargetoriginal = nscontextmenu.prototype.settarget; components.utils.reporterror(settargetoriginal); nscontextmenu.prototype.settarget = function(anode, arangeparent, arangeoffset) { settargetoriginal.apply(this, arguments); if (this.istargetaf...
... as a result, all controls in the window will support a context menu when right-clicked, since we've changed the core behavior of context menus to override their default behavior of d...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
customization dialog won't work correctly without this. the way to include the file in the manifest is to add this line: style chrome://global/content/customizetoolbar.xul chrome://xulschoolhello/skin/toolbar.css if you are using xbl bindings (explained way ahead) for your toolbar items, you'll have to include the css files for those as well, each in a new line like the one above. we now have code that adds one or more buttons to the toolbar palette. the user can now use the customize dialog to add the buttons to the current firefox toolbars. in most cases this is not what you want as default behavior, because it would be very hard for the user to discover your buttons. keep in mind most users don't know how to customize toolbars in firefox. let's add our own toolbar. this is done in the ...
... specific css, and xbl bindings lose their internal state when moved around the dom. adding toolbar buttons to existing toolbars finally, there is the very common case where you just want to add one button to the main toolbar. in this case you still need to add the button to the palette using an overlay. in order to add your button to the main toolbar on first run, you'll have to use javascript code. keep in mind that you shouldn't assume anything about the location (or presence!) of any specific buttons; remember users could have moved them or removed them altogether. the toolbar code snippets page has a code sample you can use to do this. remember to validate if your button is already present, to prevent duplicates. it's also a good idea to set a preference that indicates that you added y...
The Box Model - Archive of obsolete content
there are two flexibility directions to consider. an hbox is as big as its contents horizontally, but it will occupy all the available space vertically. you can make an hbox flexible horizontally with the css property -moz-box-flex or the flex attribute. the same applies to a vbox, but in the other direction. unlike most style attributes, the flex attribute is considered acceptable to use in xul code. this is because this attribute is used much too often, and it would require a great deal of css code to avoid using it. at any rate, it can always be overriden using css, so your extension won't lose skinability because of it. flexibility is defined as a numeric value. the default value for most elements is 0, which means that the element will not stretch in the direction of its orientation, an...
...n this case, the labels and paddings in the buttons. if the label of 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 ...
User Notifications and Alerts - Archive of obsolete content
the alerts service this is a very good option when you want to alert users about events without requiring input from them. alerts are displayed in an os-specific way, so their look is native. you can associate an action to the user clicking on the alert. another advantage is that you use an xpcom service to do this (nsialertsservice), so you can easily trigger alerts from chrome and non-chrome code. on the other hand, alerts are displayed only temporarily using the alerts service is similar to using notification boxes: let alertsservice = cc["@mozilla.org/alerts-service;1"].getservice(ci.nsialertsservice); let title = this._bundle.getstring("xulschoolhello.greeting.title"); let message = this._bundle.getstring("xulschoolhello.greeting.label"); alertsservice.showalertnotification( "...
...ox to the overlay, but use css positioning to locate it where you want. this usually means that the box will be hovering on top of the page's content, and there are a few things you must know about this. first of all, switching tabs will probably make your alert disappear. this is probably due to the fact that the browser tab box uses a deck internally, and that affects z-indexing. you'll have to code around this using tab events in order to know when to re-display your alert. another problem you need to take into account is that transparency of floating xul on the mac os version of firefox 2 doesn't work. you'll end up with a box with a white background you can't get rid of . on firefox 3 and above, this seems to have been corrected, using the panel element. the bottom right corner of the br...
Overlay extensions - Archive of obsolete content
prior to firefox 4, and the gecko 2 engine that powers it, this was the only way to develop extensions. this methodology has largely been superseded by restartless extensions, and the add-on sdk, which is built on top of them. ...
...used in these newer types of add-ons. xul school xul school is a comprehensive add-on development tutorial, focusing on firefox extension development but mostly applicable to other gecko-based applications. more resources setting up your environment setting up the application for extension development. xul tutorials and reference for the user interface language used by xul extensions. code snippets sample code for many of the things you'll want to do. installing extensions how to install an extension by copying the extension files into the application's install directory. firefox add-ons developer guide a guide to developing overlay extensions. javascript code modules javascript modules available to extension developers. extension preferences how to specify the prefer...
Creating reusable content with CSS and XBL - Archive of obsolete content
you apply this technique in a simple demonstration. information: xbl bindings the structure provided by markup languages and css is not ideal for complex applications where parts need to be self-contained and reusable. you can place stylesheets in separate files, and you can place scripts in separate files. but you must link those files from the document as a whole. ...
...padding: .5em 2em; } open the document in your browser and press the button. this wiki does not support javascript in pages, so it is not possible to show the demonstration here. it looks something like this, before and after you press the button: notes about this demonstration: the html document links the document stylesheet as usual, but it does not link any javascript code. the document does not contain any buttons. it only contains the text of the button's label. the button is added by the binding. the document stylesheet links the binding. the binding links its own stylesheet, and it supplies its own content and javascript code. so the binding is self-contained. challenges change the xbl file so that the square doubles in width when it changes ...
List of Former Mozilla-Based Applications - Archive of obsolete content
e browser browser originally mozilla-based but now i believe the have a web-based tool (need reference for that) miro (formerly democracy player) video switched from xulrunner to webkit in version 3.0.2 moblin browser browser when moblin became meego it switched from a custom gecko-based browser to chrome nautilus file manager hasn't used mozilla code since version 2.0 raptr client gaming client was a xulrunner app initially but now uses adobe air rift technologies software installation over internet no longer using mozilla technology -- need confirmation and details second life virtual world desktop client switched from embedded mozilla browser to a plugin architecture with a qtwebkit plugin ...
...old article available about how borland embedded mozilla in kylix 2 mango im client last news item on site from ja...
Using content preferences - Archive of obsolete content
this makes it possible to write an extension that lets the user customize the appearance of specific web sites (setting the font size larger on sites that use obnoxiously small fonts, for instance). the content preferences service, implemented by nsicontentprefservice, offers functions for setting and retrieving preferences for specific sites or in the global preference space; global preferences are used whenever a site-specific preference isn't available. ...
...ilesystem directory related about:config preferences: browser.download.lastdir the last directory for any site use downloadlastdir.jsm for access to these preferences. browser.upload.lastdir path of a filesystem directory this preference is stored and retrieved automatically by file upload controls. spellcheck.lang language code (e.g., "en-us") private browsing requires gecko 9.0(firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) prior to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), the content preference service always stores preferences on disk. because of this, in private browsing mode, use of the content preference service needed to be avoided while in private browsing mode; instead, ...
Bonsai - Archive of obsolete content
that lets you perform queries on the contents of a cvs archive; you can: get a list of checkins, see what checkins have been made by a given person, or on a given cvs branch, or in a particular time period. it also includes tools for looking at checkin logs (and comments); doing diffs between various versions of a file; and finding out which person is responsible for changing a particular line of code ("cvsblame"). start at the main bonsai query page or seamonkey tree control page here are some example queries that will give you a taste of what bonsai is capable of: today's checkins to the mozilla source mainline. checkins to any branch of xfe by ramiro between 26-feb-1998 and 12-may-1998 differences between revisions 3.1 and 3.3 of the file mozilla/cmd/xfe/forms.c that's a small s...
...e mainline. checkins to any branch of xfe by ramiro between 26-feb-1998 and 12-may-1998 differences between revisions 3.1 and 3.3 of the file mozilla/cmd/xfe/forms.c that's a small sample, but it should be enough to get you started. play around with the various options on the main bonsai query page. if you're updating our cvs tree you'll need to learn about hacking with bonsai. bonsai source code the source code to the bonsai tool itself is also available, check out the information available at the bonsai project page. original document information author(s): jamie zawinski last updated date: september 8, 2004 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
izard). if a wizard gives you a checkbox to create an empty project, then check it. otherwise you'll delete files later. again note that the resulting dll filename must start with "np", so either call your project like this or rename the file later delete the .cpp and .h and readme files from the project and disk (if you did not create an empty project) copy the npruntime sample plugin source code into the dir of the new vs project and add the files to the project using the vs gui (.cpp files to "source files", .h files to "header files", .rc file to "resource files"). samples can be obtained from: https://developer.mozilla.org/en/plugins/samples_and_test_cases get the npapi sdk. add the npapi sdk include path (example : c:\npapi-sdk\headers) to project properties|(all configurations)|c+...
...e "test.html" and begin testing. make sure the mimetypes of your html embed tags match the mimetype specified in your nprt.rc file and the top of your npp_gate.cpp file version issues if vc++ compiler throws you error c2664 on 'drawtext' function call, you may replace it by 'drawtexta'. in fact, all win32 api functions dealing with character strings can be added an 'a' to the end to avoid unicode cast errors. visual c++ 2008 express don't support c99 standard about int32_t, uint32_t. you have to add #include "nptypes.h" in top of plugin.h file. feel free to append here your issues fixes if the above guide helped you. ...
Making a Mozilla installation modifiable - Archive of obsolete content
mage files are in binary gif, jpg, or png format and must be edited with an image editing program. the files are then collected into a series of jar archives, which are just zip files that contain a specially formatted "manifest" file which describes the contents of the archive so mozilla knows what to do with them. although jar archives are binary files, mozilla's ui is not compiled into machine code; mozilla instead builds its ui from the non-compiled files in the archive each time it starts up. because of this, we can modify the files in the archive and see our changes to the ui merely by restarting the application. this makes modifying mozilla's ui much easier than for many other applications. although mozilla stores the ui files in jar archives, it can also access them in their original, ...
...ve and see our changes to the ui merely by restarting the application. this makes modifying mozilla's ui much easier than for many other applications. although mozilla stores the ui files in jar archives, it can also access them in their original, unarchived form, which is useful for the extensions developer because it makes it unnecessary to extract the files from the archive before changing the code and then re-add them to the archive afterwards. instead, you only have to extract them once and can then make as many modifications as you like. to make mozilla modifiable, we will first extract the ui files from the archives using an unzip utility, then edit mozilla's registry of ui files to use the extracted files instead of the original jar archives. the archives are stored within the chrome s...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
contents.rdf goes in the content sub-subdirectory: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <rdf:seq about="urn:mozilla:package:root"> <rdf:li resource="urn:mozilla:package:tinderstatus"/> </rdf:seq> <rdf:description about="urn:mozilla:package:tinderstatus" ...
...hrome#"> <rdf:seq about="urn:mozilla:package:root"> <rdf:li resource="urn:mozilla:package:tinderstatus"/> </rdf:seq> <rdf:description about="urn:mozilla:package:tinderstatus" chrome:displayname="mozilla tinderstatus extension" chrome:author="myk melez" chrome:name="tinderstatus" chrome:extension="true" chrome:description="displays tinderbox status for the mozilla codebase."> </rdf:description> <rdf:seq about="urn:mozilla:overlays"> <rdf:li resource="chrome://navigator/content/navigator.xul"/> </rdf:seq> <rdf:seq about="chrome://navigator/content/navigator.xul"> <rdf:li>chrome://tinderstatus/content/tinderstatusoverlay.xul</rdf:li> </rdf:seq> </rdf:rdf> install.js, on the other hand, goes into the tinderstatus-installer directory: initinstall( "...
Tinderbox - Archive of obsolete content
tinderbox is a web tool for tracking the status of the mozilla source code. it consists of a set of client machines that continuously build and test mozilla and report their results back to a server that makes those results available via a web page. the tool enables mozilla.org to be immediately notified of changes to the code that prevent mozilla from compiling and running (or compromise performance and footprint) so they can get someone to fix the problem or reverse the changes. mozilla engineers regularly check tinderbox before changing the code because changes are prohibited while the codebase is broken. the mozilla sheriff, a rotating position responsible for watching the code and getting engineers to fix breakage, checks tinderbox even more regularly. while it isn't difficult to ...
...o show users the worst possible situation, i.e. if any clients have failed to build, we will display a red icon that signifies a build failure; if all clients built successfully but some failed tests we will display an orange icon that signifies a test failure. only if all clients reported both successful builds and successful tests will we display a green icon that signifies all is well with the code. « previousnext » ...
DTrace - Archive of obsolete content
in d (no, not that one). mozilla dtrace support has been added by the sun dtrace team and can be used on solaris 10 and mac os x 10.5. dtrace has been largely supplanted by the gecko profiler and other tools, so this documentation has been archived. if you find that there are still use cases of consequence, you're welcome to file a documentation bug. the dtrace probes currently built into the codebase may be enabled by default in the future, but for now you'll need to create a build with --enable-dtrace (on mac os x you also have to use at least the 10.5 sdk for --with-macos-sdk, unlike the common configuration that uses the 10.4 sdk). trunk nightly builds with shark support (*-mac-shark.dmg here) are built with --enable-dtrace. documentation writing scripts ...
... sdk for --with-macos-sdk, unlike the common configuration that uses the 10.4 sdk). trunk nightly builds with shark support (*-mac-shark.dmg here) are built with --enable-dtrace. documentation writing scripts a general introduction to writing d scripts and using the built-in mozilla probes. optimizing javascript with dtrace a guide on profiling javascript code using dtrace. adding probes a guide on creating probes and the build system magic needed to add probes to your code. pounce on dtrace a guide to using dtrace on mac os x 10.5. dtrace for web developers how to use dtrace to profile your web application. view all... community dtrace forums #dtrace on irc.freenode.org sun's dtrace howto ...
Dehydra Frequently Asked Questions - Archive of obsolete content
for patterns in control flow graphs (cfgs). images of those graphs reminded me of the multiheaded hydra monster. thus de-hydra can be thought of as a decapitating tool for slaying cfgs. currently dehydra does not provide the cfg functionality, this functionality is now provided by treehydra. ...
...note that some of the analyses may require treehydra. please see building with static checking for more information about static checking builds in mozilla. ...
Dehydra Function Reference - Archive of obsolete content
mode werror boolean: turns js warnings into errors gczeal int: this is a write-only parameter to set turn on frequent garbage collection. it is a mainly useful for debugging dehydra for rooting bugs. gczeal is only enabled when spidermonkey and dehydra are compiled with debug macro defined. require() example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) print a warning message using the gcc warning mechanism. if -werror is specified this will cause compilation to fail. optional: code is an integer parameter that allows warnings to be enabled(-wfoo) and disabled(-wno-) on the gcc commandline. this parameter is used when the first argument to warning() is an integer. it is not possible to define new warnings in dehydra, thus one ha...
...msg is a string to be presented as a gcc warning optional: loc is the location that should be reported for the warning. ...
Dehydra Object Reference - Archive of obsolete content
introduction dehydra represents c++ types and variables as javascript objects. the objects are designed to distill that type system to the minimum such that it can be easy to match on. often, the best way to become familiar with the dehydra objects is to print out the objects: dehydra example code an online tool for pretty-printing dehydra data understanding properties dehydra only sets properties that are applicable. for example, class types and typedefs are declared and will have a .loc property. intrinsic types such as "int" are not declared and will not have a .loc. dehydra only sets boolean flags when they are true. for example, a pointer type will have .ispointer == true, but a class type will not have an .ispointer property. common properties property type description ...
...t a class type will not have an .ispointer property. common properties property type description .loc location object source location of a type or declaration. .attributes array of objects attributes of the type or declaration. each member of the array has the following properties: { name: string, value: string or number, if applicable } see an example on enforcing final classes. code can be annotated with arbitrary user attributes: __attribute__((user("customstring"))). variable objects dehydra presents ast nodes as variables. these types are used to represent variables, functions, assignments, etc. the following properties are usually available: property type description .name string the function or variable name. .type type object the type of this function or ...
Content states and the style system - Archive of obsolete content
would be :hover, :active, :focus, :target, :checked). we will focus on describing how changes in content state are handled. generally, whenever a node's content state changes, style has to be reresolved (recomputed) for that node and all of its descendants. this is an expensive operation, however, so the style system tries to minimize the number of style reresolves it does. to this end, when a <code>contentstateschanged</code> notification is dispatched for a content node the first thing that's done is to is to check whether the content state change something could affect any styles. this is done by walking the list of all css2.1 simple selectors in all style sheets applied to the page that have a state-dependent pseudo-class as part of the selector. this list is created during the parsing ...
...h selectors that now match and selectors that no longer match. for example, say we have the selectors: a:hover a:not(:hover) div:hover and the hover state on some node changes. we then try matching the node against these selectors, with the assumption that both :hover and :not(:hover) match the node. so the effect will be that of matching a node against the selectors: a a div the code that implements this is in the selectormatches method, which is passed the list of states that changed in the astatemask parameter. ...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
ntext. nsdocumentopeninfo::prepare is passed the channel to open. it calls getinterface on the window context to get and save that context's nsiuricontentlistener. openchannel returns to openuri which just opens the channel, setting the nsdocumentopeninfo as the stream listener. onstartrequest notification comes back from necko nsdocumentopeninfo::onstartrequest checks the response status code on the channel for http channels and drops the load on the floor if warranted (e.g. 204 or 205 responses). then it calls nsdocumentopeninfo::dispatchcontent nsdocumentopeninfo::dispatchcontent starts doing the real dirty work. first it checks whether the channel has "content-disposition: attachment" set. if so, it skips trying to find an internal viewer and goes right over to looking for a stre...
...type. if that is the case, dispatchcontent tries to convert the data to some other content type by looking for a stream converter (implementing nsistreamconverter) that takes our content type as input and outputs the magic type "*/*" (which just means we'll take anything it can give us). if the type of the data is "application/x-unknown-content-type" (another magic type), this is where nsunknowndecoder would be instantiated. the conversion attempt is made by calling convertdata. this creates a new nsdocumentopeninfo object and sets it as the output streamlistener of the converter. this way, once we know what type we've managed to get we can attempt to redispatch it. if a converter is found, we hook that up as our stream listener and are done -- we just need to pump data into it and let the dow...
GRE - Archive of obsolete content
tions as if they were a gre. the mozilla suite never supported a gre on mac. xulrunner: the new gre xulrunner is the new version of the gre, which not only allows embedding but is capable of bootstrapping entire xul applications such as firefox. xulrunner supports or is planned to support embedding on all three major platforms (windows, mac, and linux). finding and using a gre from application code avoid linking directly against xpcom.dll if an application wishes to use the gre, it must take careful steps to ensure that it links against the proper libraries. if you link directly against xpcom.dll/libxpcom.so (xpcom.lib import lib), your application will not launch unless xpcom.dll is in your path. this prevents dynamically finding a compatible gre at runtime. find a compatible gre note...
... embedder to specify what version(s) of gre are appropriate, and to specify any special features the gre must have (currently there are no special features defined). statically link to xpcomglue.lib (the "standalone glue") the solution is to statically link against xpcomglue.lib, also known as the "standalone glue" (see xpcom glue). this library provides a layer of indirection between embedding code and xpcom. to use the xpcom glue, you must follow these steps: compile your code with xpcom_glue defined. link with xpcomglue.lib (not xpcomglue_s.lib!). don't link against the nspr libs. find a compatible gre (see above). dynamically link to that gre using the xpcomgluestartup() function. see environment variables below. initialize xpcom and do your work; when finished, shut down xpcom. ...
HTTP Class Overview - Archive of obsolete content
the mozilla http implementation. it's meant as a guide to developers wishing to understand or extend the mozilla http implementation. ...
...nse codes intercepts progress notifications nshttpconnection implements nsistreamlistener & nsistreamprovider talks to the socket transport service feeds data to its transaction object routes progress notifications nshttpconnectioninfo identifies a connection nshttptransaction implements nsirequest encapsulates a http request and response parses incoming data nshttpchunkeddecoder owned by a transaction strips chunked transfer encoding nshttprequesthead owns a nshttpheaderarray knows how to fill a request buffer nshttpresponsehead owns a nshttpheaderarray knows how to parse response lines performs common header manipulations/calculations nshttpheaderarray stores http "<header>:<value>" pairs nshttpauthcache stores authentication credentials for ...
Creating a Help Content Pack - Archive of obsolete content
actual file names without path when needed later. you don't actually need this attribute if you don't want it, but it's a useful shorthand to save typing. next, we need to describe where to find the glossary, index, and table of contents. (we're still not actually to the point where we're describing the actual data in each of these, so we'll just use some filler data for now.) add the following code inside the rdf:description element you just created: <nc:panellist> <rdf:seq> </rdf:seq> </nc:panellist> you'll create the relevant information descriptions within the rdf:seq element. the location of each of the glossary, index, and table of contents data sources is stored in one rdf:description element contained within one rdf:li element, like so: <...
...sults found" is accessed. this attribute is required. the sample page chrome://help/locale/welcome.xhtml has a section on searching which may be a useful link to use here. note that you can use the nc:datasources attribute to inherit content from other content packs. one common use of this is to inherit the small using the help window article provided with the viewer. ...
Helper Apps (and a bit of Save As) - Archive of obsolete content
ns come in. knows how to launch a helper application on the data based on the nsimimeinfo. knows how to save the data to disk at a given location if the user decides to do so. nsexternalapphandler::onstartrequest creates a temporary file with a salted name to hold the data. decides on a suggested filename for the data in case it will be saved. decides whether the data should be content-decoded (based on some not-so-great heuristics). decides whether the user should be prompted (based on a preference). calls show() on the nsihelperapplauncherdialog, which asynchronously puts up the helper app dialog. nsexternalapphandler::ondataavailable here we just copy the newly arrived data over into our temporary file. if any read or write errors occur, abort the whole process: cancel the ...
...imeinfo came from. last-ditch check for executable files here. mac: use the launchwithdoc() method on nsilocalfilemac. unix: launch directly via nsiprocess. security considerations multiple checks for whether a file is executable (on windows) to keep from launching such files via ::shellexecute(). checks happen in onstartrequest, in the helper app dialog, and as a last ditch in the launching code. limitations of nsimimeinfo no way to say "do whatever the os default is." no support for command-line arguments. no support for multiple commands connected by pipes (mostly useful on unix). ongoing work support synchronous dialogs, not just asynchronous ones (fixes many issues related to pre-downloading, content-decoding, etc). reworking the nsimimeservice api to improve the quality o...
Hidden prefs - Archive of obsolete content
mported from mozilla.org and last updated in 2002. this page has been flagged by editors or users as needing technical review. until it is fully reviewed, it may contain inaccurate or incorrect information. ...
...ref ("mail.addr_book.mapit_url.format" ) the format for this pref is: @a1 == address, part 1 @a2 == address, part 2 @ci == city @st == state @zi == zip code @co == country if the pref is set to "", no "get map" button will appear in the addressbook card preview pane. the default (defined in mailnews.js) is: pref("mail.addr_book.mapit_url.format", "http://www.mapquest.com/maps/map.adp...st&zipcode=@zi"); addressbook quick search query pref ("mail.addr_book.quicksearchquery.format" ) the format for this pref is: @v == the escaped value typed in the quick search bar in the addressbook every occurance of @v will be replaced. note, the ui has "name or email contains:". this entity (searchnameoremail.label) is defined in messenger.dtd. so if you change the quick search query to match based ...
importUserCertificates - Archive of obsolete content
rack. 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. deprecatedthis feature has been removed from the web standards. though some browsers may still support it, it is in the process of being dropped. avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. be aware that this feature may cease to work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. resultst...
...is ignored. if the string is null and no certificate with the same dn exists in the user's certificate store, personal security manager uses the following pattern to derive the nickname: <tt><common name>'s <issuer name> id</tt>. "certrepstring" this string is the cmmf certification response from the ca that contains the user's certificate(s). the response is base-64 encoded. forcebackup this is a boolean argument. it allows the ca or ra to indicate to the client whether to force the user to back up a newly issued certificate (pkcs #12). the importusercertificates() method is used to import newly issued certificates for the user. the private key for the certificates must already reside in the user's personal private key database. th...
JavaScript crypto - Archive of obsolete content
rack. 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. deprecatedthis feature has been removed from the web standards. though some browsers may still support it, it is in the process of being dropped. avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. be aware that this feature may cease to work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. using t...
...he crypto system you are interested by setting window.crypto.enablesmartcardevents to true. you can then register event handlers for these events with the document.addeventlistener() method. two smart card related events are generated: smartcard-insert when smartcards are inserted, and smartcard-remove when smartcards are removed. web sites which use ssl clientauth login could use the following code to refresh the page on token insertions and removals: <!doctype html> <p>... <script> function onsmartcardchange() { window.location.reload(); } function register() { window.crypto.enablesmartcardevents = true; document.addeventlistener("smartcard-insert", onsmartcardchange, false); document.addeventlistener("smartcard-remove", onsmartcardchange, false); } function deregister() { docum...
Jetpack Snippets - Archive of obsolete content
note: this page documents the jetpack prototype, which is no longer under active development. read the experiment report for what we learned from it and the blog post announcing the first sdk release for what we're up to next! bits of code that may come in handy. ...
...r what we're up to next! ...
Simple Storage - Archive of obsolete content
storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this method. ...
...ple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this method. examples this code persistently stores some data: jetpack.future.import("storage.simple");var mystorage = jetpack.storage.simple;mystorage.fribblefrops = [1, 3, 3, 7];mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt));var bar = mystorage.heimelfarbs.bar;jetpack.notifications.show(bar.baz); that's all there is to it! note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object. they could have ...
Simple Storage - Archive of obsolete content
storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this method. ...
...object is automatically populated when a feature is loaded, but a feature may force the object to read from disk by calling jetpack.storage.simple.open(). don't abuse this method. examples this code persistently stores some data: jetpack.future.import("storage.simple"); var mystorage = jetpack.storage.simple; mystorage.fribblefrops = [1, 3, 3, 7]; mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt)); var bar = mystorage.heimelfarbs.bar; jetpack.notifications.show(bar.baz); that's all there is to it! note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object. they could ha...
statusBar - Archive of obsolete content
its acutally not implemented in the current version. ...
...its acutally not implemented in the current version. onready (event) occurs when the item was loaded onunload (event) triggers when the item was removed. ...
Microsummary XML grammar reference - Archive of obsolete content
generators installed from the web via nssidebar::addmicrosummarygenerator are identified b...
...generators installed from the web via nssidebar::addmicrosummarygenerator are identified by the remote url from which they were downloaded, and firefox ignores the value of this attribute for them. ...
Mozilla Application Framework - Archive of obsolete content
of the exploding world of web services. xpinstall our cross-platform installer for trivial packaging and installation of your mozilla framework applications. and much much more... tools venkman a javascript debugger with support for breakpoints, conditional breakpoints, local variable inspection, watch variables, single step, stop on error, profile data collection, report generation, code reformatting (pretty printing), and more. dom inspector a tool for inspecting and editing the structure and widgets of your user interface while your application is running. xulmaker a gui builder currently under development that lets you drag-and-drop widgets onto a grid to build your user interface. bugzilla the mozilla bug tracking webtool to help you track progress in fixing bu...
...structure and widgets of your user interface while your application is running. xulmaker a gui builder currently under development that lets you drag-and-drop widgets onto a grid to build your user interface. bugzilla the mozilla bug tracking webtool to help you track progress in fixing bugs and implementing features that affect your applications. lxr a web interface to the mozilla codebase that shows you every file in the repository as well as a line-by-line breakdown of who changed which line when in each file bonsai a web interface to the checkin log that you can query for checkins between certain dates, of certain files, or by certain developers. tinderbox our 24/7 build and test webtool that constantly builds, tests, and reports on the mozilla application suite on...
Overview of how downloads work - Archive of obsolete content
click on the images to display them "stand-alone" in the browser, which may resize them to fit the browser window. ...
...click on the images to display them "stand-alone" in the browser, which may resize them to fit the browser window. ...
Porting NSPR to Unix Platforms - Archive of obsolete content
lled the local threads only version of classic nspr. you should attempt to do a local threads only port first. the classic nspr source files are in <tt>mozilla/nsprpub/pr/src/threads</tt> and <tt>mozilla/nsprpub/pr/src/io</tt>. if the platform has pthreads, you can also use pthreads as an implementation strategy. this is referred to as pthreads nspr. pthreads nspr has relatively orthogonal source code in the thread management, thread synchronization, and i/o area. the pthreads source files are in <tt>mozilla/nsprpub/pr/src/pthreads</tt>. i use the netbsd port i recently received as an example to illustrate the mechanical part of the porting process. there are a few new files you need to add: <tt>mozilla/nsprpub/config/netbsd.mk</tt> the name of this file is the return value of <tt>uname -s<...
...fy the following files: <tt>mozilla/nsprpub/pr/include/md/_pth.h</tt> files in mozilla/nsprpub/pr/src/pthreads, most likely <tt>ptthread.c</tt> and <tt>ptio.c</tt> testing your port we have some unit tests in <tt>mozilla/nsprpub/pr/tests</tt>. first a warning: some of the tests are broken. further, we don't have documentation of our unit tests, so you often need to resort to read the source code to understand what they do. some of them respond to the <tt>-h</tt> command line option and print a usage message. <strike>henry sobotka of the os/2 mozilla porting project has a web page at http://www.axess.com/users/sobotka/n.../warpztjs.html with good documentation of the nspr unit tests</strike>. here are my favorite tests. for thread management and synchronization: <tt>cvar -d</tt> <tt>cv...
Priority Content - Archive of obsolete content
netscape and xslt 1.0 wiki location: transforming xml with xslt migrators: serge k. keller in progress: rapid application development with mozilla original: author's page and planned host, ben's temporary host wiki location: toc and links page still under construction. migrators: nigel mcfarlane and ben karel shorter works mostly completed: bypassing security restrictions and signing code original: bypassing security restrictions and signing code wiki location: bypassing security restrictions and signing code migrators: joel stanley i added the related links from the original article. however, the link about signtool seems to be broken. anyone knows what to do? mathieu deaudelin 15:22, 17 may 2005 (pdt) mostly completed: netscape gecko compatibility handbook original: nets...
...cle. however, the link about signtool seems to be broken. anyone knows what to do? mathieu deaudelin 15:22, 17 may 2005 (pdt) mostly completed: netscape gecko compatibility handbook original: netscape gecko compatibility handbook wiki location: gecko compatibility handbook migrators: mathieu deaudelin there are inline examples on this page that cannot be migrated. they are dependant on some code that cannot be integrated in the page. dependant on: updating dhtml web pages for next generation browsers on devedge the tune-up wizard (see below, in the wishlist section) mostly completed: popup window controls devedge article migrators: mathieu deaudelin there are inline examples on this page that cannot be migrated. they are dependant on some style instructions that can only be placed ...
Frequently Asked Questions - Archive of obsolete content
note: this page is extremely out of date. what is the status of the svg implementation? we currently maintain two documents to help answer this question: a status page for svg in firefox 1.5+ and a status page for svg in the development trunk. why does mozilla show source code/gibberish instead of svg? there are two possible reasons for this: a simple mistake in the svg file, or a misconfigured server. if there's a grey area at the top of the source with the text "this xml file does not appear to have any style information associated with it" then the problem is with the svg file. to be valid the root <svg> tag in svg files must have at least the following two "namespace bindings". <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> actually the ...
...the problem is with the svg file. to be valid the root <svg> tag in svg files must have at least the following two "namespace bindings". <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> actually the second binding isn't always required, but unless you understand namespaces, we'd strongly recommend you include it. for more information see this link. if source code is displayed without a gray area at the top, or if you just see gibberish, then the problem is server misconfiguration. when servers send user agents an svg file they must tell the user agent that the file has the mime type "image/svg+xml", and if the svg file is stored gzipped they must tell the browser that too. mozilla is strict about this, and no, it's not a bug. failing to respect the mime t...
File object - Archive of obsolete content
ue if the file exists. file.canread true if the file can be read. file.canwrite true if the file can be written. file.canappend true if the file is in append mode. file.canreplace true if the file is in replace mode. file.isopen true if the file is open. file.type a string specifying the type of data or encoding contained in the file. currently "ascii" (ascii), "binary" (utf-8) or "unicode" (ucs-2). (xxx note -- ascii might imply asciiz) file.mode a string describing the mode used to open the file. file.creationtime a date object representing the time when the file was created. file.lastmodified a date object representing the time when the file was last modified. file.size the length of the file in bytes; undefined(?) for directories and pipelines. file.hasrandomaccess tr...
...as meaning when the file is a directory. file.mkdir() create a directory. directory will be created in the same directory as the file, unless the file is a directory, in which case, the directory will be created in that directory. xxx file.tostring() returns the canonical path to the file. file.tourl() returns a file:// url describing the file relative to the local file system. url is uri-encoded. examples example: hello, world file.output.writeln("hello, world"); example: writing a new file var file = new file("myfile.txt"); file.open("write,create", "text"); file.writeln("the quick brown fox jumped over the lazy dogs"); file.close(); example: reading from a file var data; var file = new file("myfile.txt"); file.open("read", "text"); data = file.readln(); file.close(); example...
Table Layout Regression Tests - Archive of obsolete content
e 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 in your .mozconfig file). to build the layout...
...to bottom: auto auto 0[0x0]tw null auto 0[0x0]tw null 0 auto |0 0 0 normal normal 0[0x0]tw normal |0 11 1,000000 0 0 0 0 0 0 0 0 0 0 0 [none]|0 0 0 -1 1 |0 0 0 null comparison for file:///e:/moz_src/mozilla/layout/html/tests/table/core/baseline/standards1.rgd failed. the first regression test has failed and it is marked so. adding new regression tests once you have checked in the code: please add your testcase for the bug to the regression tests. a testcase should only contain local files. place the images in table/images block/images or (don't forget cvs commit -kb) and the test file in the table/bugs or block/bugs directory. update the rtest.lst file in the corresponding directory in order to include your file. additional notes there is a special type of frame dump...
Abc Assembler Tests - Archive of obsolete content
tests can be found in /test/acceptance/abcasm and end with the .abs extension. the tests are run using the same runtests.py script that is used for the actionscript tests. ...
... you may not use this file except in compliance with * the license. you may obtain a copy of the license at * http://www.mozilla.org/mpl/ * * software distributed under the license is distributed on an "as is" basis, * without warranty of any kind, either express or implied. see the license * for the specific language governing rights and limitations under the * license. * * the original code is [open source virtual machine.]. * * the initial developer of the original code is * adobe system incorporated. * portions created by the initial developer are copyright (c) 2009 * the initial developer. all rights reserved. * * contributor(s): * adobe as3 team * * alternatively, the contents of this file may be used under the terms of * either the gnu general public license versio...
Running Tamarin acceptance tests - Archive of obsolete content
you should set environment variables as described above except for avm, which should be: $ export avm=$tamarin_build_top/platform/android/android_shell.py where $tamarin_build_top is your main tamarin repo folder. note that avm needs to...
...mshell /data/local/tamarin/avmshell $ adb shell 'chmod 777 /data/local/tamarin/avmshell' copy android_runner.sh, if it doesn't already exist on the phone in /data/local/tamarin $ adb push tamarin-redux/platform/android/android_runner.sh /data/local/tamarin/android_runner.sh $ adb shell 'chmod 777 /data/loca/android_runner.sh' test it out with a simple .abc or no args for usage (should return exitcode=0) $ tamarin-redux/platform/android/android_shell.py hello.abc hello exitcode=0 test it out by retrieving the version information of the shell on the android device $ $avm -dversion shell 1.4 debug build 6299:455bca954565 features avmsystem_32bit;avmsystem_unaligned_int_access;avmsystem_little_endian;avmsystem_arm;avmsystem_unix; avmfeature_jit;avmfeature_abc_interp;avmfeature_selftest;avmfeature...
Running Tamarin performance tests - Archive of obsolete content
just type the following commands after making sure you've set the environment variables correctly. $ cd /test/performance $ ./runtests.p...
...just type the following commands after making sure you've set the environment variables correctly. $ cd /test/performance $ ./runtests.py note on using an emulator: the emulator does seem to support hardware floa...
Tamarin - Archive of obsolete content
tamarin build documentation how to get, build, and use tamarin. tamarin build system documentation documentation on how the tamarin build system works and how to modify. tamarin commit hook instructions for installing and using the mercurial hook for tamarin. tamarin acceptance testing instructions on how to validate changes to the tamarin source code. tamarin pages at wiki.mozilla.org more documentation. mmgc overview an overview of the tamarin garbage collector. nanojit lir in nanojit, lir is the source language for compilation to machine code. tamarin strings documentation the implementation of tamarin strings has changed. this page is a how-to about the ch...
... tamarin doxygen documentation documentation for the latest release. ...
Treehydra Manual - Archive of obsolete content
callbacks and gcc intermediate representations like dehydra, treehydra sends program representations to the user javascript via callbacks. there are 3 treehydra callbacks. ...
...callbacks and gcc intermediate representations like dehydra, treehydra sends program representations to the user javascript via callbacks. there are 3 treehydra callbacks. ...
URIs and URLs - Archive of obsolete content
in the nsstandardurl object with pointers (position and length) to each basic segment and for the more global segments like path and prehost for example. necko provides pre written urlparsers for schemes based on hierachical naming systems. escaping to be able to parse an url safely it is sometimes necessary to "escape" certain characters, to hide them from the parser. an escaped character is encoded as a character triplet, consisting of the percent character "%" followed by the two hexadecimal digits representing the octet code. for example, "%20" is the escaped encoding for the us-ascii space character. another quote from rfc 2396: a uri is always in an "escaped" form, since escaping or unescaping a completed uri might change its semantics. normally, the only time escape encodings can sa...
...he uri is being created from its component parts; each component may have its own set of characters that are reserved, so only the mechanism responsible for generating or interpreting that component can determine whether or not escaping a character will change its semantics. likewise, a uri must be separated into its components before the escaped characters within those components can be safely decoded. this implies that the segments of urls are escaped differently. this is done by ns_escapeurl which is now part of xpcom, but started as part of necko. the information how to escape each segment is stored in a matrix. also a string should not be escaped more than once. necko will not escape an already escaped character unless forced by a special mask that can be used if it is known that a string...
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
problem statement win-16 (aka, windows 3.1, et al), is unique in that the architecture depends on the operating environment (i.e., windows) knows the address of the stack, and that there is only one such address. consequently, implementing threads, with their implication of a unique stack for each thread, requires that the nspr copy the stacks during thread context switches. the actual copying of the stack is not such a hardship as one would imagine. ...
...of convoluted logic, and finds its way into an object that is shared. ...
Venkman Internals - Archive of obsolete content
as with any complex application, aspects of the design may not be clear for new readers of the source. 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. ...
...e is one scriptmanager per url (web page). this method is set into jsdiscripthook.onscriptcreated venkman-views.js views are the panels shown within the venkman window. for example, the "open windows" view shows the browser's windows. venkman-records.js a "record" seems to be data underlying a view. for example, framerecord represents a javascript stack frame. venkman-msg.js localization code, reads venkman.properties from a subdirectory of "locale" and injects variables. things like msg.alert define variables msg_alert. venkman-utils.js defines the dd debug dump and friends windowrecord representation of the open windows. filecontainerrecord - list of script tags found in the parent record's window.document property. to obtain the antecedent files: doc.getelementsbytagname("...
Video presentations - Archive of obsolete content
how pages are built using the dom this presentation describes how documents are loaded and the dom tree is constructed. (as quicktime; 198 mb) laying out and drawing documents (slides) this presentation describes how a document is laid out and painted to the display by the gecko engine. ...
... how pages are built using the dom this presentation describes how documents are loaded and the dom tree is constructed. (as quicktime; 198 mb) laying out and drawing documents (slides) this presentation describes how a document is laid out and painted to the display by the gecko engine. ...
Event Handlers - Archive of obsolete content
vent matches all of the criteria specified by the handler. the most basic handler specifies the event to listen for and an action to take when the handler fires. this action can be specified either using an action attribute or by specifying the script as a child of the handler element. if both are specified, the attribute wins. in both cases the javascript body is compiled just before execution; code that does not depend on the context of the event should be factored into normal javascript file. (note that there is a possibility that this may change in the future.) handlers are attached to the bound element, and they are registered by default for bubbling events. this means that <handler event="click" action="foo()"/> is analogous to onclick="foo()" defined on the bound element. the phas...
...ute. examples of common keys in the list are shift and control. for more details, see the xbl element reference for <handler>. in addition, mouse events can specify the button and the clickcount. this allows xbl authors to easily define handlers for right-click, or for left double-click, without having to write script on the same handler to differentiate those cases. key events support the charcode and keycode attributes. when set, the corresponding fields in the event object must match for the event to fire. [editor's note: should we have section on error-handling? probably.] ...
Windows stub installer - Archive of obsolete content
(if you need to rebuild stub installer, got to /mozilla/xpinstall/wizard/windows/setup and type "nmake /f makefile.win") go to mozilla/xpinstall/wizard/windows/builder on the shell prompt type "perl build.pl". now you will find an installer *and* the xpcom.xpi and other debug xpis delivered to mozilla/dist/win32_d.obj/install. run the stub installer setup.exe from the install directory. ...
...xpis delivered to mozilla/dist/win32_d.obj/install. run the stub installer setup.exe from the install directory. if you need to use vc++ to debug the installer: under project | settings | debug set "executable for debug session" to be the path to mozilla/dist/win32_d.obj/install/setup.exe set "working directory" to be the path to mozilla/dist/wind32_d.obj/install press f10 to step into the code how we get setup to debug the xpinstall engine from the windows stub installer? this section needs to be added how do i add an installer package to the windows installer? adding a package involves a few steps: add a section named for your <component> to the packages-win manifest that describes which files from dist belong to which module. for example, see the xpcom section that lists al...
dirCreate - Archive of obsolete content
description the input parameter is a filespecobject that you have already created with the install object's getfolder method. ...
...description the input parameter is a filespecobject that you have already created with the install object's getfolder method. ...
dirRemove - Archive of obsolete content
...
... ...
initInstall - Archive of obsolete content
nt when you add components with the addfile method. version an installversion object or a string representing the version of the package being installed. when version is a string it should be up to four integer values delimited by periods, such as "1.17.1999.1517". flags an optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. description the initinstall method initializes the installation of the specified software. you must call this method immediately after the constructor. it is an error to call any other install methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it finishes. if your script d...
... it is an error to call any other install methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it finishes. if your script does not call performinstall or cancelinstall, netscape 6 will not be able to clean up properly after your script finishes. example to start installation for the royal airways plug-in, you could use this code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ... err = getlasterror(); if (!err) performinstall(); else cancelinstall(err); ...
patch - Archive of obsolete content
representing the directory to the getfolder method. relativelocalpath a pathname relative to the localdirspec parameter that identifies the subcomponent that is to be patched. you must always use forward slashes (/) in this pathname, regardless of the convention of the underlying operating system. if this parameter is blank or null, xpisourcepath is used. returns an integer error code. for a list of possible values, see return codes. description the patch method to update an existing component by applying a set of differences between two known versions. the set of differences is in gdiff format and is created by the nsdiff utility. a patch can only be applied between two known versions. if the existing version of the file does not match the checksum stored in the gdiff fil...
.... if the existing version of the file does not match the checksum stored in the gdiff file, patch returns an error without applying the patch. after patch applies a patch, it compares a checksum.of the resulting file against a checksum stored in the gdiff file. if the checksums do not match, the original version of the file is preserved, the patched version of the file is discarded, and an error code is returned. any single installation process can apply multiple patches to the same file. if performinstall indicates that a reboot is necessary to complete the installation, patch may not work in subsequent xpinstall processes until the reboot is performed. ...
resetError - Archive of obsolete content
reseterror resets a saved error code to zero. method of install object syntax void reseterror (); parameters none. returns nothing. description the reseterror method resets any saved error code to zero. see getlasterror for additional information. ...
... reseterror resets a saved error code to zero. method of install object syntax void reseterror (); parameters none. returns nothing. description the reseterror method resets any saved error code to zero. see getlasterror for additional information. ...
Methods - Archive of obsolete content
ules it for later execution. gestalt retrieves information about the operating environment. (mac os only) getcomponentfolder returns an object representing the directory in which a component is installed. getfolder returns an object representing a directory, for use with the addfile method. getlasterror returns the most recent non-zero error code. getwinprofile constructs an object for working with a windows .ini file. getwinregistry constructs an object for working with the windows registry. initinstall initializes installation for the given software and version. loadresources returns an object whose properties are localized strings loaded from the specified property file. lo...
...ent add a comment line to the install log. patch applies a set of differences between two versions. performinstall finalizes the installation of the software. refreshplugins refreshes the list of plug-ins registered for the browser. registerchrome registers chrome with the chrome registry. reseterror resets a saved error code to zero. setpackagefolder sets the default package folder that is saved with the root node. ...
onbookmarkgroup - Archive of obsolete content
...
... ...
oncommand - Archive of obsolete content
« xul reference home oncommand type: script code this event handler is called when the command is activated. this occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. ...
... « xul reference home oncommand type: script code this event handler is called when the command is activated. this occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. ...
onpaneload - Archive of obsolete content
...
... ...
TOC - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › TOC
...
...ailable in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. ...
Extensions - Archive of obsolete content
ingle menu. this context menu has the id 'contentareacontextmenu'. in this example, a single item is added to the end of the firefox context menu. <popup id="contentareacontextmenu"> <menuitem id="thumbnail-show" label="view thumbnail" oncommand="thumbnails.view();"/> </popup> note that the popup element is used rather than the menupopup element as this is the element that firefox uses. the code above will append the new item at the end of the context menu. if you want to place the item at a specific location within the context menu rather than at the end, you can use either the insertbefore or insertafter attributes to insert it before or after another item specified by an id. for example, the following may be used to insert a command just after the 'select all' command: <popup id="con...
... an object which handles all of the functionality specific to the firefox context menu. specifically, this object is initialized with a set of properties that indiciate the type of object that was the target of the context menu. for instance, the 'onlink' property is set to true when a link was context-clicked. you may wish to use these properties instead of determining the type yourself, as the code already handles various special and complex cases that would take a lot of code to deal with manually. the following are the most common properties that you can check. an example follows. target the element that was context clicked. if the keyboard was used to open a context menu, this will be the focused element. ontextinput true if the target is a plain or password type...
OpenClose - Archive of obsolete content
rk. for instance, a menu's popup will open when the menu label is clicked, and a submenu will open when the mouse is hovered over the parent menu element. however, there may be situations when you wish to open a menu manually. the menu element has an open property which may be set to true to open the menu, or false to close the menu. a simple example: somemenu.open = true; this single line of code will open a menu referenced by the variable 'somemenu'. note that the open property applies to the menu or button, not to the menupopup. here is a complete example which uses a button to open a menu: <button label="open menu" oncommand="document.getelementbyid('editmenu').open = true;"/> <menu id="editmenu" label="edit"> <menupopup> <menuitem label="cut"/> <menuitem label="cop...
...do this. a menu in an unprivileged content window (such as a web page) can only open a popup while its window is focused, and it is in the currently active tab. that means that a document in a background tab cannot open a menu or popup. closing menus menus will close automatically once the user has made a selection from the menu. when an menu item is selected, it fires a command event so that code may be used to perform an action. the user may cancel selecting a command from a menu by pressing the escape key. this will close a single menu, but if this menu has a parent menu, the parent menu will remain open. a user may also cancel selecting from a menu by clicking outside the menu. in this case, not only will that menu close, but all parent menus will close as well. a menu may be closed b...
Panels - Archive of obsolete content
a panel to an non-button element, for instance to have a panel open when a label is clicked, use the popup attribute. the popup attribute should be set to the id of a panel within the same document. when the left mouse button is pressed on the element with the popup attribute, the corresponding panel will be displayed. for instance, to attach the popup defined above to a label, use the following code: <label value="search" popup="search-panel"/> the result is a search button which opens a panel for entering the search term. when using the popup attribute, the panel will appear with the top left corner at the mouse position. in this case, you may wish to have the popup appear below the label instead. the position attribute may be used to control the placement of the popup. here is a complet...
...olbarbutton label="search" type="panel"> <panel id="search-panel" position="after_start"> <textbox id="search"/> <button label="search" oncommand="dosearch();"/> </panel> </toolbarbutton> in this example, the dosearch() function is called when the "search" button is pressed. this function retrieves the popup and calls the hidepopup method. naturally, this function would also include code to start the search operation. preventing panels from automatically closing a panel will be closed when a user clicks outside of the panel or when the escape key is pressed. this is the normal way in which a user would cancel the operation. you may wish to also place a cancel or close button within the panel, especially if the panel is larger with a lot of controls within it. sometimes, howeve...
PopupEvents - Archive of obsolete content
ocument.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 instance, it is much better to rework the ui such that the code can handle no value being entered instead. otherwise, the user will be distracted with a popup that they cannot close. you also cannot cancel the hiding of a menupopup when a user has made a selection from a menu, as it is already too late to do so. in this situation the command event has already been sent to the selected menuitem and the operation already carried out. this is one special case in...
..., before the dialog can be opened. otherwise, the user would have a menu for a parent window that is no longer active. so instead, the popup is removed first. note that this means that the popuphiding event doesn't fire until after the modal dialog has been closed. there are situations when the popuphiding event will not fire when a menu is closed so you should make sure not to call any necessary code there. a better way is to just reinitialize the menu or popup in the popupshowing event. one such situation when the hiding events are not sent is when the menu is removed from the document. this is because there is no longer an element to send the events to. another situation is when the document is being unloaded. the popuphidden event the popuphidden event is fired after a popup has been close...
Sorting and filtering a custom tree view - Archive of obsolete content
this is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via javascript. this will not work for other types of trees, for example rdf-backed or ones created with dom methods. for the sake of simplicity, strings are not localized and the data loaded is hard coded. because of bug 340478, this code will only work from privileged script. sort.xul <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/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> ...
...nt.getelementbyid("tree"); loadtable(); } //this function is called every time the tree is sorted, filtered, or reloaded function loadtable() { //remember scroll position. this is useful if this is an editable table //to prevent the user from losing the row they edited var topvisiblerow = null; if (table) { topvisiblerow = gettopvisiblerow(); } if (data == null) { //put object loading code here. for our purposes, we'll hard code it. data = []; //the property names match the column ids in the xul. this way, we don't have to deal with //mapping between the two data.push({name: "leonardo", description: "leader", weapon: "dual katanas"}); data.push({name: "michaelangelo", description: "party dude", weapon: "nunchaku"}); data.push({name: "donatello", description: "does machi...
Additional Template Attributes - Archive of obsolete content
t. <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.xulp...
...instead. <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...
Static Content - Archive of obsolete content
ll be displayed just like it would be as if the template wasn't present. that is, before the template is examined, the menulist would have one item in it, with the label 'all'. the template generates two results as before, one for each country, and appends a menuitem for each one. one interesting thing about this example is that only one menupopup will be created, even though there are two in the code, one outside the template and another one inside the action body. this demonstrates how the template builder generates content, and the specifics of how this is done become important when dealing with recursive content and multiple rules. what's going on here is that the xul parser first creates the outer menulist element. the static content outside the template will also be created. the result w...
...ide the action body. this demonstrates how the template builder generates content, and the specifics of how this is done become important when dealing with recursive content and multiple rules. what's going on here is that the xul parser first creates the outer menulist element. the static content outside the template will also be created. the result will be a xul display that looks just like the code above, except that the template and its content is hidden. at this point, the menulist will have a menupopup as a child, and the menupopup will in turn have one menuitem child. next, the template is examined and two results are generated. remember that only the content at the uri attribute or below inside the action are copied for each result. when processing the action body, the builder looks at...
Template and Tree Listeners - Archive of obsolete content
!= -1) builder.root.view.selection.select(idx); } } }; tree.builder.addlistener(somelistener); this example is very simple and just saves and restores the selected index after a rebuild. since the content goes away during a rebuild, the selection is lost, so it is restored here during the didrebuild method. the firefox bookmarks window uses this technique. if you try an example using the code above, you will notice that the first tree will maintain the selection when the rebuild button is pressed, whereas in the second tree does not. this is because the listener is only attached to the first tree. the example above makes use of the getresourceatindex and getindexofresource methods. these two methods are available for tree builders and will convert between an index in the tree and the ...
...der) .addobserver(treebuilderobserver); the candropbeforeafter method returns false since we do not want to allow before and after drops. the candropon method returns true however. the candrop method is there for compatibility with older versions; this function checks the orientation and returns the opposite. this works as the 'on' value is 0 and the 'between' values are -1 and 1. obviously, this code is much simpler than what we would really want to use -- we should be checking what is being dragged to make sure that it is compatible with the tree. or, we might want to allow dropping on specific rows only; the drop methods are supplied with an index argument so we can check for this. « previousnext » ...
Things I've tried to do with XUL - Archive of obsolete content
bove. feel free to add your own xul experiences here. how do i use percentage-based height/width with xul? short answer: you can't easily, at least not yet. this means that creating any sort of visual display (not necessarily "ui"; my use case is for creating a calendar time display) that sizes sanely when the user resizes the window is unfortunately very difficult. (to add insult, xul layout code *explicitly* trims off '%' from width/height, thus treating it as pixels.) for reference, i'd like the following to give a vbox that resizes along with the window, with the green, red, and blue inside boxes always maintaining a 30%-20%-50% ratio to the height of the parent vbox. <vbox flex="1"> <box height="30%" flex="1" style="background: green;"/> <box height="20%" flex="1" style="background...
...the snippets assume that there's some enclosing structure that will provide the actual height. wrap the whole thing in a <vbox height="300"> or something. :) silver: if you set height="0" and include "overflow: hidden" on each box that is sharing the space, current gecko will quite happily split the space out according to flex, ignoring the contents of each box, as desired. from my reading of the code, just height="0" should work, but it doesn't seem to. this trick doesn't work in 1.4, but works in 1.7 and current versions. obtaining the rect of an element you can't obtain the actual visible rect of an element. html elements have the non-standard clientwidth/clientheight properties (see http://www.mozilla.org/docs/dom/domr...entheight.html); no equivalent exists for xul. enn: most people wo...
Adding Style Sheets - Archive of obsolete content
r class="titlespace"/> <hbox> <progressmeter id="progmeter" value="50%" style="display:none;"/> the new xml-stylesheet line is used to import the style sheet. it will contain the styles instead of having them directly in the xul file. you can include any number of style sheets in a similar way. here the style sheet is placed in the same directory as findfile.xul. some of the styles in the code above have been removed. one that wasn't was the display property on the progressmeter. this will be changed by a script so it was left in, as it doesn't really make sense to have the progress bar visible initially. you could still put this in a separate style sheet if you really wanted to. a class was added to the spacers so that they can be referred to. a style sheet also needs to be created.
...ecific filename was not indicated here. we have done a similar thing with the global style sheet file (chrome://global/skin). a style sheet may import styles from another stylesheet using the import directive. normally, you will only import one style sheet from each xul file. the global style sheet can be imported from within the style sheet associated with the xul file. this can be done with the code below, allowing you to remove the import from the xul file: style import from xul: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> style import from css: @import url(chrome://global/skin/); the second syntax is preferred because it reduces the number of dependencies within the xul file itself. remove the global style sheet import from findfile.xul and add the import to findf...
Broadcasters and Observers - Archive of obsolete content
eral elements to respond to events or changes of state easily. to do this, we can use broadcasters. command attribute forwarding we've already seen that elements such as buttons can be hooked up to commands. in addition, if you place the disabled attribute on the command element, any elements hooked up to it will also become disabled automatically. this is a useful way to simplify the amount of code you need to write. the technique also works for other attributes as well. for instance, if you place a label attribute on a command element, any buttons attached to the command will share the same label. example 1 : source view <command id="my_command" label="open"/> <button command="my_command"/> <checkbox label="open in a new window" command="my_command"/> in this example, the button does ...
...ed to the first button automatically. next, because the broadcast occured, the event handler onbroadcast is called. this results in an alert message appearing. note that the broadcast only occurs if the attributes on the broadcaster element are changed. changing the style of the buttons directly will not cause the broadcast to occur so the alert box will not appear. if you tried duplicating the code for the first button several times, you would end up with a series of alert boxes appearing, one for each button. this is because each button is an observer and will be notified when the style changes. next, we'll look at using the document object model with xul elements. « previousnext » ...
Creating a Window - Archive of obsolete content
ster/gatekeeper/there.is.only.xul"> <!-- other elements go here --> </window> this window will not do anything since it doesn't contain any ui elements. those will be added in the next section. in fact, there will not be shown any window at all. if you want to force the window to become visible you can add the width and height attribute to the window tag. here is a line by line breakdown of the code above: <?xml version="1.0"?> this line simply declares that this is an xml file. you would normally add this line as is at the top of each xul file. <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> this line is used to specify the style sheets to use for the file. this is the syntax that xml files use to import style sheets. in this case, we import the styles found in the g...
......
Introduction - Archive of obsolete content
in between the other two are applications which are created in the same way as an extension, but they act like a separate application in a separate window. this is used when you don't want to have the larger size of a complete xulrunner application, but don't mind requiring a mozilla browser to be installed to be able to run the application. remote xul application you could also just place xul code on a web server and open it in firefox, as you would any other web page, however this is discouraged and was disabled in firefox 8. it is still possible to enable this for selected sites to let legacy apps to continue working, but for new remote applications you should use html to create your user interface instead; most of the features you used to have to use xul for are available in html5. t...
...ced on them, so they may access local files and read and write preferences, for example. for extensions, the xul files and associated scripts and images used by an application would be packaged into a single file and downloaded and installed by the user. mozilla applications such as firefox provide an extension manager which allows packages to be installed without having to write a lot of complex code. what do i need to know to use this tutorial? you should have an understanding of html and at least a basic understanding of xml and css. here are some guidelines to keep in mind: xul elements and attributes should all be entered in lowercase as xml is case-sensitive (unlike html). attribute values in xul must be placed inside quotes, even if they are numbers. xul files are usually split i...
Modifying the Default Skin - Archive of obsolete content
des a skin by default, and you may download others. the xul for any skins is the same, however the style sheets and images used are different. for a simple personalized look to a firefox window, you can easily change the style sheets associated with it. larger changes can be done by creating an entirely new skin. firefox has a theme manager for changing the default skin. (although the underlying code for mozilla calls them skins and the user interface calls them themes, they're both referring to the same thing). a skin is described using css, allowing you to define the colors, borders and images used to draw elements. the file classic.jar contains the skin definitions. the global directory within this archive contains the main style definitions for how to display the various xul elements. by...
...hey are easy to remove. it also removes the reliance on specific image filenames. you can assign images to a button, checkbox and other elements by using the list-style-image property as in the following: checkbox { list-style-image: url("chrome://findfile/skin/images/check-off.jpg"); } checkbox[checked="true"] { list-style-image: url("chrome://findfile/skin/images/check-on.jpg"); } this code changes the image associated with a checkbox. the first style sets the image for a normal checkbox and the second style sets the image for a checked checkbox. the modifier 'checked=true' makes the style only apply to elements which have their checked attributes set to true. see also : creating a skin for firefox and css getting started in the next section, we will look at creating a new skin. ...
XPCOM Examples - Archive of obsolete content
s. try this example by opening a number of browser windows and you'll see that they are all listed on the menu. window mediator component this is fine for displaying a list of open windows, but we would like to enhance this so that clicking on the menu item will switch to that window. this is accomplished by using the window mediator component. it implements the interface nsiwindowdatasource. the code below shows how to get a component which implements it: var wmdata = components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"].getservice(); wmdata.queryinterface(components.interfaces.nsiwindowdatasource); this code retrieves a window mediator data source component. the component used here is the same one that handles the window-mediator rdf datasource. you can also get this comp...
...terface() it to an nsicookie before we can use it. in this case, we just use the instanceof operator to accomplish this. finally, an item is added to the menu for the cookie. the host, name and value properties of the cookie are used for this. menus have an appenditem() function which can be used to add an item to the menu, given a label and a value. see also more examples are available below. code snippets http://kb.mozillazine.org/category:xpcom_example_code next, we'll look at how to create trees. « previousnext » ...
Using Remote XUL - Archive of obsolete content
wever, so you should always specify a stylesheet. source | rendered step 6: behavior so far, so good. we have a menu bar with menus and buttons, and we can press the buttons, open the menus, and select their items. the interface is in place, but it doesn't do anything. we want it to load urls in the iframe when we press the buttons or select the menu items. for that we need to add javascript code. <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript"> function loadurl(event) { var contentframe = document.getelementbyid("contentframe"); var url = event.target.getattribute("value"); if (url) contentframe.setattribute...
...://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript"> function loadurl(event) { var contentframe = document.getelementbyid("contentframe"); var url = event.target.getattribute("value"); if (url) contentframe.setattribute("src", url); } </script> ... </window> the code to load the urls is simple. first we write an event handler function that receives an event, extracts a url from the value attribute of the element where the event occurred (a.k.a. the target element), and loads the url in the iframe. we add an id attribute to the iframe element so we can reference it from our function, and we add an oncommand event listener to the menubar element that calls the ...
XUL Changes for Firefox 1.5 - Archive of obsolete content
rence windows. these windows are special types of dialogs which support several panels, each of which may be contained in the same file or a separate file. a set of icons will appear across the top of the dialog allowing the user to switch panels. along with the new preference elements and some additional attributes for existing elements, they make it easy to set preferences without having to use code. for more information, see preferences system. bfcache mozilla now caches the page's dom, so that navigating back and forward does not reload the page, making navigation much more efficient. the pageshow and pagehide events are used when switching from a page in the cache, while the load and unload events are used only when the page is loaded or unloaded. for more information see using firefox...
... <menulist> items in a <menulist> support the description attribute to allow for extra descriptive text to appear beside an item's label. the menulist modification methods appenditem and insertitemat take an extra description argument when creating items this way. <listbox> the removeitemat method was sometime non zero-based due to a bug (bug 236068). this has been fixed in firefox 1.5 and all code depending on this non zero-based behaviour should be changed. <stringbundle> the <stringbundle> element has a strings property which may be used to retrieve an enumeration of all of the strings in the bundle. draggable tabs the tabbrowser now allows the user to rearrange tabs by dragging them. <tabbox> the <tabbox> element now supports a selectedindex attribute to specify the tab to be sele...
XUL Coding Style Guidelines - Archive of obsolete content
lines are recommended practices, the others are mandatory. xml, xul, html, and xhtml guidelines the following are considered good coding style for xml/xul documents. disobeying them might not cause any parsing error for now, however, it might cause future maintenance headache: convert html files to xul files. use the xml declaration. use namespace. case sensitivity. use chrome urls. javascript code shall be moved out of xul. dtd declaration. predefined entities. other guidelines mentioned in xhtml 1.1 recommendation. see details here. making xul localizable -- mandatory in the past, ui (display) related resource descriptions are stored in *.rc (for windows client) or *.ad (for unix client) so that they can be localized for a specific language or culture. in the new world, mozilla 5.0, thi...
...ersion="1.0" encoding='utf-8'?> <!-- do not localize this file: [reason...] it isn't part of the build; --> when translators see this line, they won't bother to look at the rest of the file. references xul is discussed in depth in xul language spec and xul window language. xul localizability issues xhtml 1.1 recommendation namespaces in xml extensible markup language (xml) 1.0 euro sign the unicode standard®, version 2.1 "xml applications" by frank boumphrey. published by wrox press inc. isbn 1-861001-52-5. author: tao cheng newsgroup discussion mailing list original document information author(s): tao cheng last updated date: december 10, 2004 copyright information: copyright (c) tao cheng ...
menulist - Archive of obsolete content
xamples | attributes | properties | methods | related ] an element that can be used for drop-down choice lists. the user may select one of the elements displayed in the menulist. the currently selected choice is displayed on the menulist element. to create the drop-down, put a menupopup inside the menulist containing the choices as menuitem elements. the command event may be used to execute code when the menulist selection changes. more information is available in the xul tutorial. attributes accesskey, crop, disableautoselect, disabled, editable, focused, image, label, oncommand, open, preference, readonly, sizetopopup, tabindex, value properties accessibletype, crop, description, disableautoselect, disabled, editable, editor, image, inputfield, itemcount, label, menuboxobject...
...ute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. oncommand type: script code this event handler is called when the command is activated. this occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. open type: boolean for the menu type buttons, the open attribute is set to true when the menu is open. the open attribute is not present if the menu is closed. preference type: id connects the element to a corresponding ...
menupopup - Archive of obsolete content
abel="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> <label value="right click for popup" context="clipmenu"/> attributes ignorekeys type: boolean if true, keyboard navigation between items in the popup is disabled. left type: integer overrides the horizontal position of the popup specified by the showpopup method. 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"/> <menuitem label="item 2"/> <menu id="submenu1" label="submenu 1"...
...-popup"> <menuitem label="submenu1 item 1"/> <menuitem label="submenu1 item 2"/> </menupopup> </menu> <menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a p...
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
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"/> <menuitem label="item 2"/> <menu id="submenu1" label="submenu 1"...
...-popup"> <menuitem label="submenu1 item 1"/> <menuitem label="submenu1 item 2"/> </menupopup> </menu> <menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a p...
preference - Archive of obsolete content
erence instead of enabling it. name type: string the name of the preference to change. for example, the browser's home page is set with the preference browser.startup.homepage. overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the window object event object exampl...
...ich the focus is moved when the user presses the "tab" key. elements with a higher tabindex are later in the tab sequence. type type: one of the values below the preference type which should be one of the following values. bool a boolean set to either true or false. usually a checkbox would be connected to these preferences. int an integer string a string unichar a unicode string wstring a localized string. in this situation the preference will save the path to a property file which contains the actual value of the preference. file a file. the file path will be stored in the preferences. properties defaultvalue (readonly) returns the default value of the preference. the type of the property depends on the value of the type property. if the pre...
toolbarbutton - Archive of obsolete content
p > menu { max-width: none; } dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the elements are placed left to right or top to bottom in the order they appear in the xul code. reverse for scales, the scale's values are ordered from right to left (for horizontal scales) or from bottom to top (for vertical scales). for other elements, they are placed right to left or bottom to top. this is reverse of the order in which they appear in the xul code. disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the ele...
...ute is empty or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. oncommand type: script code this event handler is called when the command is activated. this occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. open type: boolean for the menu type buttons, the open attribute is set to true when the menu is open. the open attribute is not present if the menu is closed. orient type: one of the values below used to specify whether...
tooltip - Archive of obsolete content
ttribute is copied to the menulist.value property upon user selection of the menuitem. noautohide type: boolean if this attribute is set to false or omitted, the tooltip will automatically disappear after a few seconds. if this attribute is set to true, this will not happen and the tooltip will only hide when the user moves the mouse to another element. 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"/> <menuitem label="item 2"/> <menu id="submenu1" label="submenu 1"...
...1-popup"> <menuitem label="submenu1 item 1"/> <menuitem label="submenu1 item 2"/> </menupopup> </menu> <menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a pop...
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
s results in a performance enhancement, but you will not be able to use the dom functions to retrieve the tree rows. hidecolumnpicker type: boolean when set to false, a drop-down will appear in the upper right corner of the tree, which the user may use to show and hide columns. when set to true, the column picker will be hidden. the default value is false. onselect type: script code this event is sent to a tree when a row is selected, or whenever the selection changes. the user can select multiple rows by holding down shift or control and clicking on a row. the onselect event will be sent for each item added to or removed from the selection. rows type: integer the number of rows to display in the element. if the element contains more than this num...
... xul for the tree: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="file://c:/main.css" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <row><button label="getrowvalues" oncommand="getrowcellvalues();"/></row> <tree flex="1" editable="true" id="mytree"> <treecols>...
wizard - Archive of obsolete content
es firstpage, lastpage, pagestep, title, windowtype properties canadvance, canrewind, currentpage, onfirstpage, onlastpage, pagecount, pageindex, pagestep, title, wizardpages methods advance, cancel, extra1, extra2, getbutton, getpagebyid, goto, rewind examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="thewizard" title="secret code wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkcode(){ document.getelementbyid('thewizard').canadvance = (document.getelementbyid('secretcode').value == "cabbage"); } </script> <wizardpage onpageshow="checkcode();"> <label value="enter the secret code:"/> <textbox id="secretcode" onkeyup="checkcode();"/> </wizardpa...
...moreover this hides separator between titlebar and window contents. this only affects mac os x. firstpage type: boolean true if the wizard is on the first page. ...
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
he application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application. on microsoft windows xp, all xul applications may wind up being grouped together in the taskbar. frequently asked questions why is installing xulrunner so painful? why isn't there a nice installer? because nobody has written that code yet! this is a developer preview release: additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner 1.8 for more informati...
...preview release: additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner 1.8 for more information. where is the source code? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel. ...
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
e application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application. on microsoft windows xp, all xul applications may wind up being grouped together in the taskbar. frequently asked questions why is installing xulrunner so painful? why isn't there a nice installer? because nobody has written that code yet! this is a developer preview release: additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner 1.8 for more informat...
...view release: additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner 1.8 for more information. where is the source code? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel. interwiki languag...
XULRunner 1.9.2 Release Notes - Archive of obsolete content
current version the current version of xulrunner 1.9.2 is 3.6.26, matching firefox 3.6.26 detailed release notes can be found here. ...
...on.xpi the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application. on microsoft windows xp, all xul applications may wind up being grouped together in the taskbar. frequently asked questions why is installing xulrunner so painful? why isn't there a nice installer? because nobody has written that code yet! additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner for more information. where is the source code? here. where is ...
XULRunner 1.9 Release Notes - Archive of obsolete content
xulrunner 1.9 is a stable release of the mozilla xulrunner application framework. it replaces version 1.8.0.4; all users should upgrade. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. xulrunner 1.9 is built from the same source code snapshot as firefox 3. current version the current version of xulrunner is 1.9.0.17, matching firefox 3.0.17 detailed release notes can be found here. system requirements before installing, make sure your computer meets the system requirements. the system requirements for xulrunner are the same as the system requirements for firefox. installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xu...
...the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application. on microsoft windows xp, all xul applications may wind up being grouped together in the taskbar. frequently asked questions why is installing xulrunner so painful? why isn't there a nice installer? because nobody has written that code yet! additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner for more information. where is the source code? here. wher...
XULRunner 2.0 Release Notes - Archive of obsolete content
current version the current version of xulrunner 2.0 is 2.0, matching firefox 4.0 detailed release notes can be found here. ...
...on.xpi the application will be installed to /usr/lib/vendor/applicationname known issues firewall software may identify all xul applications as the same application. on microsoft windows xp, all xul applications may wind up being grouped together in the taskbar. frequently asked questions why is installing xulrunner so painful? why isn't there a nice installer? because nobody has written that code yet! additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner for more information. where is the source code? here. where is ...
XULRunner FAQ - Archive of obsolete content
e name is a hangover from that that has now stuck. when will firefox be based on xulrunner? there is no intention to do this for official release versions of firefox. it is already possible to run firefox on xulrunner now though and certain linux distributions already do this. why is installing xulrunner so painful? why isn't there a nice installer? because nobody has written that code yet! this is a developer preview release: additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner 1.8 for more infor...
...w release: additional features for installing and deploying xulrunner and applications based on xulrunner will be available in future releases. i'm writing a xul application, how can i deploy that application to my users? right now mozilla recommends that xulrunner should be deployed privately with each application. see deploying xulrunner 1.8 for more information. where is the source code? here. i think i've found a bug, how do i report it? bugzilla.mozilla.org is used to track bugs in all mozilla products. please search to make sure that your bug has not already been reported. how can i help? if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel. ...
XULRunner Hall of Fame - Archive of obsolete content
ns a built in email marketing system that is tightly integrated with the associated web site. one example of this tight integration is that the form in a web site can collect payment and set up a login for a members only section. a newsletter can be sent to members who sign up on a regular bases. instantbird multi-protocol im client. build instructions komodo edit a multi-language code development tool. build instructions pencil the pencil project's unique mission is to build a free and opensource tool for making diagrams and gui prototyping that everyone can use. source qiqqa research manager, reference manager, and pdf manager. xulrunner is embedded to provide automatic search against journal archives, automatic acquisition of bibtex information, and automati...
...n a separate browser process. songbird songbird™ is a desktop web player, a digital jukebox and web browser mashup. build instructions spicebird a collaboration suite - e-mail, calendaring and instant messaging. latest release: june 2010 - build instructions utilities / prototypes ajax toolkit framework (atf) a part of the eclipse web tools platform (wtp) aliwal geocoder geocode addresses onto a map benjamin's xulrunner examples "mybrowser is a very simple example browser", xulmine. an updated version of "mybrowser" that works with firefox 25.0.1+ is available in matthew kastor's xulrunner examples at https://github.com/matthewkastor/xulrunner-examples/ exch a currency conversion tool using updated data from http://finance.yahoo.com/currency.
Make your xulrunner app match the system locale - Archive of obsolete content
this article is going to assume a lot of knowledge of xpcom and will be written for someone using python, but the ideas should be adaptable. also, this may not be the proper way to do this and it may not work for you in all cases. please update if there are more correct ways to do this. the first step is to get the code we're about to write to run before any of the locale specific resources are loaded. ...
...o, this may not be the proper way to do this and it may not work for you in all cases. please update if there are more correct ways to do this. the first step is to get the code we're about to write to run before any of the locale specific resources are loaded. democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component. the code described lives in the pybridge component's onstartup method which gets called automatically. the second step is to figure out the system locale. to be finished later. then set the locale preference. the following is python code to set this preference. from xpcom import components ps_cls = components.classes["@mozilla.org/preferences-service;1"] ps = ps_cls.getservice(components.interfaces.nsipr...
Windows and menus in XULRunner - Archive of obsolete content
ult icon (top left corner on windows). you’ll most likely want to specify your own icons. you can learn how to do it in the article window icons. menus and toolbars most desktop applications are complex enough to require some sort of menu and/or toolbar to structure the application’s available commands. xul provides elements to support both menus and toolbars. ...
...mand id="cmd_open" label="&file.open;" oncommand="dofileopen();"/> <command id="cmd_save" label="&file.save;" oncommand="dofilesave();"/> </commandset> ... <menuitem command="cmd_open"/> <menuitem command="cmd_save"/> ... <toolbarbutton id="open" command="cmd_open"/> <toolbarbutton id="save" command="cmd_save"/> ... we can add images to the toolbar buttons through the css file. we could hard-code the images in the xul file itself, but css is a better practice. here’s the css file: /* global skin --------------------------------------------------- */ @import url(chrome://global/skin/); /* toolbar ------------------------------------------------------- */ #open { list-style-image: url(chrome://basicapp/skin/open.png); -moz-box-orient: vertical; } #save { list-style-image: url(chr...
XUL Explorer - Archive of obsolete content
the xul can be loaded from and saved to files. a xul validator and the error console are both available to help debug problems. the help menu provides access to xul information on mdc. there is even simple “keyword” help lookup for xul elements. ...
...rojects - xul files, js xpcom, and xulrunner applications for more detailed information, see the xul_explorer:planning#feature_planning_for_xul_explorer. ...
calICalendarViewController - Archive of obsolete content
vides a way for a calicalendarview to create, modify, and delete items. implementing a calicalendarviewcontroller allows for these actions to be performed in a manner consistent with the rest of the application in which the calicalendarview is included. calendar/base/public/calicalendarviewcontroller.idlscriptable please add a summary to this article. ...
...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. ...
calIFileType - Archive of obsolete content
summary the califiletype interface provides information about a specific file type. califiletype is used in caliimporter and caliexporter to determine which file types are supported for import/export. status: unfrozen. defined in calendar/base/public/caliimportexport.idl interface code [scriptable, uuid(efef8333-e995-4f45-bdf7-bfcabbd9793e)] interface califiletype : nsisupports { readonly attribute astring defaultextension; readonly attribute astring extensionfilter; readonly attribute astring description; }; attributes defaultextension the default extension that should be associated with files of this type. extensionfilter the extension filter to use in the filepicker's filter list. separate multiple extensions with semicolon and space. description the description to show to th...
... ...
2006-11-17 - Archive of obsolete content
how to fiter out mail for a particular recepient? this user want to add a filter to his tb, so that it could color the mail that is for a particular recepient, however, the regular expression that he uses doesn't work and want suggestion from others. a few suggestion is posted. what file format is tb's address book using? tb's address book uses mork (file format). there are also some perl code provided in this link. how to get review for work-in-progress patch? answer: cc whoever you need review from, but don't post a formal review. steps for posting a formal review is provided also. how to access xyz.properties items more detail and code examples are provided in the posting. how to create top-level folders in inbox with an imap account on courier server. solution is provided ...
... posting. how to create top-level folders in inbox with an imap account on courier server. solution is provided by jay lee should there be an additional options for account configuration that just delete the messages from the server whenever they are deleted in tb? some discussion is posted. however, david bienvenu stated that the options already exist in tb 2.0, just that it is a hidden. code review requested for smtp swticher no comment is made. meetings calendar project weekly status meeting - 2006/11/15 17:00 utc (meeting notes) calendar project weekly qa chat - 2006/11/02 16:30 utc (meeting notes) ...
2006-11-03 - Archive of obsolete content
11 2006. when he builds using the disable.crypto option he encounters the following problem: no rule to make target `../../dist/lib/components/libpipboot.a', needed by `minimo'. he has also created a bug entry on bugzilla with the bug id of opened bug #344854. problem compiling with vs 2003 .net phil is trying to compile firefox for the first time and is getting an error wh...
...les mozilla across different platforms when pkg_config is used. on november 1st peter weilbacher responded gery's question. he told gery to create a bug for this problem in bugzilla. on november 2nd gery replied with the bug number 358706. problems building browser's trunk on windows using vs 2005 originally posted on october 29th: ricardo sixel is trying to retrieve the trunk source code using the browser check out option. however it fails on him. he has created the following bug entry https://bugzilla.mozilla.org/show_bug.cgi?id=331404. announcements a change in tp2's numbers on october 31st adam guthrie announced that: rob helmer will be adding his patch to fix tp2's reporting of average pre-load times. more tbox changes on the way, most hitting on friday on october ...
2006-11-24 - Archive of obsolete content
g with the source tarball for xulrunner 1.8.4,running "make -f client.mk distclean" followed by "make -f client.mk build_all". joe is asking for help on a possible solution to fix his problem. building xpcom components with msvs 2005 november 21st: buffaloaf is having trouble getting a personal xpcom component to work under xulrunner when compiled with msvs 2005. ...
...e solution to fix his problem. building xpcom components with msvs 2005 november 21st: buffaloaf is having trouble getting a personal xpcom component to work under xulrunner when compiled with msvs 2005. luke is migrating all of his code to compile with vc8 and is having some problems. he is receiving the following error: error: uncaught exception: [exception... "component returned failure code: 0x80570016 (ns_error_xpc_gs_returned_failure) [nsijscid.getservice]" nsresult: "0x80570016 (ns_error_xpc_gs_returned_failure)" location: "js frame :: chrome://modzilla/content/js/pkg_zillacom.js :: <top_level> :: line 1202" data: no] he is running xulrunner v1.8.0.4. luke wants to know if compiling xulrunner with a static crt is better or worse than compiling with the mscvr80.dll dependenc...
2006-09-22 - Archive of obsolete content
authors dean woodside sherman fernandes ...
... authors dean woodside sherman fernandes ...
2006-10-13 - Archive of obsolete content
10; the target release date for rc3 is october 17 new tinderbox and bonsai servers the build team would like help testing out the new tinderbox and bonsai servers. ...
...10; the target release date for rc3 is october 17 new tinderbox and bonsai servers the build team would like help testing out the new tinderbox and bonsai servers. ...
2006-11-17 - Archive of obsolete content
meetings no meetings this week ...
... meetings no meetings this week ...
2006-11-24 - Archive of obsolete content
discussions java versus tamarin discussion about possibility of implementing java technology in mozilla products. a user writes that the licensing incompatibilities between gpl and mpl would prevent java code to be added in mozilla. the license would need to be compatible with all three mpl/gpl/lgpl (used by tamarin) to be considered for mozilla. ...
...ersus tamarin discussion about possibility of implementing java technology in mozilla products. a user writes that the licensing incompatibilities between gpl and mpl would prevent java code to be added in mozilla. the license would need to be compatible with all three mpl/gpl/lgpl (used by tamarin) to be considered for mozilla. ...
NPN_GetValue - Archive of obsolete content
the value parameter should point to a npbool, which will be set appropriately if the function returns nperr_no_error. npnvprivatemodebool: indicates whether or not the browser is currently in private browsing mode. the value parameter should point to an npbool, which will be set appropriately if the function returns nperr_no_error. npnvdocumentorigin: the value for this variable is the unicode serialization of the origin converted to nfkc-encoded (normalized) utf-8. memory for this string must be freed by the plugin via npn_memfree(). for more information, see the document origin specification. npnvplugindrawingmodel: (mac only) npnvsupportsquickdrawbool : (mac only) npnvsupportscoregraphicsbool : (mac only) value function returns the name of the plug-in in th...
...ol : (mac only) value function returns the name of the plug-in in the value parameter. gecko 1.9.2 note starting with gecko 1.9.2 (firefox 3.6), the variables npnvservicemanager, npnvdomelement, and npnvdomwindow are no longer supported. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_getvalue returns the browser information set with npn_setvalue. the queried information is returned in the value parameter. unix the platform-specific values for this parameter are npnvxdisplay (the current display), npnvxtappcontext (the browser's xtappcontext), and npnvnetscapewindow (the browser toplevel window in which the plugin is disp...
NPN_RequestRead - Archive of obsolete content
npbyterange* rangelist); parameters the function has the following parameters: stream stream of type np_seek from which to read bytes. rangelist range of bytes in the form of a linked list of npbyterange objects, each of which specifies a request for a range of bytes. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description for a seekable stream, the browser sends data only in response to requests by the plug-in. the plug-in calls npn_requestread() to request data from a seekable stream. the plug-in can use this function to make one or more requests for ranges of bytes. these requests result in subsequent calls to npp_writeready() and npp_write(). for multiple requ...
...rently seekable; npn_requestread() automatically changes the mode to np_seek. if the stream is not inherently seekable, the stream must have been put in np_seek mode initially (since the browser must cache all the stream data on disk in order to access it randomly). if npn_requestread() is called on a stream that is not inherently seekable and not initially in mode np_seek, it returns the error code nperr_stream_not_seekable. typically, the only streams that are inherently seekable are those from in-memory or on-disk data, or from http servers that support byte-range requests. see also npp_newstream() npp_writeready() npp_write() npstream ...
NPN_SetValue - Archive of obsolete content
nppvpluginkeeplibraryinmemory: tells browser that the plugin dll should live longer than usual nppvpluginneedsxembed nppvpluginscriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set. returns if successful, the function should return nperr_no_error. if unsuccessful, the function should return the most relevant npapi error code. for possible values, see error codes. description a good place to set plugin operation mode such as windowless mode is npp_new, so the browser knows right away what mode the plugin is designed to operate in. nppvpluginwindowbool (windows and unix) specifies that the plugin operates in windowed mode. the alternative is windowless where no window messages are sent to the plugin as there is no ...
...shutdown. the plugin calls npn_setvalue any time with nppvpluginkeeplibraryinmemory as variable parameter and value set to true. by default, the dll will be unloaded from memory preceded by an np_shutdown call. remarks all four variable values are boolean. although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boolean. the browser code reads this parameter as follows (nppvpluginwindowbool as an example): nperror np_export _setvalue(npp npp, nppvariable variable, void *value) { ... bool bwindowless = (value == null); ... } so the proper way to call this function from a plug-in would be: bool bwindowed = false; npn_setvalue(npp, nppvpluginwindowbool, ( void *)bwindowed); see also npp_new, npn_getvalue, npp_setval...
NPN_Version - Archive of obsolete content
obtain version information, both of the plug-in api and of the browser itself. syntax #include <npapi.h> void npn_version(int* plugin_major, int* plugin_minor, int* netscape_major, int* netscape_minor); parameters the function has the following parameters: plugin_major pointer to a plug-in's major version number; changes with major code release number. plugin_minor pointer to a plug-in's minor version number; changes with point release number. netscape_major pointer to the browser's major version; changes with major code release number. netscape_minor pointer to the browser's version; changes with point release number. description the values of the major and minor version numbers of the plug-in api...
...f the feature it represents exists in this version. for example, the plug-in could inquire on the constant npvers_has_windowless to see if it is running in a browser that supports windowless functionality. for more information and an example, see finding out if a feature exists. for a listing of version constants defined in the plug-in api, see version feature constants. note: platform-specific code in the plug-in api files npwin.cpp, npmac.cpp, or npunix.c checks version numbers automatically. a plug-in whose major version is less than the major version of the browser is not loaded. see also npn_useragent() np_initialize() ...
NPP_SetValue - Archive of obsolete content
description none see also npp_new, npp_getvalue, npn_setvalue, npn_getvalue ...
...alue); parameters the function has the following parameters: instance pointer to plugin instance on which to set the variable. variable the variable being set. value value for the variable being set. returns if successful, the function should return nperr_no_error. if unsuccessful, the function should return the most relevant npapi error code. for possible values, see error codes. description none see also npp_new, npp_getvalue, npn_setvalue, npn_getvalue ...
NPP_URLNotify - Archive of obsolete content
#include <npapi.h> void npp_urlnotify(npp instance, const char* url, npreason reason, void* notifydata); parameters the function has the following parameters: instance pointer to the current plug-in instance. url url of the npn_geturlnotify() or npn_posturlnotify() request that has completed. reason reason code for completion of request. values: npres_done (most common): completed normally. npres_user_break: user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. npres_network_err: stream failed due to problems with network, disk i/o, lack of memory, or other problems. notifydat...
...sk i/o, lack of memory, or other problems. notifydata plug-in-private value for associating a previous npn_geturlnotify() or npn_posturlnotify() request with a subsequent npp_urlnotify() call. description the browser calls npp_urlnotify() after the completion of a npn_geturlnotify() or npn_posturlnotify() request to inform the plug-in that the request was completed and supply a reason code for the completion. the most common reason code is npres_done, indicating simply that the request completed normally. other possible reason codes are npres_user_break, indicating that the request was halted due to a user action (for example, clicking the stop button), and npres_network_err, indicating that the request could not be completed, perhaps because the url could not be found. the param...
Samples and Test Cases - Archive of obsolete content
there is a guide to compiling the npruntime sample in visual studio. in addition to those samples, there are 2 more plugins in the tree that might be helpful. ...
... there is a guide to compiling the npruntime sample in visual studio. in addition to those samples, there are 2 more plugins in the tree that might be helpful. ...
Writing a plugin for Mac OS X - Archive of obsolete content
this article is adapted from josh aas's blog post writing an npapi plugin for mac os x. before you go on reading this article, you may wish to grab the sample code located here, as it will be referenced during this tutorial. the sample is posted under a bsd-style license that means you can use it for anything, even if you don't plan to release your source code. getting started if you check out the mozilla source code in mac os x, you can simply open basicplugin.xcodeproj in xcode, click build, and you're done. xcode will create a "build" directory next to the project file, and if you built it in release mode, that folder in turn contains a "release" directory with the plugin inside it. to install the plugin, just copy it into one of these two locations: /library/internet plugi...
...ugins working. some symbols must be visible as standard c symbols so the browser can find them, which means they need to be prefixed by an underscore, and must not have the c++ obfuscation that is generated by the c++ compiler. the three symbols that must always be visible are: np_initialize() np_getentrypoints() np_shutdown() the sample plugin is written entirely in c, using a standard xcode build configuration, so by default all of its symbols are c-style and visible. if you want to implement your plugin in c++ or objective-c++, you need to tell the compiler to export them in c format by using extern "c" in the header, like this: #pragma gcc visibility push(default) extern "c" { nperror np_initialize(npnetscapefuncs *browserfuncs); nperror np_getentrypoints(nppluginfuncs *plu...
Plugins - Archive of obsolete content
plugins are written using npapi, the cross-browser api for plugins. the main source of documentation for npapi is the gecko plugin api reference. to make your plugin scriptable from web pages, use npruntime. plugins can be written completely from scratch using c apis (usually in c or c++) or they may be built on a plugin framework such as firebreath, juce, or qtbrowserplugin. there are also some code generation tools that may be helpful. more information about these tools can be found on the external resources page. plugins are different from extensions, which modify or enhance the functionality of the browser itself. plugins are also different from search plugins, which plug additional search engines in the search bar. gecko plugin api reference (npapi) this reference describes the a...
...ads plugins into a separate process. firefox 3.6.4 introduced out-of-process plugins which execute in a separate process so that a crashing plugin does not crash the browser. logging and debugging for multi-process plugins how to create a plugin log to aid in debugging problems with multi-process plugins. writing a plugin for mac os x learn how to write a plugin for mac os x; a template xcode project is provided. monitoring plugins use an observer service notification to monitor the amount of time spent executing calls in plugins. this can be useful when trying to determine if a plug-in is consuming too many resources. scripting plugins: macromedia flash this article explains how javascript can be used to access methods from within the flash plugin, as well as how a feature ...
Building a Theme - Archive of obsolete content
rmat (note that it should not be your email). make it unique. you could also use a guid. note: this parameter must be in the format of an email address, although it does not have to be a valid email address. (example.example.example) 4 - the type of the add-on. '4' declares that it is installing a theme. if you were to install an extension it would be 2 (see install manifests#type for other type codes). {ec8030f7-c20a-464f-9b0e-13a3a9e97384} - firefox's application id. 29.0 - the exact version number of the earliest version of firefox you're saying this extension will work with. never use a * in a minversion, it almost certainly will not do what you expect it to. 39.* - the maximum version of firefox you're saying this extension will work with. set this to be no newer than the newest curre...
... (or in jar packages). create a chrome manifest the chrome manifest is the file that maps these chrome uris to your theme's files. for more information on chrome manifests and the properties they support, see the chrome manifest reference. open the file called chrome.manifest that you created alongside the chrome directory at the root of your extension's source folder hierarchy. add in this code: skin browser sample chrome/browser/ skin communicator sample chrome/communicator/ skin global sample chrome/global/ skin mozapps sample chrome/mozapps/ don't forget the trailing slash, "/"! without it, the package won't be registered. the third column needs to match your theme's internalname value from the install manifest above. this maps skin...
Using the W3C DOM - Archive of obsolete content
re not part of the w3c document object model (dom) standards and may cause javascript errors in standards-compliant browsers. the w3c document object model provides interfaces dom elements to scriptable objects. w3c dom standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use. using w3c standards means that code will run in compliant browsers with minimal need for cross-browser support, whereas code based on proprietary standards requires much more effort to be compatible with multiple user agents. unsupported dom-related properties the following ie proprietary document object properties are not supported in the w3c document object model: document.layers[] id_attribute_value document.all document...
...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 brows...
Browser Feature Detection - Archive of obsolete content
k true false true speakheader true false false speaknumeral true false false speakpunctuation true false false speechrate true false true stress true false false tablelayout true true true textshadow true false true top true true true unicodebidi true true true visibility true true true voicefamily true false true volume true false true widows true false true zindex true true true test code // document properties that are used to determine // support levels var _features = { 'domcore1': [ {name: 'doctype', 'supported': false},...
...name: 'speak', 'supported': false}, {name: 'speakheader', 'supported': false}, {name: 'speaknumeral', 'supported': false}, {name: 'speakpunctuation', 'supported': false}, {name: 'speechrate', 'supported': false}, {name: 'stress', 'supported': false}, {name: 'tablelayout', 'supported': false}, {name: 'textshadow', 'supported': false}, {name: 'top', 'supported': false}, {name: 'unicodebidi', 'supported': false}, {name: 'visibility', 'supported': false}, {name: 'voicefamily', 'supported': false}, {name: 'volume', 'supported': false}, {name: 'widows', 'supported': false}, {name: 'zindex', 'supported': false} ] }; function supports(object, featureset) { var i; var features = _features[featureset]; var level = 0; if (!features) return level; for (i = 0; i < ...
-moz-os-version - Archive of obsolete content
syntax values windows-win7 the user is on the windows 7 operating system. ...
... syntax values windows-win7 the user is on the windows 7 operating system. ...
Processing XML with E4X - Archive of obsolete content
warning: e4x is obselete. it's been disabled by default for chrome in firefox 17, and completely removed in firefox 21. use domparser/domserializer or a non-native jxon algorithm instead. first introduced in javascript 1.6, e4x introduces a native xml object to the javascript language, and adds syntax for embedding literal xml documents in javascript code. a full definition of e4x can be found in the ecma-357 specification. this chapter provides a practical overview of the language; it is not a complete reference. compatibility issues prior to widespread browser support for the <script> element, it was common for javascript embedded in a page to be surrounded by html comment tags to prevent <script> unaware browsers from displaying javascript code to the user. this practice i...
...for backwards compatibility, e4x defaults to ignoring comments and cdata sections. ...
ActiveXObject - Archive of obsolete content
tivex objects may present security issues. to use the activexobject, you may need to adjust security settings in internet explorer for the relevant security zone. ...
...f an automation object that you can use in your code, you may need to use a com object browser, such as the ole/com object viewer, if no reference documentation is available for the automation object. to create an automation object, assign the new activexobject to an object variable: var excelapp = new activexobject("excel.application"); var excelsheet = new activexobject("excel.sheet"); this code starts the application creating the object (in this case, a microsoft excel worksheet). once an object is created, you refer to it in code using the object variable you defined. in the following example, you access properties and methods of the new object using the object variable excelsheet and other excel objects, including the application object and the activesheet.cells collection. // make e...
VBArray.lbound - Archive of obsolete content
r than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error. parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. example the following example consists of three parts. ...
...od generates a "subscript out of range" error. parameters safearray a vbarray object. dimension optional optional. the dimension of the vbarray for which the lower bound index is wanted. if omitted, lbound behaves as if a 1 was passed. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the lower bound of each dimension. since the safe array is created in vbscript rather than visual basic, the lower bound will always be zero. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscr...
New in JavaScript 1.2 - Archive of obsolete content
tor 4.0. --> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x). arrays can now be created using literal notation (inspired by list literal syntax from python 1.x). ...
...jects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x). arrays can now be created using literal notation (inspired by list literal syntax from python 1.x). ...
New in JavaScript 1.3 - Archive of obsolete content
the following is a changelog for javascript from netscape navigator 4.0 to 4.5. the old netscape documentation can be found on archive.org. netscape navigator 4.5 was released on october 19, 1998. the most significant change in javascript 1.3 was compliance with ecma-262 and unicode by removing inconsistencies between javascript 1.2 and the new ecma standard (which was published in june 1997). additional features of version 1.2, at the time not specified by ecma-262 were kept in the javascript language (see below for a list of differences). javascript versions netscape communicator and navigator 4.06 and 4.5 executes javascript language versions up to 1.3. note that communicator and navigator 4.0-4.05 and earlier ignored scripts with the language attribute set to "javascript1.3" and higher...
... changed functionality in javascript 1.3 changes to date to conform with ecma-262 new constructor date(year, month, day, [,hours [, minutes [, seconds [, milliseconds ]]]]) additional method parameters: setmonth(month[, date]) sethours(hours[, min[, sec[, ms]]]) setminutes(min[, sec[, ms]]) setseconds(sec[, ms]) ...
New in JavaScript 1.7 - Archive of obsolete content
ascript 1.7. this version was included in firefox 2 (october 2006). javascript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment. using javascript 1.7 in order to use some of the new features of javascript 1.7, you need to specify that you wish to use javascript 1.7. ...
...the features that do not introduce new keywords (destructuring assignment and array comprehensions) can be used without specifying the javascript version. new features in javascript 1.7 the following features added with javascript 1.7 were not part of an ecma-262 standard at the time. ...
New in JavaScript 1.8 - Archive of obsolete content
the following is a changelog for javascript 1.8. this version was included in firefox 3 and is part of gecko 1.9. see bug 380236 for a tracking development bug for javascript 1.8. using javascript 1.8 in order to use some of the new features of javascript 1.8 in html, use: <script type="application/javascript;version=1.8"> ... your code ... </script> another way (not recommended) to do this is to use the deprecated <script> language attribute and define it as "javascript1.8". when using the javascript shell, javascript xpcom components, or xul <script> elements, the latest js version (js1.8 in mozilla 1.9) is used automatically (bug 381031, bug 385159). the features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 or higher because existing...
...o use the deprecated <script> language attribute and define it as "javascript1.8". when using the javascript shell, javascript xpcom components, or xul <script> elements, the latest js version (js1.8 in mozilla 1.9) is used automatically (bug 381031, bug 385159). the features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 or higher because existing code might use those keywords as variable or function names. the features that do not introduce new keywords (such as generator expressions) can be used without specifying the javascript version. new features in javascript 1.8 expression closures. generator expressions. allowing you to simply create generators (which were introduced in javascript 1.7). typically you would have to create a custom ...
JSException - Archive of obsolete content
constructor summary the netscape.javascript.jsexception class has the following constructors: jsexception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.jsexception class has the following methods: getwrappedexception instance method getwrappedexception. getwrappedexceptiontype ...
...sage. declaration 1. public jsexception() 2. public jsexception(string s) 3. public jsexception(string s, string filename, int lineno, string source, int tokenindex) arguments s the detail message. filename the url of the file where the error occurred, if possible. lineno the line number of the file, if possible. source the string containing the javascript code being evaluated. tokenindex the index into the source string where the error occurred. getwrappedexception instance method getwrappedexception. declaration public object getwrappedexception() description getwrappedexception() returns an object that represents the value that the javascript actually threw. javascript can throw any type of value. use getwrappedexception() to determine ...
JSObject - Archive of obsolete content
sobject; when a jsobject is sent from java to javascript, the runtime engine unwraps it to its original javascript object type. the jsobject class provides a way to invoke javascript methods and examine javascript properties. any javascript data brought into java is converted to java data types. when the jsobject is passed back to javascript, the object is unwrapped and can be used by javascript code. see the core javascript 1.5 guide for more information about data type conversions. method summary the netscape.javascript.jsobject class has the following methods: call calls a javascript method. equals determines if two jsobject objects refer to the same instance. (what's the problem with == ?) eval evaluates a javascript expression. getmember retrieves the value of a ...
...arlier versions, you can use either the equals method of java.lang.object or the == operator to evaluate two jsobject objects. in more recent versions, the same jsobject can appear as different java objects. you can use the equals method to determine whether two jsobjects refer to the same instance. eval method. evaluates a javascript expression. the expression is a string of javascript source code which will be evaluated in the context given by "this". declaration public object eval(string s) getmember method. retrieves the value of a property of a javascript object. equivalent to "this.name" in javascript. declaration public object getmember(string name) getslot method. retrieves the value of an array element of a javascript object. equivalent to "this[index]" in javascript. de...
LiveConnect - Archive of obsolete content
rence the java classes used for liveconnect, along with their constructors and methods. java in firefox extensions community view mozilla.dev.tech.java forums... mailing list newsgroup rss feed related topics javascript, plugins older notes (please update or remove as needed.) while the bloated liveconnect code in the mozilla source was removed in version 1.9.2 of the platform (see bug 442399), its former api has been restored (see also the specification and this thread) (building on npapi?), and as of java 6 update 12, extensions as well as applets can make use of this restored api. the reimplementation also restores the ability to use try-catch exceptions within javascript, and is free of the increasi...
...ct use by applets is enabled via the use of the "mayscript" attribute in applet tags on an html page, following which the applet may refer to classes in the netscape.javascript package to access javascript objects, and scripts may directly call applet methods (using the syntax document.applets.name.methodname()). standard java objects are also available for creation and manipulation by javascript code (e.g. by writing code like "new java.lang.string('javascript string')" for classes in the java.* package hierarchy, or using a new "packages" object for classes outside this hierarchy). old liveconnect documents, broken links: java method overloading and liveconnect 3 the technique that liveconnect uses to invoke overloaded java methods from javascript. liveconnect exceptions how do jav...
XForms Custom Controls - Archive of obsolete content
xformswidget-output binding. if you would like to do this kind of heroic work then please contact the mozilla xforms developers before you start. hopefully we can help you avoid a lot of frustration and despair :). overview the mozilla xforms controls are largely implemented using xbl and the bindings are applied to the individual xforms control tags via css. so you can always refer to our source code to get some great examples of how xforms controls can be written. this will also allow you to be up to date with our current approaches (often the result of hard-learned lessons) and that will hopefully help you to more easily write your own controls. to get started, you really only need to know the language where you'd like to use xforms (like xhtml or xul), some xbl and javascript, and the xpco...
.... nsixformsuiwidget every custom control should implement the nsixformsuiwidget interface. this interface is used by the xforms engine to interact with the underlying control. for example, when the control needs to be updated according to the rules of xforms, the refresh method will be called by the processor. below is the structure of the interface. as always, please refer directly to the source code to be sure that you are using the latest, up-to-date version: extensions/xforms/nsixformsuiwidget.idl. interface nsixformsuiwidget : nsidomelement { /** * is called when control should be updated to reflect the value of the bound node. */ void refresh(); /** * is called when focus is advanced to the xforms element. */ boolean focus(); /** * is called when control should...
Implementation Status - Archive of obsolete content
d 11.8.1 name unsupported 11.8.2 value unsupported 11.9 submission options supported 11.9.1 the get submission method supported 11.9.2 the post, multipart-post, form-data-post, and urlencoded-post submission methods supported 11.9.3 the put submission method supported 11.9.4 the delete submission method unsupported 11.9.5 serialization as application/xml supported 11.9.6 serialization as multipart/related ...
...xforms and styling section title status notes bugs g.1 pseudo-class...
Archive of obsolete content
ted below is archived, obsolete material about open web topics. beginner tutorials this page includes archived beginners tutorials, from various places around mdn. case sensitivity in class and id names creating a dynamic status bar extension concepts covered in the previous sample won't be reiterated here; instead, refer to the downloadable sample code or to the previous sample for further details. creating a status bar extension many of the concepts introduced here apply to any xul-based application; however, to keep from getting completely overwhelmed, we're going to focus specifically on firefox. css3 css3 is the latest evolution of the cascading style sheets language and aims at extending css2.1. it...
...erequisites sunbird theme tutorial this tutorial is a step-by-step guide to making a theme for sunbird 0.3a1 and later versions. it is designed for beginners. it does not cover advanced topics. table reflow internals key: tamarin tracing build documentation the following instructions are for obtaining and building the tamarin tracing source code. for instructions on tamarin central, please see the basics of web services summary: a current hot topic on the web right now are web services. this short guide will allow you to learn more about web services. themes archived theme documentation. updating an extension to support multiple mozilla applications this article shows how to take ...
2D collision detection - Game development
green means collision, blue means no collision.</p> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.5.4/crafty-min.js"></script> crafty.init(200, 200); var dim1 = {x: 5, y: 5, w: 50, h: 50} var dim2 = {x: 20, y: 10, w: 60, h: 40} var rect1 = crafty.e("2d, canvas, color").attr(dim1).color("red...
...else { // no collision this.color("blue"); } }); note: another example without canvas or external libraries. circle collision another simple shape for collision detection is between two circles. this algorithm works by taking the centre points of the two circles and ensuring the distance between the centre points are less than the two radii added together. playable code <div id="cr-stage"></div> <p>move the circle with arrow keys. green means collision, blue means no collision.</p> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crafty/0.5.4/crafty-min.js"></script> #cr-stage { position: static !important; height: 200px !important; } crafty.init(200, 200); var dim1 = {x: 5, y: 5} var dim2 = {x: 20, y: 20} crafty.c("circl...
3D collision detection - Game development
an easy optimization to avoid it consists of comparing the squared distance with the squared radius, so the optimized equation would instead involve distancesqr < sphere.radius * sphere.radius. sphere vs. sphere the sphere vs sphere test is similar to the point vs sphere test. what we need to test here is that the distance betw...
...m based on bounding volumes as well. the way a physics engine works is by creating a physical body, usually attached to a visual representation of it. this body has properties such as velocity, position, rotation, torque, etc., and also a physical shape. this shape is the one that is considered in the collision detection calculations. we have prepared a live collision detection demo (with source code) that you can take a look at to see such techniques in action — this uses the open-source 3d physics engine cannon.js. ...
Building up a basic demo with PlayCanvas - Game development
re examples. engine vs editor the engine itself can be used as a standard library by including its javascript file directly in your html, so you can start coding right away; in addition the playcanvas toolset comes with an online editor that you can use to drag and drop components onto the scene — a great way to create games and other apps requiring scenes if you're more of a designer than a coder. those approaches are different but work equally well regarding achieving end goals. playcanvas engine built for modern browsers, playcanvas is a fully-featured 3d game engine with resource loading, an entity and component system, advanced graphics manipulation, collision and physics engine (built with ammo.js), audio, and facilities to handle control inputs from various devices (including gam...
...ndle control inputs from various devices (including gamepads). that's quite an impressive list of features — let's see some in action, check out the building up a basic demo with playcanvas engine for details. playcanvas editor instead of coding everything from the beginning you can also use the online editor. this can be a more pleasant working environment if you are not someone who likes to code. see the building up a basic demo with playcanvas editor for details. summary of course, it depends on your approach — designers may favor the online editor while programmers will prefer having the full control over the coding environment and will probably use the engine's source files. the good thing is that you have a choice and can pick whatever tools suit you best. ...
WebVR — Virtual Reality for the Web - Game development
for example: function setcustomfov(up,right,down,left) { var testfov = ne...
...for example: function setcustomfov(up,right,down,left) { var testfov = new vrfieldofview(up,right,down,left); ghmd.setfieldofview(testfov,testfov,0.01,10000.0); } the gpositionsensor variable holds the positionsensorvrdevice — using this you can get the current position or orientation state (for example to update the scene view on every frame), or reset the sensor. ...
Tools for game development - Game development
ools. asm.js asm.js is a very limited subset of the javascript language, which can be greatly optimized and run in an ahead-of-time (aot) compiling engine for much faster performance than your typical javascript performance. this is, of course, great for games. ...
... shumway shumway is a renderer for adobe flash built entirely in javascript, webgl, etc., bridging the gap between flash and web standards. ...
Animations and tweens - Game development
to make the game look more juicy and alive we can use animations and tweens. this will result in a better, more entertaining experience. let's explore how to implement phaser animations and tweens in our game. animations in phaser, animations, involve taking a spritesheet from an external source and displaying the sprites sequentially. as an example, we will make the ball wobble when it hits something. ...
...ng do to is to start the tween right away using start(). that's the expanded version of the tween definition, but we can also use the shorthand syntax: game.add.tween(brick.scale).to({x:2,y:2}, 500, phaser.easing.elastic.out, true, 100); this tween will double the brick's scale in half a second using elastic easing, will start automatically, and have a delay of 100 miliseconds. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps animations and tweens look very nice, but we can add even more to our game — in the next section we'll look at handling button inputs. « previousnext » ...
Bounce off the walls - Game development
now that physics have been introduced, we can start implementing collision detection into the game — first we'll look at the walls. bouncing off the world boundaries the easiest way to get our ball bouncing off the walls is to tell the framework that we want to treat the boundaries of the <canvas> element as walls and not let the ball move past them. in phaser this can be easily accomplished using the collideworldsbound property. ...
...ball.body.collideworldbounds = true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. to make this occur we have to set its bounciness. add the following line below the previous one: ball.body.bounce.set(1); try reloading index.html again — now you should see the ball bouncing off all the walls and moving inside the canvas area. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps this is starting to look more like a game now, but we can't control it in any way — it's high time we introduced the player paddle and controls. « previousnext » ...
Player paddle and controls - Game development
we have the ball moving and bouncing off the walls, but it quickly gets boring — there's no interactivity! we need a way to introduce gameplay, so in this article we'll create a paddle to move around and hit the ball with. rendering the paddle from the framework point of view the paddle is very similar to the ball — we need to add a variable to represent it, load the relevant image asset, and then do the magic. ...
..., 'ball'); ball.anchor.set(0.5); the velocity stays almost the same — we're just changing the second parameter's value from 150 to -150, so the ball will start the game by moving up instead of down. find the existing ball.body.velocity.set( ... ) line and update it to the following: ball.body.velocity.set(150, -150); now the ball will start right from the middle of the paddle. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we can move the paddle and bounce the ball off it, but what's the point if the ball is bouncing off the bottom edge of the screen anyway? let's introduce the possibility of losing — also known as game over logic. « previousnext » ...
The score - Game development
having a score can also make the game more interesting — you can try to beat your own highscore, or your friend's. in this article we'll add a scoring system to our game. we will use a separate variable for storing the score and phaser's text() method to print it out onto the screen. new variables add two new variables right after the previously defined ones: // ... ...
...k and update the scoretext to display the current score. this can be done using the settext() method — add the two new lines seen below to the ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); } that's it for now — reload your index.html and check that the score updates on every brick hit. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we now have a scoring system, but what's the point of playing and keeping score if you can't win? let's see how we can add a victory state, allowing us to win the game. « previousnext » ...
404 - MDN Web Docs Glossary: Definitions of Web-related terms
a 404 is a standard response code meaning that the server cannot find the requested resource. ...
... a 404 is a standard response code meaning that the server cannot find the requested resource. ...
502 - MDN Web Docs Glossary: Definitions of Web-related terms
an http error code meaning "bad gateway". a server can act as a gateway or proxy (go-between) between a client (like your web browser) and another, upstream server. when you request to access a url, the gateway server can relay your request to the upstream server. "502" means that the upstream server has returned an invalid response. normally the upstream server is not down (i.e. furnishes no response to the gateway/proxy), but simply does not understand the same data-exchange protocol as the gateway/proxy. internet protocols are quite explicit, and so a 502 usually means that one or both machines were incorrectly or incompletely programmed. ...
...stream server has returned an invalid response. normally the upstream server is not down (i.e. furnishes no response to the gateway/proxy), but simply does not understand the same data-exchange protocol as the gateway/proxy. internet protocols are quite explicit, and so a 502 usually means that one or both machines were incorrectly or incompletely programmed. learn more list of http response codes ...
ASCII - MDN Web Docs Glossary: Definitions of Web-related terms
since 2007, utf-8 superseded it on the web. ...
...since 2007, utf-8 superseded it on the web. ...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
can change internal implementation of class independently without affecting the user. ...
... can change internal implementation of class independently without affecting the user. ...
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). ...
...antee that all attack methods have been discovered, but each algorithm is judged against known classes of attacks. ciphers operate two ways, either as block ciphers on successive blocks, or buffers, of data, or as stream ciphers on a continuous data flow (often of sound or video). they also are classified according to how their keys are handled: symmetric key algorithms use the same key to encode and decode a message. the key also must be sent securely if the message is to stay confidential. asymmetric key algorithms use a different key for encryption and decryption. ...
Cipher suite - MDN Web Docs Glossary: Definitions of Web-related terms
a cipher suite is a combination of a key exchange algorithm, authentication method, bulk encryption cipher, and message authentication code. in a cryptosystem like tls, the client and server must agree on a cipher suite before they can begin communicating securely. ...
...suite before they can begin communicating securely. ...
Conditional - MDN Web Docs Glossary: Definitions of Web-related terms
a condition is a set of rules that can interrupt normal code execution or change it, depending on whether the condition is completed or not. an instruction or a set of instructions is executed if a specific condition is fulfilled. otherwise, another instruction is executed. it is also possible to repeat the execution of an instruction, or set of instructions, while a condition is not yet fulfilled. ...
...pleted or not. an instruction or a set of instructions is executed if a specific condition is fulfilled. ...
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
the benefit of houdini is that developers can create css features without waiting for web standards specifications to define them and without waiting for every browser to fully implement the features. ...
...features houdini enables can be created with javascript, interacting directly with the cssom before javascript is enabled provides for faster parse times. browsers create the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts: layout, paint, and composite processes are repeated for updated javascript styles to be implemented. houdini code doesn't wait for that first rendering cycle to be complete. rather, it is included in that first cycle, creating renderable, understandable styles. see also houdini houdini: an introduction cssom css paint api css typed om ...
Idempotent - MDN Web Docs Glossary: Definitions of Web-related terms
w with the same effect while leaving the server in the same state. in other words, an idempotent method should not have any side-effects (except for keeping statistics). implemented correctly, the get, head, put, and delete method are idempotent, but not the post method. all safe methods are also idempotent. to be idempotent, only the actual back-end state of the server is considered, the status code returned by each request may differ: the first call of a delete will likely return a 200, while successive ones will likely return a 404. another implication of delete being idempotent is that developers should not implement restful apis with a delete last entry functionality using the delete method. note that the idempotence of a method is not guaranteed by the server and some applications may ...
... technical knowledge description of common idempotent methods: get, head, put, delete, options, trace desc...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
syntax specifies the required combination and sequence of characters making up correctly structured code. syntax generally includes grammar and the rules that apply to writing it, such as indentation requirements in python. syntax varies from language to language (e.g., syntax is different in html and javascript). although languages can share few similarities in terms of their syntaxes for example "operand operator operand" rule in javascript and python. this does not mean the two langauges share similarities with syntax. syntax applies both to programming languages (commands to the computer) and markup languages (document structure information) alike. ...
...es for example "operand operator operand" rule in javascript and python. this does not mean the two langauges share similarities with syntax. syntax applies both to programming languages (commands to the computer) and markup languages (document structure information) alike. syntax only governs ordering and structure; the instructions must also be meaningful, which is the province of semantics. code must have correct syntax in order to compile correctly, otherwise a syntax error occurs. even small errors, like a missing parenthesis, can stop source code from compiling successfully. frameworks are said to have a "clean" syntax if they produce simple, readable, concise results. if a codebase uses "a lot of syntax", it requires more characters to achieve the same functionality. learn more ge...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
because these things are all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite loop, the entire browser will hang. this results in a frustrating, sluggish (or worse) user experience. ...
...because these things are all happening in one thread, a slow website or app script slows down the entire browser; worse, if a site or app script enters an infinite loop, the entire browser will hang. this results in a frustrating, sluggish (or worse) user experience. ...
Tree shaking - MDN Web Docs Glossary: Definitions of Web-related terms
tree shaking is a term commonly used within a javascript context to describe the removal of dead code. it relies on the import and export statements in es2015 to detect if code modules are exported and imported for use between javascript files. in modern javascript applications, we use module bundlers (e.g., webpack or rollup) to automatically remove dead code when bundling multiple javascript files into single files. this is important for preparing code that is production ready, for example with clean structures and minimal file size. ...
... and imported for use between javascript files. in modern javascript applications, we use module bundlers (e.g., webpack or rollup) to automatically remove dead code when bundling multiple javascript files into single files. this is important for preparing code that is production ready, for example with clean structures and minimal file size. ...
UTF-8 - MDN Web Docs Glossary: Definitions of Web-related terms
utf-8 (ucs transformation format 8) is the world wide web's most common character encoding. each character is represented by one to four bytes. utf-8 is backward-compatible with ascii and can represent any standard unicode character. the first 128 utf-8 characters precisely match the first 128 ascii characters (numbered 0-127), meaning that existing ascii text is already valid utf-8. all other characters use two to four bytes. each byte has some bits reserved for encoding purposes. ...
...umbered 0-127), meaning that existing ascii text is already valid utf-8. all other characters use two to four bytes. each byte has some bits reserved for encoding purposes. since non-ascii characters require more than one byte for storage, they run the risk of being corrupted if the bytes are separated and not recombined. learn more general knowledge utf-8 on wikipedia faq about utf-8 on unicode website ...
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
ipt library that focuses on simplifying dom manipulation, ajax calls, and event handling. jquery uses a format, $(selector).action() to assign an element(s) to an event. to explain it in detail, $(selector) will call jquery to select selector element(s), and assign it to an event api called .action(). ...
...tion, ajax calls, and event handling. jquery uses a format, $(selector).action() to assign an element(s) to an event. to explain it in detail, $(selector) will call jquery to select selector element(s), and assign it to an event api called .action(). ...
Percent-encoding - MDN Web Docs Glossary: Definitions of Web-related terms
percent-encoding is a mechanism to encode 8-bit characters that have specific meaning in the context of urls. it is sometimes called url encoding. the encoding consists of substitution: a '%' followed by the hexadecimal representation of the ascii value of the replace character. special characters needing encoding are: ':', '/', '?', '#', '[', ']', '@', '!', '$', '&', "'", '(', ')', '*', '+', ',', ';', '=', as well as '%' itself. other characters don't need to be encoded, though they could. ':' '/' '?' '#' '[' ']' '@' '!' '$' '&' "'" '(' ')' '*' '+' ',' ';' '=' '%' ' ' %3a %2f %3f %23 %5b %5d %40 %21 %24 %26 %27 %28 %29 %2a %2b %2c %3b %3d %25 %20 or + ...
... learn more general knowledge definition of percent-encoding in wikipedia. technical knowledge rfc 3986, section 2.1, where this encoding is defined. ...
Assessment: Accessibility troubleshooting - Learn web development
le 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 asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for accessibility troubleshooting". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you...
...lity troubleshooting". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. previous overview: accessibility in this module what is accessibility? html: a good basis for accessibility css and javascript accessibility best practices wai-aria basics accessible multimedia mobile accessibility accessibility troubleshooting ...
CSS and JavaScript accessibility best practices - Learn web development
another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. instead of marking required form fields in red, for example, mark them with an asterisk and in red. hiding things there are many instances where a visual design will require that not all content is shown at once. for example, in our tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use tab and enter/return to select them). screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all...
...blur would provide accessibility for keyboard users. let's look at an example that highlights when this could be useful. maybe we want to provide a thumbnail image that shows a larger version of the image when it is moused over or focused (like you'd see on an e-commerce product catalog.) we've made a very simple example, which you can find at mouse-and-keyboard-events.html (see also the source code). the code features two functions that show and hide the zoomed-in image; these are run by the following lines that set them as event handlers: imgthumb.onmouseover = showimg; imgthumb.onmouseout = hideimg; imgthumb.onfocus = showimg; imgthumb.onblur = hideimg; the first two lines run the functions when the mouse pointer hovers over and stops hovering over the thumbnail, respectively. this won...
What is accessibility? - Learn web development
the below video also provides a brief example of what the experience is like. in terms of statistics, the world health organization estimates that "285 million people are estimated to be visually impaired worldwide: 39 million are blind and 246 have low vision." (see visual impairment and blindness). that's a large and significant population of users to just miss out on because your site isn't coded properly — almost the same size as the population of the united states of america. people with hearing impairments otherwise known as people with auditory impairments or deaf people, this group of people has either low hearing levels or no hearing at all. hearing-impaired people do use ats (see assistive devices for people with hearing, voice, speech, or language disorders), but there are no...
...certain user finding certain content difficult to use — but you should do as much as you can. if you are planning to include a whizzy 3d pie chart graphic made using webgl, you might want to include a data table as an accessible alternative representation of the data. or, you might want to just include the table and get rid of the 3d pie chart — the table is accessible by everyone, quicker to code, less cpu-intensive, and easier to maintain. on the other hand, if you are working on a gallery website showing interesting 3d art, it would be unreasonable to expect every piece of art to be perfectly accessible to visually impaired people, given that it is an entirely visual medium. to show that you care and have thought about accessibility, publish an accessibility statement on your site tha...
A cool-looking box - Learn web development
ite shadow near the top left and a semi-transparent black shadow near the bottom right — to add to the nice raised 3d look of the box. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for cool-looking box". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assesse...
...for cool-looking box". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
Cascade and inheritance - Learn web development
l. note: there is also a newer value, revert, which has limited browser support. note: see origin of css declarations in introducing the css cascade for more information on each of these and how they work. we can look at a list of links and explore how the universal values work. the live example below allows you to play with the css and see what happens when you make changes. playing with code really is the best way to get to grips with html and css. for example: the second list item has the class my-class-1 applied. this sets the color of the <a> element nested inside to inherit. if you remove the rule how does it change the color of the link? do you understand why the third and fourth links are the color that they are? check the description of the values above if not. which of ...
...e in the previous rule, even though the id has higher specificity. note: the only way to override this !important declaration would be to include another !important declaration on a declaration with the same specificity later in the source order, or one with a higher specificity. it is useful to know that !important exists so that you know what it is when you come across it in other people's code. however, we strongly recommend that you never use it unless you absolutely have to. !important changes the way the cascade normally works, so it can make debugging css problems really hard to work out, especially in a large stylesheet. one situation in which you may have to use it is when you are working on a cms where you can't edit the core css modules, and you really want to override a style...
Fundamental CSS comprehension - Learn web development
s, and what it needs to be multiplied by to get the desired value. that'll give you your em value, at least in a simple case like this. example the following screenshot shows an example of what the finished design should look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for fundamental css comprehension". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you...
...al css comprehension". details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. ...
Pseudo-classes and pseudo-elements - Learn web development
ors. what is a pseudo-class? a pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. they tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code. pseudo-classes are keywords that start with a colon: :pseudo-class-name simple pseudo-class example let's look at a simple example. if we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add css to that class, as shown in the first example below: however, this could be annoying to maintain — what if a new paragraph got add...
...ement using keyboard controls. what is a pseudo-element? pseudo-elements behave in a similar way, however they act as if you had added a whole new html element into the markup, rather than applying a class to existing elements. pseudo-elements start with a double colon ::. ::pseudo-element-name note: some early pseudo-elements used the single colon syntax, so you may sometimes see this in code or examples. modern browsers support the early pseudo-elements with single- or double-colon syntax for backwards compatibility. for example, if you wanted to select the first line of a paragraph you could wrap it in a <span> element and use an element selector; however, that would fail if the number of words you had wrapped were longer or shorter than the parent element's width. as we tend not ...
Supporting older browsers - Learn web development
er into a grid container, any flex property applied to the children will be ignored. for many layout tweaks in older browsers, you may find you can give a decent experience by using css in this way. we add a simpler layout based on older and well-supported techniques, then use the newer css to create the layout that over 90% of your audience will see. there are cases, however, when the fallback code will need to include something that the new browsers will also interpret. a good example of this is if we were to add percentage widths to our floated items to make the columns more like the grid display, stretching to fill the container. in the floated layout, the percentage is calculated from the container — 33.333% is a third of the container width. in grid however that 33.333% is calculate...
...s that an approach as detailed above will work for those browsers. what we are doing is writing our old css first, outside of any feature query. browsers that do not support grid, and do not support the feature query will use that layout information they can understand and completely ignore everything else. the browsers that support the feature query also support css grid and so will run the grid code and the code inside the feature query. the specification for feature queries also contains the ability to test if a browser does not support a feature — this is only helpful if the browser does support feature queries. in the future, an approach of checking for lack of support will work, as the browsers that don’t have feature query support go away. for now, however, use the approach of doin...
What is CSS? - Learn web development
formation. it can even be used for effects such as animation. have a look at the links in this paragraph for specific examples. css syntax css is a rule-based language — you define rules specifying groups of styles that should be applied to particular elements or groups of elements on your web page. for example "i want the main heading on my page to be shown as large red text." the following code shows a very simple css rule that would achieve the styling described above: h1 { color: red; font-size: 5em; } the rule opens with a selector . this selects the html element that we are going to style. in this case we are styling level one headings (<h1>). we then have a set of curly braces { }. inside those will be one or more declarations, which take the form of property and value p...
...rienced developers would much rather refer to mdn documentation or other tutorials. it is however worth knowing that they exist, understanding the relationship between the css you are using, browser support (see below), and the specs. browser support once css has been specified then it is only useful for us in developing web pages if one or more browsers have implemented it. this means that the code has been written to turn the instruction in our css file into something that can be output to the screen. we'll look at this process more in the lesson how css works. it is unusual for all browsers to implement a feature at the same time, and so there is usually a gap where you can use some part of css in some browsers and not in others. for this reason, being able to check implementation status ...
Basic native form controls - Learn web development
ch the :default pseudo class, even if they are no longer checked. any that are currently checked match the :checked pseudoclass. due to the on-off nature of checkboxes, the checkbox is considered a toggle button, with many developers and designers expanding on the default checkbox styling to create buttons that look like toggle switches you can see an example in action here (also see the source code). radio button a radio button is created using the <input> element with its type attribute set to the value radio: <input type="radio" id="soup" name="meal" checked> several radio buttons can be tied together. if they share the same value for their name attribute, they will be considered to be in the same group of buttons. only one button in a given group may be checked at a time; this means ...
...its name; let's move on and look at actual buttons! there are three input types that produce buttons: submit sends the form data to the server. for <button> elements, omitting the type attribute (or an invalid value of type) results in a submit button. reset resets all form widgets to their default values. button buttons that have no automatic effect but can be customized using javascript code. then we also have the <button> element itself. this can take a type attribute of value submit, reset, or button to mimic the behevior of the three <input> types mentioned above. the main difference between the two is that actual <button> elements are much easier to style. note: the image input type also renders as a button. we'll cover that later too. note: you can find the examples from ...
HTML forms in legacy browsers - Learn web development
platform-native styling, or, as is done with the value of none, remove default platform-native based styling. unobtrusive javascript one of the biggest problems is the availability of apis. for that reason, it's considered best practice to work with "unobtrusive" javascript. it's a development pattern that defines two requirements: a strict separation between structure and behaviors. if the code breaks, the content and the basic functionalities must remain accessible and usable. the principles of unobtrusive javascript (originally written by peter-paul koch for dev.opera.com) describes these ideas very well. the modernizr library there are many cases where a good "polyfill" can help a lot by providing a missing api. a polyfill is a bit of javascript that "fills in the holes" in the f...
...itical with legacy browsers; many of them have a very slow javascript engine that can make the execution of all your polyfills painful for the user. performance is a subject on its own, but legacy browsers are very sensitive to it: basically, they are slow and the more polyfills they need, the more javascript they have to process. so they are doubly burdened compared to modern browsers. test your code with legacy browsers to see how they actually perform. sometimes, dropping some functionality leads to a better user experience than having exactly the same functionality in all browsers. as a last reminder, just always think about the end users. conclusion as you can see, considering browser and operating system default form control appearance is important. there are many techniques to handle ...
How to structure a web form - Learn web development
here you'll see that we are wrapping the contact information fields inside a distinct <section> element. moreover, we have a set of two radio buttons, each of which we are putting inside its own list (<li>) element. we also have two standard text <input>s and their associated <label> elements, each contained inside a <p>, and a password input for entering ...
... our previous entry. here you'll see that we are wrapping the contact information fields inside a distinct <section> element. moreover, we have a set of two radio buttons, each of which we are putting inside its own list (<li>) element. we also have two standard text <input>s and their associated <label> elements, each contained inside a <p>, and a password input for entering a password. ...
How the Web works - Learn web development
clients and servers computers connected to the web are called clients and servers. ...
...s of the shop so you can access it. http: hypertext transfer protocol is an application protocol that defines a language for clients and servers to speak to each other. this is like the language you use to order your goods. component files: a website is made up of many different files, which are like the different parts of the goods you buy from the shop. these files come in two main types: code files: websites are built primarily from html, css, and javascript, though you'll meet other technologies a bit later. assets: this is a collective name for all the other stuff that makes up a website, such as images, music, video, word documents, and pdfs. so what happens, exactly? when you type a web address into your browser (for our analogy that's like walking to the shop): the br...
Use HTML to solve common problems - Learn web development
Learn › HTML › Howto
set up a proper structure of headings and paragraphs basic text-level semantics html specializes in providing semantic information for a document, so html answers many questions you might have about how to get your message across best in your document. ...
...re you should start: how to create a simple web form how to structure a web form tabular information some information, called tabular data, needs to be organized into tables with columns and rows. it's one of the most complex html structures, and mastering it is not easy: how to create a data table how to make html tables accessible data representation how to represent numeric and code values with html — see superscript and subscript, and representing computer code. how to use data attributes advanced text semantics how to take control of html line breaking how to mark changes (added and removed text) — see the <ins> and <del> elements. advanced images & multimedia how to add a responsive image to a webpage how to add vector image to a webpage how to add a h...
Asynchronous JavaScript - Learn web development
t familiar with the concept of asynchronous programming, you should definitely start with the general asynchronous programming concepts article in this module. if you are, then you can probably skip to the introducing asynchronous javascript module. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding program such as jsbin or glitch. guides general asynchronous programming concepts in this article we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript. you should understand these concepts before working through the other articles in the module. introducing asynchronous java...
... asynchronous javascript in this article we briefly recap the problems associated with sychronous javascript, and take a first look at some of the different asynchronous javascript techniques you'll encounter, showing how they can help us solve such problems. cooperative asynchronous javascript: timeouts and intervals here we look at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), talk about what they are useful for, and look at their inherent issues. handling async operations gracefully with promises promises are a comparatively new feature of the javascript language that allow you to defer further actions until after the previous action has completed, or...
JavaScript — Dynamic client-side scripting - Learn web development
and "what can it do?", before moving on to taking you through your first practical experience of writing javascript. after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays. javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. introducing javascript objects in javascript, most things are objects, from core javascript features like strings and arrays to the browser apis built on top of javascript. you can even create your own objects to encapsul...
...ascript, most things are objects, from core javascript features like strings and arrays to the browser apis built on top of javascript. you can even create your own objects to encapsulate related functions and variables into efficient packages. the object-oriented nature of javascript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. here we teach object theory and syntax in detail, look at how to create your own objects, and explain what json data is and how to work with it. asynchronous javascript in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching reso...
Measuring performance - Learn web development
optimize your site's performance. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. objective: to provide information about web performance metrics that you can collect through various web performance apis and tools that you can use to visualize that data. performance apis when writing code for the web, there are a large number of web apis available that allow you to create your own performance measuring tools. you can use the navigation timing api to measure client-side web performance; including the amount of time needed to unload the previous page, how long domain lookups take, the total time spent executing the window's load handler, and more. you can use the api for metrics re...
...different tools available to help you improve performance. these can generally be classified into two categories: tools that indicate or measure performance, such as pagespeed insights or the firefox network monitor and performance monitor. these tools show you how fast or slow your web app or site load. they also indicate areas that can be improved to optimize your web app. tools that update code so that your web app or site will perform better. for example, bundling tools pack your code into single files to reduce the number of http requests or minifiers that remove all whitespace from your code to make the files smaller. we'll talk about both categories in this course. and as well as talking about performance metrics we will of course talk about the metrics that you'll use to measure ...
Multimedia: video - Learn web development
most video compression work compares adjacent frames within a video, with the intent of removing detail that is identical in both frames. compress the video and export to multiple video formats, including webm, mpeg-4/h.264, and ogg/theora. your video editing software probably has a feature to reduce file size. if not, there are online tools, such as ffmpeg (discussed in section below), that encode, decode, convert, and perform other optimization functions. optimize <source> order order video source from smallest to largest. for example, given video compressions in three different formats at 10mb, 12mb, and 13mb, declare the smallest first and the largest last: <video width="400" height="300" controls="controls"> <!-- webm: 10 mb --> <source src="video.webm" type="video/webm" /> <...
... attribute is required for autoplay in mobile browsers. playsinline is required for mobile safari, allowing videos to play without forcing fullscreen mode. remove audio from muted hero videos for hero-video or other video without audio, removing audio is smart. <video autoplay="" loop="" muted="true" playsinline="" id="hero-video"> <source src="banner_video.webm" type='video/webm; codecs="vp8, vorbis"'> <source src="web_banner.mp4" type="video/mp4"> </video> this hero-video code (above) is common to conference websites and corporate home pages. it includes a video that is auto-playing, looping, and muted. there are no controls, so there is no way to hear audio. the audio is often empty, but still present, and still using bandwidth. there is no reason to serve audio with vide...
Server-side website programming first steps - Learn web development
rogramming?", and "why it is so useful?". after reading this article, you'll understand the additional power available to websites through server-side coding. client-server overview now that you know the purpose and potential benefits of server-side programming, we're going to examine in detail what happens when a server receives a "dynamic request" from a browser. as most websites' server-side code handles requests and responses in a similar way, this will help you understand what you need to do when writing your own code. server-side web frameworks the last article showed you what a server-side web application needs to do in order to respond to requests from a web browser. now we show how web frameworks can simplify these tasks, and help you choose the right framework for your first serv...
...ect your web application against the most common threats. note: this topic deals with server-side frameworks, and how to use them to create websites. if you are looking for information on client-side javascript frameworks, consult our understanding client-side javascript frameworks module. assessments this "first steps" module doesn't have any assessment because we haven't yet shown you any code. we do hope that at this point you have a good understanding of what sorts of functionality you can deliver using server-side programming, and that you have made a decision about what server-side web framework you will use to create your first website. ...
Ember resources and troubleshooting - Learn web development
rmation render performance for general javascript debugging, check out our guides on javascript debugging as well as interacting with the browser's other debugging tools. in any default ember project, there will be two main javascript files, vendor.js and {app-name}.js. both of these files are generated with sourcemaps, so when you open the vendor.js or {app-name}.js to search for relevant code, when a debugger is placed, the sourcemap will be loaded and the breakpoint will be placed in the pre-transpiled code for easier correlation to your project code. for more information on sourcemaps, why they're needed, and what the ember-cli does with them, see the advanced use: asset compilation guide. note that sourcemaps are enabled by default. ember-data comes pre-installed; do i need it? ...
... the route's model here. why can't i just use javascript? this is the most common question ember folks hear from people who have previous experience with react. while it is technically possible to use jsx, or any other form of dom creation, there has yet to be anything as robust as ember's templating system. the intentional minimalism forces certain decisions, and allows for more consistent code, while keeping the template more structural rather than having them filled with bespoke logic. see also: reactiveconf 2017: secrets of the glimmer vm what is the state of the mut helper? mut was not covered in this tutorial and is really baggage from a transitional time when ember was moving from two-way bound data to the more common and easier-to-reason-about one-way bound data flow. it could...
Getting started with Vue - Learn web development
s. project structure if everything went successfully, the cli should have created a series of files and directories for your project. the most significant ones are as follows: .eslintrc.js: this is a config file for eslint. you can use this to manage your linting rules. babel.config.js: this is the config file for babel, which transforms modern javascript features being used in development code into older syntax that is more cross-browser compatible in production code. you can register additional babel plugins in this file. .browserslistrc: this is a config for browserslist. you can use this to control which browsers your tooling optimizes for. public: this directory contains static assets that are published, but not processed by webpack during build (with one exception; index.html ge...
...u will also have a views directory). .vue files (single file components) like in many front-end frameworks, components are a central part of building apps in vue. these components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. these small blocks can help you reason about and test your code. while some frameworks encourage you to separate your template, logic, and styling code into separate files, vue takes the opposite approach. using single file components, vue lets you group your templates, corresponding script, and css all together in a single file ending in .vue. these files are processed by a js build tool (such as webpack), which means you can take advantage of build-time to...
Adding a new todo form: Vue events, methods, and models - Learn web development
anced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn about handling forms in vue, and by association, events, models, and methods. creating a new to-do form we now have an app that displays a list of to-do items. however, we can't update our list of items without manually changing our code! let's fix that. let's create a new component that will allow us to add a new to-do item. in your components folder, create a new file called todoform.vue. add a blank <template> and a <script> tag like before: <template></template> <script> export default {}; </script> let's add in an html form that lets you enter a new todo item and submit it into the app. we need a <for...
...s seen below. do this now: <input type="text" id="new-todo-input" name="new-todo" autocomplete="off" v-model="label" /> note: you can also sync data with <input> values through a combination of events and v-bind attributes. in fact, this is what v-model does behind the scenes. however, the exact event and attribute combination varies depending on input types and will take more code than just using the v-model shortcut. let's test out our use of v-model by logging the value of the data submitted in our onsubmit() method. in components, data attributes are accessed using the this keyword. so we access our label field using this.label. update your onsubmit() method to look like this: methods: { onsubmit() { console.log('label value: ', this.label); } }, ...
Chrome Worker Modules
stack traces unfortunately, the module loader doesn’t play nicely with error stack traces. that is, the following will not show human-readable stacks: try { mymodule.foo(); } catch (ex) { log("exception raised at " + ex.filename) log("stack: " + ex.stack); } rather, you should use properties modulen...
... // assuming that mymodule.js is installed to resource://gre/modules/mymodule.js let module = require("resource://gre/modules/mymodule.js") foo(module.key); // module.key == "this is public"; // however, secretkey is not exported and cannot be used for the installation of resources, please see the documentation on moz.build (if your code is part of the platform) or on chrome manifests (if your code is part of an add-on). stack traces unfortunately, the module loader doesn’t play nicely with error stack traces. that is, the following will not show human-readable stacks: try { mymodule.foo(); } catch (ex) { log("exception raised at " + ex.filename) log("stack: " + ex.stack); } rather, you should use properties modulename and modulestack, as follows: try { mymodule.foo(); ...
Embedding API for Accessibility
e a number of prefs related to accessibility. for the most part, an automatic reframe is performed when one of these prefs is changed. a reframe fixes the appearance of the page to match the new prefs, without reloading the document over the network. ...
... moz 0.8 fonts setcharpref("font.name.monospace.x-western", newfontname); setcharpref("font.name.serif.x-western", newfontname); setcharpref("font.name.sans-serif.x-western", newfontname); /* for other i18n charsets, change x-western to x-central-euro, x-cyrillic, x-unicode, x-user-def, x-baltic, el, tr, he, ar, th, ja, zh-cn or zh-tw */ setintpref("font.size.fixed.x-western", newfontsize); setintpref("font.size.variable.x-western", newfontsize); /* for other i18n charsets, change the name as explained above for font face*/ se...
Mozilla’s UAAG evaluation report
(p1) c can be changed through preferences or user style sheet the prefs are at preferences, appearances, fonts 4.3 configure text colors. (p1) vg can be changed through preferences or by editing the prefs.js file the prefs are at preferences, appearances, colors to us...
...for end-users, only developer documentation 11.2 current author bindings. (p2) ni the web page itself is currently responsible for letting the user know what accesskey's are available. 11.3 override bindings. (p2) p some bindings can be changed. see "the customizing document" there is no central place to change all bindings. unforutunately, some are hard coded. needs work. bug#? 11.4 single key access. (p2) ni bug 953707 is our open bug for this. help wanted. 11.5 default binding requirements. (p2) c provides stated functions 11.6 user profiles. (p2) vg user profiles are fully supported for all configuration options. unfortunately, switching profiles requires the entire application to be relaun...
Theme concepts
can combine the two and bundle a programmatically controlled theme with your extension. using the theme api is straightforward. first, request "theme" permission in the extension's manifest.json file. next, you build a json object containing the same information you would use in a static theme’s manifest.json, finally, pass the json object in a theme.update() call. ...
... return; } currenttheme = theme; browser.theme.update(themes[theme]); } learn more about dynamic themes and see an additional example in the following video: if you have not built a browser extension before, check out your firs...
Adding a new event
this draft document covers how to add a new event to the mozilla (firefox) source code. what type of event do you want? roughly, there are 3 types of event. first, you need to choose which type you need. a simple dom event which can be implemented with webidl and widgetevent or something. this type of event is useful if the event isn't handled by c++ code. a dom event which represents a native event like a user action such as keyboard or mouse input. this type of event allows c++ code to handle it easier. it's not a dom event. however, c++ code may need to dispatch an event to dom tree and handle it with c++ event handler. this is useful for widget notifying dom tree of something or retrieving something from dom tree. how to implement an internal event class if you're in ...
... detail: 5 }); you shouldn't define construnctor in it. create xpcom interface for the dom event if your event class should be accessible via xpcom interface, you should create a new nsidomfooevent interface in dom/interfaces/events/. however, in these days, this is not necessary. ...
Application cache implementation overview
are not executed. the channel remembers the nsiapplicationcache object. nsiapplicationcache is then queried a client id (= the manifest url + a unique time stamp). then, nsicacheservice is asked to open nsicachesession with store_offline policy and the given client id. entry is queried using that session. nshttpchannel::onofflinecacheentryavailable is then invoked. when aentrystatus is a success code, entry has been found and we are loading it from the cache. loadedfromapplicationcache flag is now set true on the channel. when aentrystatus is a failure code, entry has not been found, but the url is falling under one of the network or fallback namespaces. when matching fallback namespace, the associated fallback entry for it is remembered. the load then continues from the network as a usual lo...
... happens in nscontentsink::processofflinemanifest() called from the html parser every time <html> tag has been parsed. processofflinemanifest is an effective implementation of “cache selection algorithm” as described by the html5 spec. for purpose of this documentation it's enough to describe the simplest case ; for complete documentation of the selection algorithm refer to the spec or to the code. when the url in the manifest attribute of the html tag is identical to the manifest url the channel's nsiapplicationcache object belongs to and, the channel's loadedfromapplicationcache flag is set, the document is associated with that nsiapplicationcache object and an update attempt for the manifest is scheduled after the document completely loads. marking entries as foreign when nscontentsink:...
Chrome registration
ibing the contents of windows and dialogs. the javascript files that define the user interface are also contained within the content packages, as well as most xbl binding files. locale localizable applications keep all their localized information in locale providers. this allows translators to plug in a different chrome package to translate an application without altering the rest of the source code. the two main types of localizable files are dtd files and java-style properties files. skin a skin provider is responsible for providing a complete set of files that describe the visual appearance of the chrome. typically a skin provider will provide css files and images. note: scripts (including those found in xbl) loaded from skin packages will not execute. the chrome registry the geck...
...he content process using the manifest file so this flag is largely useless to extension developers. component {09543782-22b1-4a0b-ba07-9134365776ee} maincomponent.js process=main component {98309951-ac89-4642-afea-7b2b6216bcef} contentcomponent.js process=content xpcnativewrappers chrome packages can decide whether to use the xpcnativewrapper security mechanism to automatically protect their code against malicious content that they might access. see safely accessing content dom from chrome for details. this flag is enabled by default since firefox 1.5. disabling it manually was possible by specifying xpcnativewrappers=no until firefox 4. note: support for this flag has been removed in gecko 2.0. you can no longer disable xpcnativewrappers. to update your add-on to work without this fla...
Continuous Integration
mpleted, they are used to run a series of correctness and performance tests. the results of taskcluster jobs (both builds and tests) are displayed in treeherder. there is a group of individuals who are constantly monitoring treeherder, looking for broken builds and/or tests. these individuals are known as sheriffs. the sheriffs' role is to "keep the tree green", or in other words, to keep the code in our respositories in a good state, to the extent that the state is reflected in the output shown on treeherder. when sheriffs see a build or test has been broken, they are empowered to take one of several actions, including backing out a patch which caused the problem and closing the tree (i.e., preventing any additional commits). results in treeherder are ordered by mercurial pushes. each ...
...ushes. each taskcluster job is represented by a colored label; green means a job has succeeded, while other colors represent different kinds of problems. the label text indicates the job type. for a full list of job types, see the help menu in treeherder's upper-right corner. below is a list of the most common. builds b - normal build jobs; these jobs perform compilation and some compiled-code tests (e.g., 'make check'). be - b2g build jobs for engineering builds; user builds are denoted with b, the same as for desktop and android builds. n and ne - nightly build jobs; these jobs are similar to b and be jobs, but are triggered on a periodic basis instead of being triggered by a push to hg. hf - static rooting hazard analysis s - static analysis v - valgrind build and test jobs; th...
Creating JavaScript callbacks in components
callback patterns in idl xpcom components use idl to create interfaces. these interfaces are used to manipulate the component in c++ and javascript. a common pattern used with interfaces to create a bi-directional communication between two groups of code is the observer (or listener) pattern. basically, the component defines an observer (or listener) interface which is implemented by some external code and this implementation is passed to the component. the component can then call methods on the observer interface to signal the external code when predefined events occur. here is a very simple example of the observer pattern: [scriptable, uuid(...)] interface stringparserobserver { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data)...
...ing a word found in the raw string data. here is an example of how to use the callback system: var wordhandler = { onword : function(word) { alert(word); } }; var stringparser = /* get a reference to the parser somehow */ stringparser.addobserver(wordhandler); stringparser.parse("pay no attention to the man behind the curtain"); you can find examples of this pattern all over the mozilla codebase. in fact, there is even a specific interface for this form of push callbacks, nsiobserverservice. javascript functions as callbacks another common use of the pattern is found in addeventlistener / removeeventlistener. a nice feature of addeventlistener is that you can pass a javascript function in place of the callback listener interface. remember (or discover) that addeventlistener is a meth...
Debugging OpenGL
opengl debug mode when running a debug build, you can enable the opengl debug mode by defining the environment variable moz_gl_debug. if you start up firefox with this variable defined, the following behavior changes occur: each time you issue an opengl call, a check is performed to ensure that the gl context is current, using a thread-local static variable to keep track of this. if the context isn't current, the call aborts. every time an opengl call completes, glfinish() gets run automatically. ...
... opengl call. this can help make it much easier to debug crashes and hangs that make the computer unusable (thereby stymieing attempts to debug). the moz_gl_debug_abort_on_error environment variable, if set, causes firefox to abort as soon as an opengl error occurs. this is generally only useful in cases where you know that no error should occur, since there are cases where perfectly valid webgl code may generate opengl errors. you don't have to define more than one of these; for example, if you set moz_gl_debug_abort_on_error, the moz_gl_debug setting is assumed. ...
Simple SeaMonkey build
(for some mac os x versions, you will find it in a directory called "optional installs".) install macports. run these commands to install the other build tools: sudo port sync sudo port install mercurial libidl autoconf213 yasm problems? see mac os x build prerequisites. windows: ...
...s-devel mesa-libgl-devel alsa-lib-devel libxt-devel gstreamer-devel gstreamer-plugins-base-devel pulseaudio-libs-devel # 'development tools' is defunct in fedora 19 and above use the following sudo yum groupinstall 'c development tools and libraries' sudo yum group mark install "x software development" mac: install xcode tools. insert "mac os x install disc 2", then open xcodetools.mpkg. (for some mac os x versions, you will find it in a directory called "optional installs".) install macports. run these commands to install the other build tools: sudo port sync sudo port install mercurial libidl autoconf213 yasm problems? see mac os x build prerequisites. windows: install visual c++ 2013. both the professional edition a...
Simple Sunbird build
(for some mac os x versions, you will find it in a directory called "optional installs".) install macports. run these commands to install the other build tools: sudo port sync sudo port install mercurial libidl autoconf213 problems? see mac os x build prerequisites. windows: if you're using windows xp, you must have wind...
...t install mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libiw-dev autoconf2.13 cvs fedora linux: sudo yum groupinstall 'development tools' 'development libraries' 'gnome software development' sudo yum install mercurial autoconf213 glibc-static libstdc++-static yasm wireless-tools-devel mesa-libgl-devel mac: install xcode tools. insert "mac os x install disc 2", then open xcodetools.mpkg. (for some mac os x versions, you will find it in a directory called "optional installs".) install macports. run these commands to install the other build tools: sudo port sync sudo port install mercurial libidl autoconf213 problems? see mac os x build prerequisites. windows: if you're using windows xp, you must have windows xp service pack 2 and .net framework 2.0. install vis...
Listening to events on all tabs
the nsirequest that has changed state. this parameter may be null. need more information on what null means. astateflags flags indicating the new state. this value is a combination of one of the state transition flags and one or more of the state type flags defined in the nsiwebprogresslistener documentation. any undefined bits are reserved for future use. astatus error status code associated with the state change; this indicates whether or not the request was successful. this parameter should be ignored unless astateflags includes the state_stop bit. note: astatus may be a success code even for server generated errors, such as the http 404 file not found error. in such cases, the request itself should be queried for extended error information (e.g., for http requests se...
...wser). void onstatuschange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, nsresult astatus, prunichar *amessage ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. arequest the nsirequest that has new status. astatus this value is not an error code. instead, it is a numeric value that indicates the current status of the request. this interface does not define the set of possible status codes. note: some status values are defined by nsitransport and nsisockettransport. amessage localized text corresponding to astatus. onrefreshattempted notification that a refresh or redirect has been requested in awebprogress for example, v...
SVG Guidelines
s) ship without being cleaned up and can contain a ton of junk that bloats the file size and slows down rendering. in general the best way to combat this is to first run svg files through a linter such as svgo (see the tools section below). however, when authoring svgs by hand here are some best practices to help keep them lightweight. these rules are based on some real examples seen in mozilla's code. basics two spaces indenting no useless whitespaces or line breaks (see below for more details) adding a license header use double quotes whitespace and line breaks whitespace in addition to trailing whitespace at the end of lines, there are a few more cases more specific to svgs: trailing whitespaces in attribute values (usually seen in path definitions) excessive whitespace in p...
...uch context-awareness. to this date, there doesn't seem to be a tool that handles all of the above. ...
Frame script loading and lifetime
the script just writes "foo" to the command line: // chrome script var mm = gbrowser.selectedbrowser.messagemanager; mm.loadframescript('data:,dump("foo\\n")', true); loadframescript() takes two mandatory parameters: a url that points to the frame script you want to load a boolean flag, allowdelayedload note: if the message manager is a global frame message manager or a window message manager, loadframescript() may load the script multiple times, once in each applicable frame. ...
...10s framescripts work fine on updating. for non-e10s waiting for bug 1202125 - framescripts are not backwards loaded in message order in non-e10s. note: you might think that there is a race condition here due to the asynchronous nature of the message passing: your add-on is disabled for an upgrade. your add-on broadcasts "disable" to your frame scripts. your add-on is upgraded, and the new code loads new frame scripts. the new frame scripts receive the "disable" message and stop working. in fact, the message manager guarantees that loadframescript and broadcastasyncmessage are guaranteed to affect frame scripts in the order that they are called, so in this case "disable" will be received and consumed before the new frame scripts are loaded. at the moment, frame scripts are cached u...
Process scripts
however, a problem with frame scripts is that they can be loaded multiple times in the content process, in multiple scopes that are insulated from each other. for example, if you call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs. ...
...be registered in the content process, but if you do this in a frame script, and the frame script is loaded more than once, then you will get multiple notifications for that event. the solution in these cases is to use a process script instead of a frame script. you can load a process script by accessing a parent process message manager and calling its loadprocessscript() function. the following code uses the global parent process message manager, which will load the script into the the chrome process and any child processes: // chrome code let ppmm = cc["@mozilla.org/parentprocessmessagemanager;1"] .getservice(ci.nsiprocessscriptloader); ppmm.loadprocessscript("chrome://whatever/process-script.js", true); ppmm.addmessagelistener("hello", function(msg) { ... }); the process script's globa...
Chrome-only CSS reference
Mozilla › Gecko › Chrome › CSS
this page lists css properties that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua stylesheets.) note: most of the css properties exposed to the web in general are also usable in chrome stylesheets: see the css documentation for a list of these. -moz-window-draggingthe -moz-window-dragging css property specifies whether a window is draggable or not. ...
... are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua stylesheets.) note: most of the css properties exposed to the web in general are also usable in chrome stylesheets: see the css documentation for a list of these. -moz-window-draggingthe -moz-window-dragging css property specifies whether a window is draggable or not. ...
Getting Started with Chat
d etiquette once you have your client set up (see software below) and are connected, there are some basic rules you should follow to ensure the most enjoyable and productive experience: as with all mozilla forums and events, agreeing to our community participation guidelines is a requirement for participation. try to keep messages as concise as possible. if you have something long to post, a code snippet for example, use paste.mozilla.org and paste the generated url in irc instead. when addressing someone directly, try to use name: message format. for example, "ashughes: good morning!" every channel has its own topic. try to keep your messages within that subject matter. for example, do not talk about thunderbird issues in #firefox. mozilla's channels are most active between 9am and 7p...
...ect to a server and join a particular set of channels when you start the client. the following are some other options available to you: windows mac linux colloquy ● irssi ● ● ●* xchat ● ○ ● key: ● — binary or executable program available ○ — only available by downloading and compiling source code ●* — binary or executable may be available. if not, you'll have to download source code and compile. note: for a complete list of irc clients go here. web-based clients there are also a few web-based clients which allow connecting to irc by clicking on irc:// links. one of the simplest web-based clients is mibbit, another is irccloud. these operate very much in the same way as the previ...
Hacking with Bonsai
also, with as many as 100 engineers, it was very difficult to determine what happened in the tree that caused the instability. bonsai was created to solve these problems. the process everyone who checks into the tree, joins a group called "the hook" at 8:00 am pst every weekday morning, the source tree is closed. ...
...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 bustages. if you are on the hook, you are findable. you are either at your desk, or pageable, checking e-mail constantly, or on irc so that you can be found immediately and can respond to any problems in your code. helpful attitudes the build team are your friends. they are doing a not-so-fun job, so treat them with respect. people are "on the hook" collectively. don't just blame a certain team and walk away. ...
How Mozilla determines MIME Types
s are 9-13, 27, and 31-255. when encountering a non-text byte, the helper app dialog will be shown, showing the mime type corresponding to the extension of the file. also, for images loaded via <img src>, mozilla's image library will do content sniffing (never extension sniffing) to find out the real type of the image. if the server did not send a content-type header, mozilla uses the unknown decoder to find a mime type. file uris for file: uris, mozilla will ask the externalhelperappservice for a mime type. ftp like http uris without a mime type, ftp uris go through the unknown decoder. unknown decoder located at netwerk/streamconv/converters/nsunknowndecoder.cpp, the interesting part starts at line 287, the ssnifferentries array together with the determinecontenttype function. it doe...
...ew bytes of the file) is searched for embedded nulls; if none are found, text/plain will be used, otherwise application/octet-stream. externalhelperappservice (located at uriloader/exthandler/nsexternalhelperappservice.cpp) the file->mime type mapping works like this: on beos, the operating system is asked for the type of the file (not quite yet, bug 217723) on macos, the type and creator code will be used to lookup the type of the file from the os a hardcoded list of extensions is checked (containing currently 13 entries, nsexternalhelperappservice.cpp line 463 (this is done for speed – it is faster to find data in the hardcoded list than asking the os or looking in preferences) if the extension is not listed there, it becomes interesting. firstly, the operating system is asked fo...
How to Report a Hung Firefox
cle is intended for developers and technically-knowledgeable users. if that's not you, or you just want to fix a firefox hang without reporting it, see firefox hangs or is not responding - how to fix. is your firefox not responding? or are you regularly seeing the "firefox is running but is not responding..." dialog? this usually means that something in firefox is hung. this may be because of a code error within firefox itself, such as a deadlock or infinite loop, or it may be caused by 3rd-party software such as a firefox extension, antivirus software, or even malware or a virus on your computer. what information to include in a bug report as usual, following bug writing guidelines will make your report much more likely to lead to a fix in firefox. check the cpu usage of the firefox pr...
...ility team to debug these kinds of hangs is to make the hung firefox crash and submit a crash report. then file a bug report with the crash report id. the steps to induce a crash are slightly different on each platform: windows on windows, the stability team has written a utility which will inject a crash into firefox which will trigger the crash reporter: download crashfirefox.exe here (source code). running this tool will search for firefox.exe and inject crashing code into it. the tool also has command-line options to kill processes with other names or by process id. run the crashfirefox.exe tool. the firefox crash report ui should appear. please check the box to send the crash report to mozilla start firefox. type "about:crashes" in the url bar and click on the top listing. the cras...
IPDL Best Practices
tlives it (case in point: reference-counted). is there any chance that an ipdl function could be called after the protocol itself has been destroyed, or before it has been created? don't let it happen - that is a guaranteed crash right there. use a flag and the generated actordestroy function to control when ipdl functions can be called; see phttpchannelparent/child for an example. ...
...hat an ipdl function could be called after the protocol itself has been destroyed, or before it has been created? don't let it happen - that is a guaranteed crash right there. use a flag and the generated actordestroy function to control when ipdl functions can be called; see phttpchannelparent/child for an example. ...
Extending a Protocol
ionship. without this, we can't send messages. anyway, let's put the above into practice by creating our custom protocol: pecho.ipdl. custom protocol - pecho.ipdl this next part requires us to both specify the protocol and actually implement everything in c++. it's quite involved and, unfortunately, all steps need to be done before we can successfully recompile. we will try to compile our code as we go, noting what we need to do along the way. to be sure, ipdl looks like a crazy mix of webidl, c++ header files, and es6. the syntax should hopefully be fairly obvious though. unfortunately, it's not really fully documented anywhere - and the ipdl parser gets easily confused (hence us excluding comments below). creating the protocol pecho.ipdl let's start by saving the following f...
... // end of namespace dom } // end of namespace mozilla and add the echochild.h to dom/ipc/moz.build, as part of the exports.mozilla.dom array. again, remember that this must be in alphabetical order! compiling this will now complain: "fatal error: 'mozilla/dom/echoparent.h' file not found", so let's define echoparent.h. defining echoparent.h like before, create ./dom/ipc/echoparent.h, and code it as follows - the inline comments describe what's going on. note the recvecho(), we finally get to define where a message is received, yay!: #ifndef mozilla_dom_echoparent_h #define mozilla_dom_echoparent_h #include "mozilla/dom/pechoparent.h" namespace mozilla { namespace dom { class echoparent final : public pechoparent { friend class pechoparent; ns_inline_decl_threadsafe_refcountin...
Implementing Download Resuming
ains unchanged. this can also be used to check whether the download is resumable: if it is not (e.g. the server is not using http 1.1), then accessing this attribute will throw an ns_error_not_resumable exception. if the download gets interrupted, necko will call the stream listener's onstoprequest method with a failure status. (todo: document what webbrowserpersist/exthandler do). the front-end code can then notify the user of this, and offer to resume the download. resuming a download in order to resume a download, you should create a channel as usual (using nsiioservice). then, you can check if it implements nsiresumablechannel. if it does not, the protocol does not support resuming. otherwise, call resumeat with the desired start position, and the previously stored entity id. (it is po...
...before calling asyncopen). note: in versions of firefox prior to 3.0 alpha 7, nsiwebbrowserpersist cannot append to existing files (as opposed to overwriting them), and is therefore not usable for this task (see bug 129921). detecting when a file changed if the file changed (that is, the entity id does not match), then necko will notify the stream listener with an ns_error_entity_changed error code. the front-end may want to offer the user to get the new file from scratch in such a case. resuming not supported in some cases, it's not possible to detect whether the server supports resuming until the user actually tries to resume. in such a case, the stream listener will get an ns_error_not_resumable status. here, too, the front-end may want to offer downloading the entire file from scratch...
AsyncShutdown.jsm
or that the phase has completed and the blocker has already been resolved. examples asyncshutdown.profilebeforechange.addblocker("module: just a promise", promise); // profilebeforechange will not complete until // promise is resolved or rejected asyncshutdown.profilebeforechange.addblocker("module: a callback", function condition() { // ... ...
...filebeforechange.addblocker("module: a callback", function condition() { // ... // execute this code during profilebeforechange return promise; // profilebeforechange will not complete until promise // is resolved or rejected }); asyncshutdown.profilebeforechange.addblocker("module: trivial callback", function condition() { // ... // execute this code during profilebeforechange // no specific guarantee about completion of profilebeforechange }); if the promise returned by condition is not resolved/rejected within one minute, the process will crash to avoid blocking system shutdown, preventing the user from restarting firefox or burning through battery. this is by design. it is the caller's responsibility to ensure that the promise is ...
DeferredTask.jsm
firefox 28 note interface was changed in firefox 28, and old methods were removed. the deferredtask.jsm javascript code module offers utility routines for a task that will run after a delay. multiple attempts to run the same task before the delay will be coalesced. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/deferredtask.jsm"); use this, for instance, if you write data to a file and you expect that you may have to rewrite data very soon afterwards. with deferredtask, the task is delayed by a few milliseconds and, should a new change to the data occur during this period, only the final version of the data is actually written; a further grace delay is added to take into account other cha...
... void cancel();obsolete since gecko 28 void arm(); void disarm(); promise finalize(); attributes isarmed boolean indicates whether the task is currently requested to start again later, regardless of whether it is currently running. isrunning boolean indicates whether the task is currently running. this is always true when read from code inside the task function, but can also be true when read from external code, in case the task is an asynchronous generator function. methods ispending obsolete since gecko 28 check the current task state. bool ispending(); return value returns true if pending, false otherwise. start obsolete since gecko 28 start (or postpone) task. void start(); flush obsolete since gecko 28 ...
FxAccountsProfileClient.jsm
created fxaccountsprofileclient object implementing the methods described in this article. methods fetchprofile() fetches firefox accounts profile information. parameters none return value promise resolves: object - successful response from the '/profile' endpoint. rejects: fxaccountsprofileclienterror - profile client error. examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object. fxaccountsprofileclienterror attributes name string name ...
...rurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object. fxaccountsprofileclienterror attributes name string name of the error fxaccountsprofileclienterror code number status code of the request errno number error number error string error description message string error message ...
Http.jsm
http.jsm http.jsm provides httprequest - a wrapper for xmlhttprequest that provides convenient and simplified api for dealing with http requests. httprequest supports the following parameters: name meaning headers an array of headers postdata this can be: a string: send it as is an array of parameters: encode as form values null/undefined: no post data. method get, post or put (this is automatically set if postdata exists). onload a function handle to call when the load is complete, it takes two parameters: the responsetext and the xhr object. onerror a function handle to call when an error occurs, it takes three parameters: the error, the responsetext and the xhr...
...e post requests. the data can be specified via postdata option. postdata can be of 2 different types: a string or an array of parameters. when null/undefined is given, no post data will be attached. if a string is given the data will be appended to the request as is. in case an array of parameters is given, it will be treated as an array of key-value pairs. the elements of the array will be url-encoded and "application/x-www-form-urlencoded; charset=utf-8" will be enforced as the content type. http.jsm only forces the content type if the post data is an array, and it serializes it automatically. if the provided postdata is a string, the content type isn't touched. in this case, the content type may be set through the headers parameter. additional xhr configuration it is possible to modify th...
JavaScript OS.Constants
getservice(components.interfaces.nsiosfileconstantsservice). init(); from a chrome worker no initialization is required. module os.constants is always available for chrome workers. ...
...workers. os.constants.sys constants related to system configuration. name the name of the operating system (e.g. "darwin"). debug set to true on debug build configurations, non-existent otherwise. os.constants.path paths of well-known files and directories. libxul the path to the file containing libxul. useful, for instance, to access the platform code from javascript in conjunction with js-ctypes. profiledir the path to the current profile. homedir the path to the user's home directory. winappdatadir the path to the user's roaming application data directory. winlocalappdatadir the path to the user's local application data directory. winstartmenuprogsdir the path to the programs subdir...
Promise.jsm
the promise.jsm javascript code module implements the promises/a+ proposal as known in april 2013. this module was used before dom promises were made globally available in gecko 29. its usage is not suggested for new code. if you just need a promise, consider using a dom promise instead. if you need a deferred, because you want to create a promise and manually resolve or reject it, consider using promiseutils.jsm instead. ...
...al as known in april 2013. this module was used before dom promises were made globally available in gecko 29. its usage is not suggested for new code. if you just need a promise, consider using a dom promise instead. if you need a deferred, because you want to create a promise and manually resolve or reject it, consider using promiseutils.jsm instead. ...
SourceMap.jsm
the original line and column positions. source: the original source file (relative to the sourceroot). name: an optional original token name for this mapping. sourcemapgenerator.prototype.tostring() renders the source map being generated to a string. sourcenode sourcenodes provide a way to abstract over interpolating and/or concatenating snippets of generated javascript source code, while maintaining the line and column information associated between those snippets and the original source code. this is useful as the final intermediate representation a compiler might use before outputting the generated js and source map. new sourcenode(line, column, source[, chunk]) line: the original line number associated with this source node, or null if it isn't associated with an...
...al line. column: the original column number associated with this source node, or null if it isn't associated with an original column. source: the original source's filename. chunk: optional. is immediately passed to sourcenode.prototype.add, see below. sourcenode.prototype.add(chunk) add a chunk of generated js to this source node. chunk: a string snippet of generated js code, another instance of sourcenode, or an array where each member is one of those things. sourcenode.prototype.prepend(chunk) prepend a chunk of generated js to this source node. chunk: a string snippet of generated js code, another instance of sourcenode, or an array where each member is one of those things. sourcenode.prototype.walk(fn) walk over the tree of js snippets in this node and i...
openLocationLastURL.jsm
this object lets you fetch and change the url that is placed in the "open location" dialog box when it opens. ...
...this object lets you fetch and change the url that is placed in the "open location" dialog box when it opens. ...
Mozilla Content Localized in Your Language
tent here should be what you and your localization team have decided, together, to follow when localizing mozilla products and web sites. you are free to add, edit, remove, and localize everything in this section according to how the localization team for your language agrees. all we ask is that you name this page according to this example, "mozilla content in spanish (es-mx)" and add your locale code tag at the bottom. enjoy developing your style guide! your language's style guide abbreviations how are abbreviations expressed in your language? numerals and metrics how are numerals and metrics expressed in your language? formal and informal forms, and separators (, or .) date format what are the date formats for weeks and months are expressed in the following forms: 1)fully spelled ou...
...mphasis be made in your language? character styles how are bold, italics, underlines, etc. used to express certain concepts in your language? if these are not applicable styles, what are some of the corresponding ways to express, emphasis or highlight some of the texts. address format what is the format in your language? ex: most asian countries start from big to small: [country] [postal code][state/province][city][district][street number and name][building and suite numbers][addressee] countries of european languages start from small to big: [addressee][street number and name][building and suite numbers][district][city][state/province][postal code][country] name convention what are the order of family name and given name in your language. here is the guideline on the naming conve...
Localizing XLIFF files for iOS
is tutorial will walk you through the steps you need to take to translation strings within an xliff file. string repository for firefox on ios the firefox-ios.xliff file is located in svn. decide where on your local computer you will store your copy of the github repo and navigate there in your terminal. enter the command git clone https://github.com/mozilla-l10n/firefoxios-l10n/your-locale-code/ you should now see the firefox-ios project in your selected directoy with the firefox-ios.xliff file in it. translating the xliff file open the firefox-ios.xliff file in your favorite text editor. in the <file> tag, add the target-language attribute with your locale code as the value (e.g., target-language="xx-xx"). be aware that there may be many <file> tags within one xliff document. ea...
... strings are located within <trans-unit> tags. source english strings are contained in <source> child tags. ...
Localizing extension metadata on addons.mozilla.org
ated by native speakers. create an account and then, using the “basic open-ended question” template, follow the instructions to upload the text of your amo page. on the properties page you can specify the location of the worker in order to restrict to people living in the country where the language is spoken. the reward is up to you, but $5-10 per translation seems to work well. ...
...ended question” template, follow the instructions to upload the text of your amo page. on the properties page you can specify the location of the worker in order to restrict to people living in the country where the language is spoken. the reward is up to you, but $5-10 per translation seems to work well. localization codes amo offers 33 localizations, including english. ...
Patching a Localization
ites wiki page. if you do not have these tools, take a few steps back, grab a cookie (because, let's face it, you deserve it for all of your work), and visit the l10n prerequisites page. there you'll learn what tools you need, where to find them, and how to install them. get the source first, you need to get the source for the localization in question using its two or three character iso language code. for our example, i'll use gl (galician). whenever you see gl in blue text, replace it with the locale code for your language. next thing you need to know is which localization version you want to patch. all of our localizations work on the aurora branch. the repository for this version is releases/l10n/mozilla-aurora. for more information about branches see l10n:branches. now let's get a little ...
...example, create a directory like localization-workdir (in this example it is located in your home directory): mkdir ~/localization-workdir navigate to the directory you just created. cd ~/localization-workdir clone the localization repository for your locale and for the version you want to patch: hg clone http://hg.mozilla.org/releases/l10n/mozilla-aurora/gl now that you have the code and your working directory, edit the dtd and properties files to make your necessary changes. creating a l10n patch you've made your changes, now create your patch. navigate to your working localization directory. cd ~/localization-workdir/gl create a patch (also known as a diff) using the diff command. hg diff this command creates a patch and lists your modifications through displayin...
Localization formats
ily edited in a text editor with this setup, a localizer is given a "[something].lang" file containing all the strings needing localization. that file will have the following structure: ;getting started débuter avec firefox the english content is designated by the semi-colon and the localizer provides the translation underneath. that content is placed into an array that is used by the php code later. $array["getting started"] = "débuter avec firefox" the php code searches the array and returns the translation that is associated with the english term used by the web developer. see the example below. <h1><?php echo ___("getting started")?></h1> function ___($str) { return $array[$str]; } advantage to .lang simple work-flow allowing the web developer to place the file in...
... read more about gettext on wikipedia and on mdc. wiki blogging, documentat...
Setting up the infrastructure
ract all english strings from your application's directories specified in source_dirs, merge the resulting template (*.pot) file with the existing (already containing translations) messages.po files for each locale (if they exist) and merge the new messages.po files to messages.mo files. by default the script looks for gettext calls in *thtml or *.php files, so you may need to adjust that to your code. compile-mo.sh will only compile all locales' messages.po files to message.mo files. this is useful when a localizer submits a new version of the messages.po file. on the staging server you can also choose to set up a cronjob that will run compile-mo.sh every n minutes. this way the localizers will be able to preview their changes almost in real-time. stats-po.sh will give you a bird's-eye ...
...u a bird's-eye view on the statistics of translated, fuzzy and missing strings for each locale. create en-us locale (locale/lc_messages/) in the locale folder. create an empty filed named messages.po in the locale/lc_messages folder. create new locales by repeating steps 4 and 5 for each of them. review the english content following the web content localizability guidelines. review your code following the web applications localizability guidelines. run extract-po.sh. restart apache to reload gettext files (necessary for any text changes). merge the l10n branch back to main trunk (if the l10n branch was created in step 1). copy files over to svn. set up the staging server. set up a cronjob to svn up every n minutes. set up a cronjob to run compile-mo.sh every m minutes. ...
Mozilla Framework Based on Templates (MFBT)
the mozilla framework based on templates ("mfbt") is the central repository for macros, functions, and data structures used throughout mozilla code, including in the javascript engine. its code resides in the mfbt/ source directory, but headers within it should be included using paths like "mozilla/standardinteger.h". it is fairly new, so its functionality is currently sparse. feel free to file bugs to add new functionality to it, or to move existing functionality into it, as needed. mfbt code goes to some length to document all its interfaces in comments, including examples when possible. it also attempts to define its functionality in well-named files, such that simply skimming the contents of mfbt/ will quickly suggest the relevant header to examine. therefore this document primari...
...pile-time assertions. guardobjects.h provides macros which can be used to annotate an raii-style guard class, so that any attempt to create an unnamed temporary for it will assert. (an unnamed temporary lives for a shorter period of time than the scope where it's found, so it usually isn't what was desired.) data structures linkedlist.h implements a type-safe doubly-linked list class. most new code should use this rather than prclist. rangedptr.h implements rangedptr, a smart pointer template whose value may be manipulated only within a range specified at construction time, and which may be dereferenced only at valid locations in that range. this pointer is a useful way to expose access to values within an array. refptr.h implements various smart pointer templates to simplify reference c...
Extras
mi> <mi>a</mi> </msub> <mo>&applyfunction;</mo> <mi>x</mi> </mrow> <mo>=</mo> <mfrac> <mrow> <mi title="natural log">ln</mi> <mo>&applyfunction;</mo> <mi>x</mi> </mrow> <mrow> <mi title="natural log">ln</mi> <mo>&applyfunction;</mo> <mi>a</mi> </mrow> </mfrac> </mrow> </math> rather than repeating the instructions, some css might be used to provide a visual cue. ...
...mrow> <mo>=</mo> <mfrac> <mrow> <mi title="natural log">ln</mi> <mo>&applyfunction;</mo> <mi>x</mi> </mrow> <mrow> <mi title="natural log">ln</mi> <mo>&applyfunction;</mo> <mi>a</mi> </mrow> </mfrac> </mrow> </math> rather than repeating the instructions, some css might be used to provide a visual cue. ...
Mozilla Style System
the style system is the module of mozilla's code responsible for the loading and parsing of css style sheets, and the computation of computed values for all css properties. the handling of those computed values is the responsibility of other parts of the code. architecture the style system is split in half rather neatly. in one half (the backend) are the sources of specified style data, and in the other half (the frontend) is the code that turns the specified values into computed values. the barrier between these two halves consists of three abstract interfaces, plus some smaller structures associated with some methods on each: nsistylesheet nsistylesheet represents what one would think of as a style sheet: the in-memory representation of a css file or other source of style data...
... second of these rules is the key to many of the performance and memory-use optimizations in the style system. most callers who interact with the style system do so using the style structs. the style context has a getter for each struct, and nsiframe, which represents the concept of a css box (or rendering object), also has getters that forward to the frame's style context. thus, typical calling code looks like this: if (aframe->getstyledisplay()->mopacity < 1.0f) return pr_true; or like this: const nsstyleposition *stylepos = aframe->getstyleposition(); if (stylepos->mwidth.getunit() == estyleunit_coord) { nscoord w = stylepos->mwidth.getcoordvalue(); ... } else if (stylepos->mwidth.getunit() == estyleunit_percent) { ... rule tree style data computation css style shee...
mozilla::MutexAutoLock
a::mutex safer and easier. to use mozilla::mutexautolock, declare and initialize it with a reference to an mozilla::mutex. the mozilla::mutexautolock constructor will lock() the underlying mozilla::mutex automatically. when the mozilla::mutexautolock goes out of scope, its destructor will unlock() the underlying mozilla::mutex. because of mozilla::mutexautounlock, the rule for determining if your code owns the mutex underlying the mutexautolock is slightly more complicated than that for monitorautoenter. this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautolock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed to own the underlying mozilla::mutex. constructors mutexautolo...
...utoenter. this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautolock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed to own the underlying mozilla::mutex. constructors mutexautolock( in mozilla::mutex& lock; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::mutex. methods none. see also mozilla::mutex mozilla::mutexautounlock ...
mozilla::MutexAutoUnlock
afer and easier. to use mozilla::mutexautounlock, declare and initialize it with a reference to a locked mozilla::mutex. the mozilla::mutexautounlock constructor will unlock() the underlying mozilla::mutex automatically. when the mozilla::mutexautounlock goes out of scope, its destructor will lock() the underlying mozilla::mutex. because of mozilla::mutexautolock, the rule for determining if your code does not own the mutex underlying the mutexautounlock is slightly more complicated than that for monitorautoenter. this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautounlock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed not to own the underlying mozilla::mutex. construc...
.... this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply. important: when a mozilla::mutexautounlock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed not to own the underlying mozilla::mutex. constructors mutexautounlock( in mozilla::mutex& lock; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::mutex. methods none. see also mozilla::mutex mozilla::mutexautolock ...
DMD
ing a profile of the live heap blocks at that point in time. this is good for understanding how memory is used at an interesting point in time, such as peak memory usage. "cumulative" mode. in this mode, dmd tracks both the past and current contents of the heap. you can dump that information to file, giving a profile of the heap usage for the entire session. this is good for finding parts of the code that cause high heap churn, e.g. by allocating many short-lived allocations. "heap scanning" mode. this mode is like live mode, but it also records the contents of every live block in the log. this can be used to investigate leaks by figuring out which objects might be holding references to other objects. building and running nightly firefox the easiest way to use dmd is with the normal nigh...
... run under gdb. trigger there are three ways to trigger a dmd snapshot. visit about:memory and click the dmd button (depending on how old your build is, it might be labelled "save" or "analyze reports" or "dmd"). the button won't be present in non-dmd builds, and will be grayed out in dmd builds if dmd isn't enabled at start-up. if you wish to trigger dmd dumps from within c++ or javascript code, you can use nsimemoryinfodumper.dumpmemorytotempdir. for example, from javascript code you can do the following. const cc = components.classes; let mydumper = cc["@mozilla.org/memory-info-dumper;1"] .getservice(ci.nsimemoryinfodumper); mydumper.dumpmemoryinfototempdir(identifier, anonymize, minimize); this will dump memory reports and dmd output to the temporary directory. ...
GC and CC logs
ironment variable moz_cc_log_thread to main to only log main thread ccs, or to worker to only log worker ccs. the default value is all, which will log all ccs. to get cycle collector logs on try server, set moz_cc_log_directory to moz_upload_dir, then set the other variables appropriately to generate cc logs. ...
... to find out why an object is being kept alive, the relevant scripts are find_roots.py and parse_cc_graph.py (which is called by find_roots.py). ...
Power profiling overview
t 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 often don't provide much insight into why the problem is occurring, which part of the code is at fault, or how it can be fixed. nonetheless, they can still help improve understanding of a problem by using differential profiling. compare browsers to see if firefox is doing better or worse than another browser on a particular workload. compare different versions of firefox to see if firefox has improved or worsened over time on a particular workload. this can identify specific change...
...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.) source-level instrumentation, such as tim...
Refcount tracing and balancing
matched to be eliminated from the tree, so it makes it much easier to debug reference count leaks of objects that have a large amount of reference counting traffic. xpcom_mem_alloc_log for platforms that don't have stack-crawl support, xpcom supports logging at the call site to addref/release using the usual cpp __file__ and __line__ number macro expansion hackery. this results in slower code, but at least you get some data about where the leaks might be occurring from. you must also set one or two additional environment variables, xpcom_mem_log_classes and xpcom_mem_log_objects, to reduce the set of objects being logged, in order to improve performance to something vaguely tolerable. xpcom_mem_log_classes this variable should contain a comma-separated list of names which wil...
...es using an xpcom_mem_refcnt_log and an xpcom_mem_comptr_log that were collected at the same time. for more details, see the old documentation (which should probably be incorporated here). this is best used with --ignore-balanced play mah jongg. an unbalanced tree is not necessarily an evil thing. more likely, it indicates that one addref() is cancelled by another release() somewhere else in the code. so the game is to try to match them with one another. exclude functions. to aid in this process, you can create an "excludes file", that lists the name of functions that you want to exclude from the tree building process (presumably because you've matched them). make-tree.pl has an option --exclude [file], where [file] is a newline-separated list of function names that will be excluded from con...
TraceMalloc
tracemalloc captures stack traces of all malloc, calloc , realloc, and free calls (this currently covers all operator new and delete calls in mozilla, too). to enable tracemalloc in your build, configure with --enable-trace-malloc. the built mozilla application will support the following additional command-line options: --trace-malloc filename the application will log allocation and deallocation events with stack traces in a binary format to the given file. ...
...e-malloc/bloatblame.cpp) can be used to process filename. try running with the unified output format option, -u. the output is a large html file that hyperlinks ancestor and descendent libraries, classes, and functions that call into one another, attributing malloc blame up and down each graph. bloatblame accumulates allocation counts and ignores free calls. if you run with --trace-malloc -, your code can call ns_tracemallocdumpallocations(pathname) at opportune times, and a human-readable listing of the current heap, including stack traces for every allocation, will be written to pathname. this file can be post-processed by tools in mozilla/tools/trace-malloc as follows: histogram.pl, which produces a type histogram that can be diffed with histogram-diff.sh to produce output that looks like...
A brief guide to Mozilla preferences
loading. the only exception to this is user.js . on application launch, several preferences files are loaded. they are: default preference files firefox ships default preferences in several files, all in the application directory: greprefs.js - preferences shared by all applications using the mozilla platform services/common/services-common.js - preferences for some shared services code, this should arguably be included in some other file defaults/pref/services-sync.js - default preferences for firefox sync, also oddly misplaced browser/app/profile/channel-prefs.js - a file indicating the user's update channel. this is kept separate from other preferences because it can affect how updates are applied. browser/app/profile/firefox.js - defaults specific to firefox browser/...
...() - these preference will be written whenever the preference has a user value even when it is the same as the default. modifying preferences advanced users can set named preferences via the advanced preferences editor, by typing about:config in the location bar. this ui is not recommended for most users. programmatic changes to preferences can be made using the preferences.jsm module from js code, or the mozilla::preferences static class methods from c++ code. changing defaults a systems administrator can modify the default preferences in two ways: the administrator may add an all-companyname.js preference file (install_directory/browser/defaults/preferences/all-companyname.js). this will be parsed last during the preference loading process. the administrator may alternatively p...
javascript.options.showInConsole
true (default) errors and warnings from both chrome and content are shown in the error console. ...
... true (default) errors and warnings from both chrome and content are shown in the error console. ...
Preferences
the xul school tutorial chapter on preferences. mozilla preference reference a reference guide to all mozilla preferences; currently a work in progress. a brief guide to mozilla preferences an introductory guide to where preferences are stored and other useful information about the core preference system. using preferences from application code firefox 6 introduced static functions for accessing preferences efficiently from within application code. this api is not available for add-ons, but if you're working on a gecko application, this api is the preferred way to access preferences. mozilla networking preferences a guide to key networking-related preferences. mozilla preferences for uber-geeks ...
...ilable for add-ons, but if you're working on a gecko application, this api is the preferred way to access preferences. mozilla networking preferences a guide to key networking-related preferences. mozilla preferences for uber-geeks a guide to preferences that only truly elite geeks should play with. examples code snippets preference-related code snippets. adding preferences to an extension how to add preferences to an existing extension. related topics xul, javascript, xpcom, extensions, developing mozilla ...
Crash reporting
if you want to find a specific crash that you submitted, you first need to find the crash id that the server has assigned your crash. ...
...ng data in either sql summary or using mapreduce on the storage cluster. ...
Leak And Bloat Tests
provide reasonable coverage for the normal activities that a user performs. ...
... with your standard mozconfig file, but with the following options set: ac_add_options --enable-debug ac_add_options --enable-trace-malloc running the tests in your <objdir> run the following command: make mailbloat this will run the tests and produce some result files. see debugging memory leaks for more information on what to do with this data. todo: add more information on processing output. ...
MailNews automated testing
rent cases. this page and its sub-pages describe (and link to) the available test mechanisms within mailnews, and provide supporting information for developers and testers. functional testing xpcshell-tests and make check these are core test harnesses to which mailnews adds its own tests. these tests are run against almost every changeset that gets committed to the thunderbird and seamonkey code bases. xpcshell-tests are run in javascript without any chrome present. this makes them especially useful for testing at the component / module level. xpcshell-tests are the quickest tests to run. mailnews provides additional facilities as described on the mailnews automated testing page (see below). "make check" is used to run compiled code tests. these tests can go beyond the limitations of...
...script without any chrome present. this makes them especially useful for testing at the component / module level. xpcshell-tests are the quickest tests to run. mailnews provides additional facilities as described on the mailnews automated testing page (see below). "make check" is used to run compiled code tests. these tests can go beyond the limitations of xpcshell-tests (for example, access c++ code) and other testing options that don't test at the right level. testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using generators. in the long term we would like to lose this extra complexity in favor of the event-loop-spinning style of operation used by mozmi...
About NSPR
perhaps the primary purpose in the gromit environment, was to provide the underpinnings of the java vm, more or less mapping the sys layer that sun defined for the porting of the java vm to various platforms. nspr went beyond that requirement in some areas and since it was also the platform independent layer for most of the servers produced by netscape. it was expected and preferred that existing code be restructured and perhaps even rewritten in order to use the nspr api. it is not a goal to provide a platform for the porting into netscape of externally developed code. at the time of writing the current generation of nspr was known as nspr20. the first generation of nspr was originally conceived just to satisfy the requirements of porting java to various host environments. nspr20, an effort ...
...(the "20" in "nspr20" does not mean "version 2.0" but rather "second generation".) many of the concepts have been reformed, expanded, and matured. today nspr may still be appropriate as the platform dependent layer under java, but its primary application is supporting clients written entirely in c or c++. ...
NSPR's Position On Abrupt Thread Termination
y it knows about. in the natural course of events, these resources will be allocated by a thread, used for some period of time, and then freed as the stack unwinds. in these cases, the presence of the data is recorded only on the stack, known only to the single thread (normally referred to as encapsulated). the problem with abrupt termination is that it can happen at any time, to a thread that is coded correctly to handle both normal and exceptional situations, but will be unable to do so since it will be denied the opportunity to complete execution. it can happen because it called out of its own scope into some lazily implemented library. nspr's answer to this is that there is no abrupt thread termination. all threads must unwind and return from their root function. if they cannot, because of...
...unction that encounters an error be designed such that it first repairs its immediate state, and then reports that error to its caller. if the caller cannot deal with the failure, it must do the same. this process continues until the thread either recovers from the malady or returns from the root function. this is not all that difficult (though having done it a number of times to already existing code, i will admit it isn't much fun either). the implementation of either strategy within the nspr runtime is not difficult. that is not what this memo is about. this is about providing an api that coaxes people to do the right thing in as many ways as possible. the existence of exit() in the unix/c environment is a perfect example of how programmers will employ the most expediant solution available.
I/O Functions
for information about the types most commonly used with the functions described in this chapter, see i/o types. ...
..._layer (prdescidentity)-2 #define pr_nspr_io_layer (prdescidentity)0 pr_invalid_io_layer: an invalid layer identify (for error return). pr_top_io_layer: the identity of the top of the stack. pr_nspr_io_layer: the identity for the layer implemented by nspr. ...
PR_Seek64
seek_end. sets the file pointer to the size of the file plus the value of the offset parameter. returns the function returns one of the following values: if the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file. if the function fails, the file pointer remains unchanged and the function returns -1. ...
...ils, the file pointer remains unchanged and the function returns -1. the error code can then be retrieved with pr_geterror. description this is the idiom for obtaining the current location (expressed as a 64-bit integer) of the file pointer for the file descriptor fd: pr_seek64(fd, 0, pr_seek_cur) if the operating system can handle only a 32-bit file offset, pr_seek64 may fail with the error code pr_file_too_big_error if the offset parameter is out of the range of a 32-bit integer. see also pr_seek ...
Threads
resources and therefore require some management. to synchronize the termination of a thread, you can join it with another thread (see pr_jointhread). joining a thread provides definitive proof that the target thread has terminated and has finished with both the resources to which the thread has access and the resources of the thread itself. for an overview of the nspr threading model and sample code that illustrates its use, see introduction to nspr. for api reference information related to thread synchronization, see locks and condition variables. threading types and constants prthread prthreadtype prthreadscope prthreadstate prthreadpriority prthreadprivatedtor threading functions most of the functions described here accept a pointer to the thread as an argument. nspr does not...
...g, joining, and identifying threads controlling thread priorities interrupting and yielding setting global thread concurrency getting a thread's scope creating, joining, and identifying threads pr_createthread creates a new thread. pr_jointhread blocks the calling thread until a specified thread terminates. pr_getcurrentthread returns the current thread object for the currently running code. pr_attachthread associates a prthread object with an existing native thread. pr_detachthread disassociates a prthread object from a native thread. controlling thread priorities for an overview of the way nspr controls thread priorities, see setting thread priorities. you set a thread's nspr priority when you create it with pr_createthread. after a thread has been created, you can get a...
NSPR API Reference
introduction to nspr nspr naming conventions nspr threads thread scheduling setting thread priorities preempting threads interrupting threads nspr thread synchronization locks and monitors condition variables nspr sample code nspr types calling convention types algebraic types 8-, 16-, and 32-bit integer types signed integers unsigned integers 64-bit integer types floating-point integer type native os integer types miscellaneous types size type pointer difference types boolean types status type for return values threads threading types and constants threading functions creating, joining, and identifying threads controlling thread priorities contr...
...mory functions anonymous shared memory anonymous memory protocol anonymous shared memory functions ipc semaphores ipc semaphore functions thread pools thread pool types thread pool functions random number generator random number generator function hash tables hash tables and type constants hash table functions nspr error handling error type error functions error codes ...
CERT_FindCertByDERCert
find a certificate in the database that matches a der-encoded certificate. syntax #include <cert.h> certcertificate *cert_findcertbydercert( certcertdbhandle *handle, secitem *dercert ); parameters handle in pointer to a certcertdbhandle representing the certificate database to look in dercert in pointer to an secitem whose type must be sidercertbuffer and whose data contains a der-encoded certificate description this function looks in the ?nsscryptocontext? and the ?nsstrustdomain? to find the certificate that matches the der-encoded certificate. a match is found when the issuer and serial number of the der-encoded certificate are found on a certificate in the certificate database. returns a pointer to a certcertificate representing the certi...
...te are found on a certificate in the certificate database. returns a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found. the certificate is a shallow copy, use cert_destroycertificate to decrement the reference count on the certificate instance. see also occurrences of cert_findcertbydercert in the current nss source code (generated by lxr). ...
Deprecated SSL functions
he deprecated functions are not supported by the new ssl shared libraries. applications that want to use the ssl shared libraries must convert to calling the new replacement functions listed below. each function name is linked to its entry in the old ssl reference. ...
.... applications that want to use the ssl shared libraries must convert to calling the new replacement functions listed below. each function name is linked to its entry in the old ssl reference. the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references. ...
HTTP delegation
expected to remain valid until explicitly destroyed (sec_httpserver_freesessionfcn). should the application be unable to keep a physical connection alive all the time, the application is expected to create new connections automatically. nss may choose to repeatedly call a "network connection keep alive" function (sec_httpserver_keepalivesessionfcn) on the server session object, giving application code a chance to do whatever is required. for each individual http request, nss will request the creation of a "http request object" (sec_httprequest_createfcn). no full uri is provided as a parameter. instead, the parameters are a server session object (that carries host and port information already) and the request path. in our example the path is "/cgi-bin/ocsp-responder". (when issueing get reques...
...ce nss is finished providing all details, it will request to initiate the actual network communication (sec_httprequest_trysendandreceivefcn). the application should try to reuse existing network connections associated with the server session object. once the http response has been obtained from the http server, the function will provide the results in its "out parameters". please read the source code documentation to learn how to use this api synchronously or asynchronously. now that we have explained the interaction between nss, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. make sure you have completed the nss initialization before you attempt to register the callbacks. look at sec_httpclientfcn, which is ...
HTTP delegation
expected to remain valid until explicitly destroyed (sec_httpserver_freesessionfcn). should the application be unable to keep a physical connection alive all the time, the application is expected to create new connections automatically. nss may choose to repeatedly call a "network connection keep alive" function (sec_httpserver_keepalivesessionfcn) on the server session object, giving application code a chance to do whatever is required. for each individual http request, nss will request the creation of a "http request object" (sec_httprequest_createfcn). no full uri is provided as a parameter. instead, the parameters are a server session object (that carries host and port information already) and the request path. in our example the path is "/cgi-bin/ocsp-responder". (when issuing get request...
...ce nss is finished providing all details, it will request to initiate the actual network communication (sec_httprequest_trysendandreceivefcn). the application should try to reuse existing network connections associated with the server session object. once the http response has been obtained from the http server, the function will provide the results in its "out parameters". please read the source code documentation to learn how to use this api synchronously or asynchronously. now that we have explained the interaction between nss, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. make sure you have completed the nss initialization before you attempt to register the callbacks. look at sec_httpclientfcn, which is ...
4.3 Release Notes
igdir parameter for crypomanager.initialize method or using the nss environment variable nss_default_db_type. ...
...s tag for the jss 4.3 release is jss_4_3_rtm. source tarballs are available from https://archive.mozilla.org/pub/security/jss/releases/jss_4_3_rtm/src/jss-4.3.tar.bz2 binary releases are no longer available on mozilla. jss is a jni library we provide the jss4.jar but expect you to build the jss's matching jni shared library. we provide the jss4.jar in case you do not want to obtain your own jce code signing certificate. jss is a jce provider and therefore the jss4.jar must be signed. https://archive.mozilla.org/pub/security/jss/releases/jss_4_3_rtm/ documentation documentation for jss 4.3 is available as follows: build instructions for jss 4.3 javadoc [online] [zipped] read the instructions on using jss. source may be viewed with a browser (via the mxr tool) at http://mxr.mozilla.
NSS Memory allocation
nss makes extensive use of nspr's plarenapools for memory allocation. each block of memory allocated in a plarenapool is called a plarena. when a plarenapool is freed, all the arenas in that pool are put on an arena free list. when nss attempts to allocate more memory for an arena pool, the plarenapool code attempts to use an arena from its free list, and only gets a new arena from the heap if there are no arenas in the free list that are large enough to satisfy the request. there are two consequences of the use of plarenapools that affect leak analysis. they are: 1. at the end of execution of a program, all the arenas in the free list will appear to have been leaked. this makes it difficult to tell arenas that are truly leaked from those that are merely in the free list. there is a fu...
...of the oldest allocation of that arena. but leak analysis tools only record the allocation of memory from the heap, not memory from the arena free list, so they will always show the first allocation (from the heap) and not the most recent allocation (from the arena free list). consequently, when the arena free list is in use, the allocation call stacks shown will typically not be the stack of the code that most recently allocated that arena, but rather will be the stack of the code that first allocated that arena from the heap, and then placed it on the free list. to solve that problem, it is generally necessary to disable the arena free list, so that arenas are actually freed back to the heap each time they are freed, and are allocated afresh from the heap each time they are allocated. this m...
NSS_3.12.2_release_notes.html
smartcard bug 447563: modutil -add prints no error explanation on failure bug 448431: pk11_createmergelog() declaration causes gcc warning when compiling with -wstrict-prototypes bug 449334: pk12util has duplicate options letters bug 449725: signver is still using static libraries. ...
... flags needed when libnss3 was linked with libsoftokn3 bug 454961: fix the implementation and use of pr_fgets in signtool bug 455348: change hyphens to underscores in debug_$(shell whoami). bug 455424: nssilckt.h defines the enumeration constant 'lock' bug 456036: stubs for deprecated functions in lib/certdb/stanpcertdb.c should set the pr_not_implemented_error error. bug 456854: cert_decodecertpackage does not set nspr error code upon error bug 457980: hundreds of kilobytes of useless strings in libpkix bug 457984: enable pkcs11 module logging in optimized builds bug 458905: memory leaks in pkix bridge certificates. bug 459231: memory leak in cert fetching - aia extension. bug 459248: support intel aes extensions. bug 459359: forwardbuilderstate object is leaked when aia...
NSS 3.14.2 release notes
2 should be used with nspr 4.9.5 or newer. the release is available for download from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_2_rtm/src/ for the primary nss documentation pages please visit /docs/nss new in nss 3.14.2 nss will now make use of the intel aes-ni and avx instruction sets for hardware-accelerated aes-gcm on 64-bit linux systems. note: the new assembly code requires gnu as version 2.19 or newer. on red hat enterprise linux 5.x systems, install the binutils220 package and add /usr/libexec/binutils220 to the beginning of your path environment variable. initial manual pages for some nss command line tools have been added. they are still under review, and contributions are welcome. the documentation is in the docbook format and can be rendered as html...
...useonlytrustanchors in secoidt.h sec_oid_ms_ext_key_usage_ctl_signing notable changes in nss 3.14.2 bug 805604 - support for aes-ni and avx accelerated aes-gcm was contributed by shay gueron of intel. if compiled on linux systems in 64-bit mode, nss will include runtime detection to check if the platform supports aes-ni and pclmulqdq. if so, nss uses the optimized code path, reducing the cpu cycles per byte to 1/20 of what was required before the patch (https://bugzilla.mozilla.org/show_bug.cgi?id=805604 and https://crypto.stanford.edu/realworldcrypto/slides/gueron.pdf). support for other platforms, such as windows, will follow in a future nss release. (https://bugzilla.mozilla.org/show_bug.cgi?id=540986) sqlite has been updated to 3.7.15. note: please apply ...
NSS 3.15 release notes
o return when clients send the status_request extension. in ocsp.h cert_postocsprequest - primarily intended for testing, permits the sending and receiving of raw ocsp request/responses. in secpkcs7.h sec_pkcs7verifydetachedsignatureattime - verifies a pkcs#7 signature at a specific time other than the present time. in xconst.h cert_encodenameconstraintsextension - matching function for cert_decodenameconstraintsextension, added in nss 3.10. in secitem.h secitem_allocarray secitem_duparray secitem_freearray secitem_zfreearray - utility functions to handle the allocation and deallocation of secitemarrays secitem_reallocitemv2 - replaces secitem_reallocitem, which is now obsolete. secitem_...
...ay - represents a variable-length array of secitems. new macros in ssl.h ssl_enable_ocsp_stapling - used with ssl_optionset to configure tls client sockets to request the certificate_status extension (eg: ocsp stapling) when set to pr_true notable changes in nss 3.15 secitem_reallocitem is now deprecated. please consider using secitem_reallocitemv2 in all future code. nss has migrated from cvs to the mercurial source control management system. updated build instructions are available at migration to hg as part of this migration, the source code directory layout has been re-organized. the list of root ca certificates in the nssckbi module has been updated. the default implementation of ssl_authcertificate has been updated to ...
NSS 3.16.2 release notes
alls: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_rtm/src/ new in nss 3.16.2 new functionality dtls 1.2 is supported. the tls application layer protocol negotiation (alpn) extension is also supported on the server side. rsa-oeap is supported. use the new pk11_privdecrypt and pk11_pubencrypt functions with the ckm_rsa_pkcs_oaep mechanism. new intel aes assembly code for 32-bit and 64-bit windows, contributed by shay gueron and vlad krasnov of intel. new functions in cert.h ​cert_addextensionbyoid - adds an extension to a certificate. it is the same as cert_addextension except that the oid is represented by a secitem instead of a secoidtag. in pk11pub.h pk11_privdecrypt - decrypts with a private key. the algorithm is specified with a ck...
...ddextension except that the oid is represented by a secitem instead of a secoidtag. 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 wrapp...
NSS 3.17.3 release notes
quires nspr 4.10.7 or newer. nss 3.17.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_3_rtm/src/ new in nss 3.17.3 new functionality support for tls_fallback_scsv has been added to the ssltap and tstclnt utilities. notable changes in nss 3.17.3 the quickder decoder now decodes lengths robustly (cve-2014-1569). the following ca certificates were removed cn = gte cybertrust global root sha1 fingerprint: 97:81:79:50:d8:1c:96:70:cc:34:d8:09:cf:79:44:31:36:7e:f4:74 cn = thawte server ca sha1 fingerprint: 23:e5:94:94:51:95:f2:41:48:03:b4:d5:64:d2:a3:a3:f5:d8:8b:8c cn = thawte premium server ca sha1 fin...
...7f:90:44:c9:fe:b3:f3:3e:fa:9a cn = america online root certification authority 1 sha-1 fingerprint: 39:21:c1:15:c1:5d:0e:ca:5c:cb:5b:c4:f0:7d:21:d8:05:0b:56:6a cn = america online root certification authority 2 sha-1 fingerprint: 85:b5:ff:67:9b:0c:79:96:1f:c8:6e:44:22:00:46:13:db:17:92:84 the following ca certificates had the websites and code signing trust bits turned off ou = class 3 public primary certification authority - g2 sha1 fingerprint: 85:37:1c:a6:e5:50:14:3d:ce:28:03:47:1b:de:3a:09:e8:f8:77:0f cn = equifax secure ebusiness ca-1 sha1 fingerprint: da:40:18:8b:91:89:a3:ed:ee:ae:da:97:fe:2f:9d:f5:b7:d1:8a:41 the following ca certificates were added cn = comodo rsa cer...
NSS 3.17.4 release notes
p.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_4_rtm/src/ new in nss 3.17.4 new functionality no new functionality is introduced in this release. this is a patch release to fix multiple bugs. ...
... bugs fixed in nss 3.17.4 this bugzilla query returns all the bugs fixed in nss 3.17.4: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.4 compatibility nss 3.17.4 shared libraries are backward compatible with all older nss 3.x shared libraries. ...
NSS 3.17 release notes
ervices (nss) 3.17, which is a minor release. distribution information the hg tag is nss_3_17_rtm. nss 3.17 requires nspr 4.10.7 or newer. ...
... new macros in ssl.h ssl_reuse_server_ecdhe_key notable changes in nss 3.17 the manual pages for the certutil and pp tools have been updated to document the new parameters that had been added in nss 3.16.2. ...
NSS 3.19.2.1 release notes
balls: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.2.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. ...
... bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actually allocating the requested memory. ...
NSS 3.19.4 release notes
tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_4_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.19.4. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. ...
... bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actually allocating the requested memory. ...
NSS 3.20.1 release notes
tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_1_rtm/src/ https://ftp.mozilla.org/pub/nspr/releases/v4.10.10/src/ security advisories the following security-relevant bugs have been resolved in nss 3.20.1. users are encouraged to upgrade immediately. bug 1192028 (cve-2015-7181) and bug 1202868 (cve-2015-7182): several issues existed within the asn.1 decoder used by nss for handling streaming ber data. while the majority of nss uses a separate, unaffected der decoder, several public routines also accept ber data, and thus are affected. an attacker that successfully exploited these issues can overflow the heap and may be able to obtain remote code execution. the following security-relevant bugs have been resolved in nspr 4.10.10, which affect nss. ...
... bug 1205157 (nspr, cve-2015-7183): a logic bug in the handling of large allocations would allow exceptionally large allocations to be reported as successful, without actually allocating the requested memory. ...
NSS 3.24 release notes
ance (as of 2015): software integrity checks and post functions are executed on shared library load. these checks have been disabled by default, as they can cause a performance regression. to enable these checks, you must define symbol nss_force_fips when building nss. counter mode and galois/counter mode (gcm) have checks to prevent counter overflow. additional csps are zeroed in the code. nss softoken uses new guidance for how many rabin-miller tests are needed to verify a prime based on prime size. nss softoken has also been updated to allow nss to run in fips level 1 (no password). this mode is triggered by setting the database password to the empty string. in fips mode, you may move from level 1 to level 2 (by setting an appropriate password), but not the reverse. a ...
...or signing rather than key exchange. update sslauthtype to define a larger number of authentication key types. deprecate the member attribute authalgorithm of type sslciphersuiteinfo. instead, applications should use the newly added attribute authtype. rename ssl_auth_rsa to ssl_auth_rsa_decrypt. add a shared library (libfreeblpriv3) on linux platforms that define freebl_lowhash. remove most code related to ssl v2, including the ability to actively send a sslv2-compatible client hello. however, the server-side implementation of the ssl/tls protocol still supports processing of received v2-compatible client hello messages. disable (by default) nss support in optimized builds for logging ssl/tls key material to a logfile if the sslkeylogfile environment variable is set. to enable the funct...
NSS 3.28 release notes
emeprefset allows an application to set which signature schemes should be supported in tls and to specify the preference order of those schemes. ssl_signatureschemeprefget allows an application to learn the currently supported and enabled signature schemes for a socket. request to test and prepare for tls 1.3 this release contains improved support for tls 1.3, however, the code that supports tls 1.3 is still disabled by default (not built). for the future nss 3.29 release, it is planned that standard builds of nss will support the tls 1.3 protocol (although the maximum tls protocol version enabled by default will remain at tls 1.2). we know that some applications which use nss, query nss for the supported range of ssl/tls protocols, and will enable the maximum enabled...
...prefget. the old ssl_signatureprefset and ssl_signatureprefset functions are now deprecated. nss will now no longer assume that default signature schemes are supported by a peer if there was no commonly supported signature scheme. nss will now check if rsa-pss signing is supported by the token that holds the private key prior to using it for tls (bug 1311950). the certificate validation code contains checks to no longer trust certificates that are issued by old wosign and startcom cas, after october 21, 2016. this is equivalent to the behavior that mozilla will release with firefox 51. background information can be found in mozilla's blog post. bugs fixed in nss 3.28 this bugzilla query returns all the bugs fixed in nss 3.28: https://bugzilla.mozilla.org/buglist.cgi?resolution=fi...
NSS 3.35 release notes
for a sufficient number of records. ssl_keylogfile support was updated for tls 1.3. an option to enable tls 1.3 compatibility mode, ssl_enable_tls13_compat_mode, was added. note: in this release, support for new rsa_pss_pss_shax signature schemes have been disabled; end-entity certificates with rsa-pss keys will still be used to produce signatures, but they will use the rsa_pss_rsae_shax codepoints. note: the value of ssl_tls13_key_share_xtn value, from the sslextensiontype, has been renumbered to match changes in tls 1.3. this is not expected to cause problems; code compiled against previous versions of tls will now refer to an unsupported codepoint, if this value was used. recompilation should correct any mismatches. note: dtls support is promoted in draft -23, but this is cu...
...ny 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 runtime to a later version of nss, which no longer provides any of these apis, the application must handle the scenario gracefully. in order to ease transitions, experimental functions return secfailure and set the ssl_error_unsupported_experimental_api code if the selected api is not available. experimental functions will always return this result if they are disabled or removed from a later nss release. if these experimental functions are made permanent in a later nss release, no change to code is necessary. (only apis exported in *.def files are stable apis.) new experimental functionality provided below are descriptions of experimental functio...
NSS 3.45 release notes
19) bug 1515342 - more thorough input checking (cve-2019-11729) bug 1552208 - prohibit use of rsassa-pkcs1-v1_5 algorithms in tls 1.3 (cve-2019-11727) bug 1227090 - fix a potential divide-by-zero in makepfromqandseed from lib/freebl/pqg.c (static analysis) bug 1227096 - fix a potential divide-by-zero in pqg_verifyparams from lib/freebl/pqg.c (static analysis) bug 1509432 - de-duplicate code between mp_set_long and mp_set_ulong bug 1515011 - fix a mistake with chacha20-poly1305 test code where tags could be faked. only relevant for clients that might have copied the unit test code verbatim bug 1550022 - ensure nssutil3 gets built on android bug 1528174 - chacha20poly1305 should no longer modify output length on failure bug 1549382 - don't leak in pkcs#11 modules if c_getslotinfo(...
...cket only after handshake is marked as finished bug 1550708 - fix gyp scripts on solaris sparc so that libfreebl_64fpu_3.so builds bug 1554336 - optimize away unneeded loop in mpi.c bug 1559906 - fipstest: use ckm_tls12_master_key_derive instead of vendor specific mechanism bug 1558126 - tls_aes_256_gcm_sha384 should be marked as fips compatible bug 1555207 - helloretryrequestcallback return code for rejecting 0-rtt bug 1556591 - eliminate races in uses of pk11_setwrapkey bug 1558681 - stop using a global for anti-replay of tls 1.3 early data bug 1561510 - fix a bug where removing -arch xxx args from cc didn't work bug 1561523 - add a string for the new-ish error ssl_error_missing_post_handshake_auth_extension this bugzilla query returns all the bugs fixed in nss 3.45: https://bugz...
NSS 3.55 release notes
_3_55_rtm/src/ other releases are available in nss releases. notable changes in nss 3.55 p384 and p521 elliptic curve implementations are replaced with verifiable implementations from fiat-crypto and ecckiila. special thanks to the network and information security group (nisec) at tampere university. pk11_findcertinslot is added. with this function, a given slot can be queried with a der-encoded certificate, providing performance and usability improvements over other mechanisms. see bug 1649633 for more details. dtls 1.3 implementation is updated to draft-38. see bug 1647752 for details. nspr dependency updated to 4.27. known issues on some platforms, using the makefile builds fails to locate seccomon.h; ensure you are using make all rather than just make. another potential work...
...h. bug 1649648 - don't memcpy zero bytes (sanitizer fix). bug 1649316 - don't memcpy zero bytes (sanitizer fix). bug 1649322 - don't memcpy zero bytes (sanitizer fix). bug 1653202 - fix initialization bug in blapitest when compiled with nss_disable_deprecated_seed. bug 1646594 - fix avx2 detection in makefile builds. bug 1649633 - add pk11_findcertinslot to search a given slot for a der-encoded certificate. bug 1651520 - fix slotlock race in nsc_gettokeninfo. bug 1647752 - update dtls 1.3 implementation to draft-38. bug 1649190 - run cipher, sdr, and ocsp tests under standard test cycle in ci. bug 1649226 - add wycheproof ecdsa tests. bug 1637222 - consistently enforce iv requirements for des and 3des. bug 1067214 - enforce minimum pkcs#1 v1.5 padding length in rsa_checksignr...
Hashing - sample 1
2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
...2.0. if a copy of the mpl was not distributed with this * file, you can obtain one at http://mozilla.org/mpl/2.0/. ...
Notes on TLS - SSL 3.0 Intolerant Servers
like netscape 6.0/6.01/6.1 preview release 1 and mozilla 0.9.1 and earlier to turn off the tls option at: edit | preferences | privacy and security | ssl | enable tls. however, this is a temporary workaround at best. we recommend strongly that you urge users to upgrade to the latest netscape version (or at least netscape 6.1) since the newer versions have the graceful rollback implemented in the code. if you have questions concerning netscape browsers and problem servers, please contact us using the feedback address at the top of this page. detecting intolerant servers because newer versions of netscape and mozilla have built-in workaround for the problem servers, it is now unlikely that you will experience this problem. but if you're running netscape 6.0/6.01/6.1 pr 1 or mozilla build (p...
...wer versions of netscape and mozilla have built-in workaround for the problem servers, it is now unlikely that you will experience this problem. but if you're running netscape 6.0/6.01/6.1 pr 1 or mozilla build (prior to 6/11/2001), you should look out for the symptom described below. you may also run this test with versions later than the older versions of netscape 6.x or mozilla -- just in case code changes in netscape 6.1/mozilla 0.9.2 or later may not catch all problem servers. when you find a secure site which simply does not display any page content or drops the connection, check to see if the preference option edit | preferences | privacy and security | ssl | enable tls is turned on. if so, turn it off. now re-visit the problem site. if the content displays this time, you are most l...
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
oken to provide the des encryption. only if that token cannot do des will nss try to extract the key. if the smartcard can't do key generation, will nss do the key generation automatically? yes. if your token can do ckm_rsa_pkcs, and is writable, nss displays it as one of the options to do key generation with. if the token cannot do ckm_rsa_pkcs_gen_keypair, nss uses its software key generation code and writes the private and public keys into the token using c_createobject. the rsa private key will contain all the attributes specified by pkcs #11 version 2.0. this is also true for ckm_dsa and ckm_dsa_gen_keypair. what is the c_generatekeypair process? for example, what happens when an application in the a server asks an nss based client to do a keypair generation while a smartcard is atta...
...the key itself. key generation in mozilla clients is triggered either by the standard <keygen> tag, or by the keygen functions off the window.crypto object. this is the same method used for generating software keys and certificates and is used by certificate authorities like verisign and thawte. (red hat certificate server also uses this method). the public key is sent to the server base-64-der-encoded with an (optional) signed challenge. are persistent objects that are stored on the token, such as private keys and certificates, created by the pkcs #11 module? is it safe to assume that nss never calls c_createobject for those persistent objects? no. as stated in the answer to the preceding question, when nss does a keygen it uses c_generatekeypair if the token supports the keygen method. if ...
Migration to HG
bles. updated instructions for building nss with nspr can be found at: /docs/nss_reference/building_and_installing_nss/build_instructions it's best to refer to the above document to learn about the various environment variables that you might have to set to build on your platform (this part hasn't changed). ...
...set build_opt=1 to get an optimized build make nss_build_all note that the jss project has been given a private copy of the former mozilla/security/coreconf directory, allowing it to remain stable, and only update its build system as necessary. because of the changes described above, we have decided to use a new series of (minor) version numbers. the first releases using the new code layout will be nspr 4.10 and nss 3.15 ...
NSS_Initialize
t certs module automatically. nss_init_optimizespace - optimize for space instead of speed. use smaller tables and caches. nss_init_pk11threadsafe - only load pkcs#11 modules that are thread-safe, i.e., that support locking - either os locking or nss-provided locks . if a pkcs#11 module isn't thread-safe, don't serialize its calls; just don't load it instead. this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, the java sunpkcs11 provider. nss_init_pk11reload - ignore the ckr_cryptoki_already_initialized error when loading pkcs#11 modules. this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, java sunpkcs11 provider. nss_init...
...the following limitation applies when this is set : secmod_waitforanytokenevent will not use c_waitforslotevent, in order to prevent the need for c_finalize. ...
NSS tools : vfychain
ble slots, enable or disable fips 140-2 compliance, and assign default providers for cryptographic operations. this tool can also create certificate, key, and module security database files. the tasks associated with security module database management are part of a process that typically also involves managing key databases and certificate databases. options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more. -r following certfile is raw binary der (default) -t following cert is exp...
...crl" and "ocsp". -s method flags sets revocation flags for the method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape, red hat, and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license version 2. references visible li...
SSL functions
most commonly used by applications to support ssl. the nss home page links to additional ssl documentation. if documentation is available for a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. ...
...r a function listed below, the function name is linked to either its mdc wiki page or its entry in the old ssl reference. the mozilla cross reference (dxr) link for each function provides access to the function definition, prototype definition, and source code references. the nss version column indicates which versions of nss support the function. ...
NSS Tools
nss security tools newsgroup: mozilla.dev.tech.crypto overview the nss security tools allow developers to test, debug, and manage applications that use nss. the tools information table below describes both the tools that are currently working and those that are still under development. the links for each tool take you to the source code, documentation, plans, and related links for each tool. the links will become active when information is available. currently, you must download the nss 3.1 source and build it to create binary files for the nss tools. for information about downloading the nss source, see https://developer.mozilla.org/nss/building. if you have feedback or questions, please feel free to post to mozilla.dev.tech.crypto. this newsgroup is the preferred forum for all ...
...y the properties of existing modules (such as whether a module is the default provider of some crypto service). source, documentation, tasks/plans pk12util 1.0 import and export keys and certificates between the cert/key databases and files in pkcs12 format. source, documentation, tasks/plans signtool 1.3 create digitally-signed jar archives containing files and/or code. source, documentation, signver 1.1 verify signatures on digitally-signed objects. source, documentation, tasks/plans sslstrength ssl strength documentation ssltap 3.2 proxy requests for an ssl server and display the contents of the messages exchanged between the client and server. the ssltap tool does not decrypt data, but it shows things l...
NSS Tools certutil
at follows rfc 1485. -t trustargs specify the trust attributes to modify in an existing certificate or to apply to a certificate when creating it or adding it to a database. there are three available trust categories for each certificate, expressed in this order: "ssl ,email ,object signing ". ...
...for example: -t "tcu,cu,tuw" use the -l option to see a list of the current certificates and trust attributes in a certificate database. -u certusage specify a usage context to apply when validating a certificate with the -v option. the contexts are th...
NSS Tools cmsutil
ts are combinations of the options and arguments listed in the following section. each command takes one option. each option may take zero or more arguments. to see a usage string, issue the command without options. options and arguments options specify an action. option arguments modify an action. the options and arguments for the cmsutil command are defined as follows: options -ddecode a message. -c encrypt a message. -e envelope a message. -o create a certificates-only message. -s sign a message. arguments -c content use this detached content (decode only). -d dbdir specify the key/certificate database directory (default is ".") -e envfile specify a file containing an enveloped message for a set of recipients to which you would like to send an encrypted...
...ify a file containing an enveloped message for a set of recipients to which you would like to send an encrypted message. if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only). -g include a signing time attribute (sign only). -h num generate email headers with info about cms message (decode only). -i infile use infile as a source of data (default is stdin). -n nickname specify nickname of certificate to sign with (sign only). -n suppress output of contents (decode only). -o outfile use outfile as a destination of data (default is stdout). -p include an s/mime capabilities attribute. -p password use password as key database password. -r recipient1,recipient2, . ...
NSS tools : signver
Mozilla › Projects › NSS › tools › signver
the signature verification tool can also display the contents of the signed object. ...
... https://wiki.mozilla.org/nss_shared_db_howto o engineering and technical information about the shared nss database https://wiki.mozilla.org/nss_shared_db additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape, red hat, and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license vers...
NSS tools : vfychain
s 140-2 compliance, and assign default providers for cryptographic operations. this tool can also create certificate, key, and module security database files. the tasks associated with security module database management are part of a process that typically also involves managing key databases and certificate databases. ...
...s revocation flags for the method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape, red hat, and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license vers...
Small Footprint
bytes of all uncompressed rhino classes with debug information included. with various changes js.jar size can be reduced to 204,689 bytes corresponding to 424,774 bytes of uncompressed classes. tools most embeddings won't need any of the classes in org.mozilla.javascript.tools or any of its sub-packages. optimizer it is possible to run rhino with interpreter mode only, allowing you to remove code for classfile generation that include all the classes from <tt>org.mozilla.javascript.optimizer</tt> package. javaadapter implementing the javaadapter functionality requires the ability to generate classes on the fly. removing org.mozilla.javascript.javaadapter will disable this functionality, but rhino will otherwise run correctly. class generation library if you do not include optimizer or ...
...class file generation and you can remove all the classes from in org.mozilla.classfile package. regular expressions the package org.mozilla.javascript.regexp can be removed. rhino will continue to run, although it will not be able to execute any regular expression matches. this change saves 47,984 bytes of class files. debug information debug information in rhino classes consumes about 25% of code size and if you can live without that, you can recompile rhino to remove it. smalljs.jar ant build script in rhino supports smalljar target that will generate smalljs.jar that does not include tools, optimizer, javaadapter and class generation library, regular expressions, e4x implementataion and deprecated files. to build such minimalist jar without debug information, run the following command...
Rhino scopes and contexts
; once you are done with execution, simply exit the context: context.exit(); these calls will work properly even if there is already a context associated with the current thread. that context will be returned and an internal counter incremented. only when the counter reaches zero will it be disassociated from the thread. remember to put the exit() call in a finally block if you're executing code that could throw an exception. scopes a scope is a set of javascript objects. execution of scripts requires a scope for top-level script variable storage as well as a place to find standard objects like function and object. it's important to understand that a scope is independent of the context that created it. you can create a scope using one context and then evaluate a script using that scop...
...enever you need one. however, initstandardobjects is an expensive method to call and it allocates a fair amount of memory. we'll see below that there are ways to share a scope created this way among multiple scopes and threads. name lookup so how are scopes used to look up names? in general, variables are looked up by starting at the current variable object (which is different depending on what code is being executed in the program), traversing its prototype chain, and then traversing the parent chain. in the diagram below, the order in which the six objects are traversed is indicated. order of lookups in a two-deep scope chain with prototypes. for a more concrete example, let's consider the following script: var g = 7; function f(a) { var v = 8; x = v + a; } f(6); we have a top...
Creating JavaScript tests
ionality. jstests is intended for tests of language-visible functionality. please put tests of functionality into jstests even if related tests are in jit-tests, since jstests are closer to (and more easily converted to) test262 tests. (in fact, the test262 test suite is run as part of jstests.) practical differences between the two test suites: jstest new jstest files should be put the code in the appropriate subdirectory of js/src/tests/non262/, or, under some scenarios, contributed directly to the test262 repository. jstests run in both the shell and the browser (although you can specify that the test should be run in only one of the two locations). jstests automatically load js/src/tests/shell.js before they run, which creates a ton of functions. read more advice on jstests he...
... in (or posting it for review). nobody likes patches that include failing tests! see running automated javascript tests for instructions on how to run jstests or jit-tests. it's also a good sanity check to run each new test against an unpatched shell or browser. the test should fail if it's working properly. checking in completed tests tests are usually reviewed and pushed just like any other code change. just include the test in your patch. security-sensitive tests should not be committed until the corresponding bug has been made public. instead, ask a spidermonkey peer how to proceed. it is ok under certain circumstances to push new tests to certain repositories without a code review. don't do this unless you know what you're doing. ask a spidermonkey peer for details. ...
FOSS
ospection mechanism) objective caml http://alain.frisch.fr/soft.html#spider - bindings to embed spidermonkey in ocaml applications perl http://jspl.msg.mx/ - bindings to cross-embed spidermonkey and perl. includes a js shell that allows you to use cpan modules from javascript. ...
...ml applications perl http://jspl.msg.mx/ - bindings to cross-embed spidermonkey and perl. includes a js shell that allows you to use cpan modules from javascript. python http://pypi.python.org/pypi/python-spidermonkey wxwidgets gluescript (formerly wxjavascript) code generators jsapigen - generates bindings for embedding spidermonkey in c applications extensions http://code.google.com/p/jslibs/ - zlib, sqlite, nspr, ode, libpng, libjpeg, libffi, (...) libraries for spidermonkey http://www.jsdb.org/ - a js shell with native objects for files, networks, databases, compression, email, etc. http://code.google.com/p/gpsee/ - commonjs platform, native-language module interoperability methods, modules, etc. for spidermonkey. designed to supplement existing embe...
GC Rooting Guide
/ ... if (!waserror) valueout.set(resultvalue); return waserror; } void otherfunction(jscontext *cx) { js::rootedvalue value(cx); bool success = maybegetvalue(cx, &value); // ... } return values it's ok to return raw pointers! these do not need to be wrapped in any of rooting classes, but they should be immediately used to initialize a js::rooted<t> if there is any code that could gc before the end of the containing function; a raw pointer must never be stored on the stack during a gc. one rare but especially tricky case to watch out for is where an raii destructor could gc in a function that is returning a bare pointer. consider: jsobject* somefunction(jscontext* cx) { js::rooted<jsobject*> obj(cx, foo()); eventlogger logger(cx); ...code... re...
...ger will fire and trigger a gc, invalidating that unrooted stack/register pointer. this scenario is rare but very difficult to notice manually, and will probably be caught by the static rooting hazard analysis. there are two different approaches to resolving this; use whichever better fits your situation: void somefunction(jscontext* cx, js::mutablehandleobject obj) { eventlogger(cx); ...code... obj.set(foo()); } (note that the above should probably check the return value and propagate an error on null), or: jsobject* somefunction(jscontext* cx) { js::rooted<jsobject*> obj(cx, foo()); { // make a scope to force the destructor to run before obj is unwrapped. eventlogger(cx); ...code... } return obj; } autorooters gc thing pointers that appear a...
Statistics API
ile. when logging to a file is used in combination with multi-process firefox (e10s) it is necessary to set security.sandbox.content.level = 0, otherwise the content process will crash. the browser preference javascript.options.mem.log controls dumping of human-readable gc stats messages to the developer console. the browser preference javascript.options.mem.notify controls emission of json encoded gc stats to an observer interface. json api addons can obtain the complete data in json format via an observer. the following adds an observer using the jetpack framework. var prefs = require("api-utils/preferences-service"); components.utils.import('resource://gre/modules/services.jsm'); function observer(subject, topic, json) { var data = json.parse(json); // process the data } p...
...es, sweep_compartments phases and so on. the times object gives how much time was spent in each phase of the gc, in milliseconds. additionally, an incremental gc is divided into a series of slices (the division into slices is completely separate from the division into phases; neither one is a refinment of the other). a little bit of gc work is done in each slice. in between slices, other browser code is allowed to run. the slices array describes how long each slice took and what work was done during the slice. each element of the slices array is an object with these fields: slice: integer - the slice index, starting at 0. pause: number (milliseconds) - the slice duration. when: number (milliseconds) - the time this slice started, relative to the first slice's start time. reason: string ...
SpiderMonkey Internals: Thread Safety
container for everything else. a program typically has only one jsruntime, even if it has many threads. each runtime has one or more jscompartments. the jscompartment is the universe in which js objects live. they can't travel to other jscompartments. crucially, any given compartment may only be accessed by one thread at a time. this means that objects cannot be shared across compartments. ...
...more jscompartments. the jscompartment is the universe in which js objects live. they can't travel to other jscompartments. crucially, any given compartment may only be accessed by one thread at a time. this means that objects cannot be shared across compartments. all js code and most jsapi calls run within a jscontext. the jscontext can be thought of as a machine that knows how to run javascript code, or as an abstraction of the notion of a thread. exception handling, for example, is per-jscontext. each jscontext must be used by only one thread at a time. a single jscontext can run work with code and objects in multiple compartments as long as no other thread is accessing those compartments. objects may be shared among jscontexts within a jscompartment. there's no fixed association between an...
JS::Value
key gc rooting guide. the jsval typedef for js::value js::value was historically known in the jsapi as jsval. spidermonkey 1.8.5 made jsval into a c struct and exposed it in c++ through the full-fledged js::value class. as of spidermonkey 17, jsval is a typedef of js::value, and spidermonkey is gradually transitioning to a new c++ jsapi, at whose heart lies js::value. jsval is deprecated; new code should use js::value. the old jsval_is_* methods, jsval_* constants and *_to_jsval methods, and jsval_to_* methods are also deprecated; uses of each should be replaced with use of the corresponding val.is*(), *value(), and val.to*() methods. js type jsval type tests jsval constants and constructors jsval accessors null jsval_is_null(v) jsval_null un...
...uses of this method should be replaced with v.isobjectornull(). ...
JSClass.flags
jsclass_global_flags this flag is only relevant for the class of an object that is used as a global object. (ecmascript specifies a single global object, but in spidermonkey the global object is the last object in the scope chain, which can be different objects at different times. this is actually quite subtle. js_executescript and similar apis set the global object for the code they execute. js_setglobalobject sets an object which is sometimes used as the global object, as a last resort.) enable standard ecmascript behavior for setting the prototype of certain objects, such as function objects. if the global object does not have this flag, then scripts may cause nonstandard behavior by replacing standard constructors or prototypes (such as function.prototype.) ...
...js_initclass to invoke the constructor when creating the class prototype. jsclass_is_extended obsolete since jsapi 17indicates that this jsclass is really a jsextendedclass. jsclass_mark_is_trace obsolete since jsapi 5 indicates that the mark hook implements the new jstraceop signature instead of the old jsmarkop signature. this is recommended for all new code that needs custom marking. spidermonkey reserves a few other flags for its internal use. they are jsclass_is_anonymous, jsclass_is_global, jsclass_is_proxy, and jsclass_has_cached_proto. jsapi applications should not use these flags. see also bug 527805 - removed jsclass_share_all_properties bug 571789 - removed jsclass_is_extended bug 638291 - removed jsclass_mark_is_trace bug 6410...
JSClass
s pointer to null. obsolete since jsapi 13 trace jstraceop the gc trace hook. description use jsclass to define a custom class of javascript objects. a jsclass has a name, flags, and several callback functions for advanced customization of object behavior. simple classes a simple custom class does not require any special jsclass callbacks. ...
... description use jsclass to define a custom class of javascript objects. a jsclass has a name, flags, and several callback functions for advanced customization of object behavior. simple classes a simple custom class does not require any special jsclass callbacks. instead, all the native code is in jspropertyops (property getters and setters) and jsnatives or jsfastnatives (methods). ...
JSDeletePropertyOp
cess is taking place. provides request. in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). obj js::handleobject the object whose properties are being deleted. id js::handleid the name or index of the property being deleted. this is either a string (unicode property identifier) or an integer (element index). succeeded bool * out parameter. receives the result of deletion. description jsdeletepropertyop callback is a hook that applications may install to be called at some point during property access. a jsdeletepropertyop may be installed on a jsclass to hook property deletes. if a jsdeletepropertyop does nothing and returns t...
...s.delproperty is called during most property deletions, even when obj has no property named id. if an error occurred, return false as per normal jsapi error practice. if no error occurred, but the deletion attempt wasn't allowed (perhaps because the property was non-configurable), set *succeeded to false and return true. this will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a typeerror in strict mode code. if no error occurred and the deletion wasn't disallowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is allowed -- it's just pointless), set *succeeded to true and return true. this hook is not called when the target property is jsprop_permanent and is an own ...
JSFunction
jsfunction is a type in the jsapi. the apis js_newfunction, js_definefunction, js_compilefunction, and their unicode equivalents return values of type jsfunction *. for native functions and jsapi-compiled functions - that is, functions returned by the apis listed above-there is a simple one-to-one relationship between the jsfunction and the corresponding javascript function object. to get a jsfunction * given the jsobject * of a function object, use js_valuetofunction. to get the jsobject * given the jsfunction *, use js_getfunctionobject. for other function objects - that is, functions created by running javascript code containing function declarations or function-expressions-the relationship between the jsfunction * and the jsobject * is not well-defined. different closures (function object...
...as a result, some apis (such as js_callfunction) that operate on jsfunctions do not work properly with closures. ...
JSGetObjectOps
a jsclass, which is stored as a private (int-tagged) pointer in object slots. in contrast, all native and host objects have a jsobjectmap at obj->map, which may be shared among a number of objects, and which contains the jsobjectops *ops pointer used to dispatch object operations from api calls. thus jsclass (which pre-dates jsobjectops in the api) provides a low-level interface to class-specific code and data, while jsobjectops allows for a higher level of operation, which does not use the object's class except to find the class's jsobjectops struct, by calling clasp->getobjectops, and to finalize the object. if this seems backwards, that's because it is! api compatibility requires a jsclass *clasp parameter to js_newobject, etc. most host objects do not need to implement the larger jsobjecto...
...or a higher level of operation, which does not use the object's class except to find the class's jsobjectops struct, by calling clasp->getobjectops, and to finalize the object. if this seems backwards, that's because it is! api compatibility requires a jsclass *clasp parameter to js_newobject, etc. most host objects do not need to implement the larger jsobjectops, and can share the common jsscope code and data used by the native (js_objectops, see jsobj.c) ops. further extension to preserve api compatibility: if this function returns a pointer to jsxmlobjectops.base, not to jsobjectops, then the engine calls extended hooks needed for e4x. jsclass hooks jsclass offerd following hook: the jsclass.getobjectops hook is called each time an object is created. it returns a pointer to a jsobjec...
JSPropertyDescriptor
var language = {}; // define an empty object language languange.log = ['cn','en']; // define the log attribute under the language object ...
... var language = {}; // define an empty object language languange.log = ['cn','en']; // define the log attribute under the language object ...
JSRuntime
the jscontext is a child of the jsruntime. a context can run scripts. it contains the global object and the execution stack. ...
...s are per-jscontext. once created, a context can be used any number of times for different scripts or jsapi queries. for example, a browser might create a separate context for each html page; every script in the page could use the same context. objects may be shared among jscontexts within a jsruntime. there's no fixed association between an object and the context in which it is created. sample code to set up and tear down a jsruntime and a jscontext is at jsapi user guide. threads only one thread may use a jscontext or jsruntime. earlier versions allowed using js_clearcontextthread and other functions to move a jscontext from one thread to another. this feature has since been removed. see also js_newruntime js_destroyruntime js_newcontext js_destroycontext ...
JS_CStringsAreUTF8
which take utf-8 explicitly or handle their own string encoding and decoding. option to have the jsapi treat char strings as utf-8. syntax jsbool js_cstringsareutf8(void); void js_setcstringsareutf8(void); // added in spidermonkey 1.8 description by default, all c/c++ strings passed into the jsapi are treated as iso/iec 8859-1, also known as iso-latin-1. that is, each byte is treated as a unicode character, and there is no way to pass in a string containing characters beyond u+00ff. however, spidermonkey can optionally interpret these strings as utf-8. there are two ways to enable this: at compile time, by building spidermonkey with js_c_strings_are_utf8 defined; or at run time, by calling js_setcstringsareutf8 before the first call to js_newruntime. enabling this option also causes js_ge...
...is no way to pass in a string containing characters beyond u+00ff. however, spidermonkey can optionally interpret these strings as utf-8. there are two ways to enable this: at compile time, by building spidermonkey with js_c_strings_are_utf8 defined; or at run time, by calling js_setcstringsareutf8 before the first call to js_newruntime. enabling this option also causes js_getstringbytes and js_encodecharacters to produce utf-8 strings instead of latin-1. js_cstringsareutf8 returns js_true if the javascript engine is configured (either at compile time or at run time) to interpret char strings as utf-8. see also bug 805080 ...
JS_CheckForInterrupt
description js_checkforinterrupt checks for the interrupt, and handle it if it's pending. ...
... description js_checkforinterrupt checks for the interrupt, and handle it if it's pending. ...
JS_CompileFunction
onst char * name of file or url containing the function. used to report filename or url in error messages. lineno unsigned int line number. used to report the offending line in the file or url if an error occurs. description js_compilefunction compiles a function from a text string, bytes, and optionally associates it with a js object, obj. js_compileucfunction is the unicode version of the function. name is the name to assign to the newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. body is a string containing the source code of the function. length is the length ...
...e function. name is the name to assign to the newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. body is a string containing the source code of the function. length is the length of the source code in characters. filename is the name of the file (or url) containing the function. this information is used in error messages if an error occurs during compilation. similarly, lineno is used to report the line number where an error occurred during compilation. if both obj and name are non-null, the new function becomes a method of obj. (a new property is defined on obj with the given name and th...
JS_CompileScript
r16_t * string containing the script to compile. length size_t the length, in characters, of source. options js::compileoptions &amp; compile options. script js::mutablehandlescript out parameter. on success, script receives the result script. description js_compilescript compiles a script, source, for execution. js_compileucscript is the unicode version of the function. the script is associated with a js object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. on success, js_compilescript and js_compileucscript stores the newly compiled script to *script and returns true. otherwise, they report an error, stores null to *script, and return false.
...with a js object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. on success, js_compilescript and js_compileucscript stores the newly compiled script to *script and returns true. otherwise, they report an error, stores null to *script, and return false. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compilescript mxr id search for js_compileucscript js::evaluate js::compileoffthread js::compilefunction js_executescript js_decompilescript bug 1143793 -- removed obj parameter ...
JS_CompileUTF8File
syntax jsobject * js_compileutf8file(jscontext *cx, jsobject *obj, const char *filename); name type description cx jscontext * the context in which to compile the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...le compiles the text of script in an external file location for execution by the js engine. filename is the name of the file containing the script to compile. on success, js_compileutf8file returns an object that represents the newly compiled script. otherwise it returns null. js_compileutf8file is deprecated, use file, use js::compile instead. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compilefile js::compile js_decompilescript js::evaluate js_executescript bug 805080 ...
JS_CompileUTF8FileHandle
obsolete since jsapi 19this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. compile a script, reading the source code from a stdio file. syntax jsobject * js_compileutf8filehandle(jscontext *cx, jsobject *obj, const char *filename, file *file); jsobject * js_compileutf8filehandleforprincipals( jscontext *cx, jsobject *obj, const char *filename, file *file, jsprincipals *principals); name type description cx jscontext * the context in which to compile the script. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object with which the script is associated. f...
.... on success, js_compileutf8filehandle reads file to eof and returns an object representing the newly compiled script. if an error occurs during compilation, js_compileutf8filehandle stops reading from the file and returns null. js_compileutf8filehandle and js_compileutf8filehandleforprincipals are deprecated, use file, use js::compile instead. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js_compileutf8filehandle js::compile js_decompilescript js::evaluate js_executescript bug 805080 ...
JS_DefineProperty
; or null. attrs unsigned property attributes. desc js::handle&lt;jspropertydescriptor&gt; the property descriptor for the property to be defined. result js::objectopresult &amp; (out parameter) receives the result of the operation. description js_defineproperty defines a single property in a specified object, obj. js_defineucproperty is the unicode version of the function. js_definepropertybyid is the same but takes a js::handleid for the property name. js_defineproperty is the fundamental operation on which several more convenient, higher-level functions are based, including js_definefunction, js_definefunctions, js_defineproperties, js_defineconstdoubles, js_defineobject, and js_initclass. it differs from js_setproperty in that: it do...
...me, initial stored value, getter, setter, and property attributes (attrs). if obj already has an own property with the given name or id, the existing property is replaced. these functions can currently replace jsprop_permanent properties, but such usage is deprecated. the javascript engine will call the getter or setter callback each time the property is read or written, whether from javascript code or via jsapi functions like js_getproperty and js_setproperty. (exception: if attrs contains the jsprop_readonly flag, the setter will never be called, as property assignment will fail before it gets that far. also note that certain jsapi functions, including js_lookupproperty, js_hasproperty, and property_attributes, can detect or examine a property without calling its getter.) if getter (or set...
JS_FS
ymbol, call, info, nargs, flags, selfhostedname) ... // added in spidermonkey 38 #define js_fnspec(name,call,info,nargs,flags,selfhostedname) ... // added in spidermonkey 31 #define js_fs_end ... name type description name const char * the javascript name for the function. (or index, if jsprop_index is present in flags) symbol a member name of js::symbolcode the javascript symbol for the function. call jsnative pointer to the c/c++ implementation of the function. info const jsjitinfo * pointer to the jit info. nargs uint16_t the number of arguments the function expects. flags uint16 the bitwise or of any number of function flags. selfhostedname const char * the function's n...
...the function. call jsnative pointer to the c/c++ implementation of the function. info const jsjitinfo * pointer to the jit info. nargs uint16_t the number of arguments the function expects. flags uint16 the bitwise or of any number of function flags. selfhostedname const char * the function's name in self-hosted javascript code. description use these macros to define an array of jsfunctionspecs to pass to js_definefunctions or js_initclass. js_fn (whose name pays homage to the old jsnative/jsfastnative split) simply adds the flag jsfun_stub_gsops. js_fninfo allows the simple adding of jsjitinfos. js_self_hosted_fn declares a self-hosted function. finally js_fnspec has slots for all the fields. the _sym variants al...
JS_GetParent
etparent(jsobject *obj); name type description obj jsobject * object for which to retrieve the parent. description js_getparent retrieves the parent object of obj, or null if obj does not have a parent. warning: the result may be an internal-use-only object. such an object should not be passed to any other jsapi function that could expose it to script code. each object is assigned a parent when it is created: the standard library objects and functions all have the global object as their parent. objects created by standard library functions, such as array.prototype.concat, have the global object as their parent. an object created by a script via the new keyword has the same parent as the constructor. for example, after d = new date, d has th...
... security features can use the parent during security checks, as a convenient way to determine the security domain of an object being accessed. the typical rule is that every object is in the same security domain as its parent. (but each application can define its own security rules. see the security section of the user guide for an introduction to the security model.) in some cases, javascript code can get an object's parent via the read-only obj.__parent__ property. but if an object's parent is an internal-use-only object (that is, a special call, with, or block object), js_getparent simply returns it, but obj.__parent__ === null. similarly, if an object's parent is an inner object, js_getparent simply returns it, but obj.__parent__ returns the corresponding outer object. see also mxr ...
JS_GetScopeChain
obsolete since javascript 1.8.7this 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. retrieves the scope chain for the javascript code currently running in a given context. js_getscopechain has been removed in spidermonkey 1.8.7 with no identical replacement. when you only used this function to retrieve the scope chain's global, then you can use the function js_getglobalforscopechain. syntax jsobject * js_getscopechain(jscontext *cx); name type description cx jscontext * the context to query. description js_getscopechain returns the first jsobject on the scope chain for the javascript code currently running in the given context, cx. th...
...ently executing function was created in the scope of a different global object, then that object will be the last object in the current scope chain. if the context is currently executing a script, and not in any function, it's running in a scope that was passed to js_executescript or a similar function by the application. this scope chain may or may not contain cx's current global object. if any code is currently executing in cx, js_getscopechain returns a pointer to the first jsobject on the current scope chain. otherwise, if cx has a global object, js_getscopechain returns that. otherwise, an error is reported and js_getscopechain returns null. to walk the scope chain, use js_getparent. see also mxr id search for js_getscopechain js_getglobalforscopechain bug 632064 ...
JS_GetSecurityCallbacks
const jssecuritycallbacks * a pointer to the new callbacks for the runtime. callback structure struct jssecuritycallbacks { jscspevalchecker contentsecuritypolicyallows; // added in spidermonkey 1.8.5 jssubsumesop subsumes; // added in spidermonkey 31 jscheckaccessop checkobjectaccess; // obsolete since jsapi 29 jsprincipalstranscoder principalstranscoder; // obsolete since jsapi 13 jsobjectprincipalsfinder findobjectprincipals; // obsolete since jsapi 13 }; name type description contentsecuritypolicyallows jscspevalchecker a pointer to the function which checks if a csp instance wants to disable eval() and friends. use null is not needed. subsumes jssubsumesop a pointe...
...unction which checks if a csp instance wants to disable eval() and friends. use null is not needed. subsumes jssubsumesop a pointe to the function which returns whether the first principal subsumes the second. use null is not needed. description js_setsecuritycallbacks sets the runtime's security callbacks to callbacks. it allows the embedding to control certain aspects of js code execution based on security settings of the global object the code is executed in. if callbacks is null, it sets callbacks to default value. js_getsecuritycallbacks returns the runtime's current security callbacks. if the callbacks are default value, it returns null see also mxr id search for js_getsecuritycallbacks mxr id search for js_setsecuritycallbacks jsprincipals jscspevalchecker jssub...
JS_GetStringEncodingLength
icle covers features introduced in spidermonkey 1.8.5 get the length of a javascript string in bytes. syntax size_t js_getstringencodinglength(jscontext *cx, jsstring *str); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext.. str jsstring * a string to encode. description js_getstringencodinglength returns the length of the specified string in bytes, regardless of its encoding. you can use this value to create a buffer to encode the string into using the js_encodestringtobuffer function. to encode to utf8, use js::getdeflatedutf8stringlength and js::deflatestringtoutf8buffer instead. see also mxr id search for js_getstringencodinglength ...
... description js_getstringencodinglength returns the length of the specified string in bytes, regardless of its encoding. you can use this value to create a buffer to encode the string into using the js_encodestringtobuffer function. to encode to utf8, use js::getdeflatedutf8stringlength and js::deflatestringtoutf8buffer instead. ...
JS_InternString
syntax jsstring * js_internstring(jscontext *cx, const char *s); jsstring * js_internstringn(jscontext *cx, const char *s, size_t length); jsstring * js_internucstring(jscontext *cx, const char16_t *s); jsstring * js_internucstringn(jscontext *cx, const char16_t *s, size_t length); name type description cx jscontext * a context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
...rray containing the data for the string. in js_internstring and js_internucstring, the string must be null-terminated. length size_t (only in js_internstringn and js_internucstringn) the length of s in characters. description js_internstring and js_internstringn return an interned javascript string with a specified value, s. js_internucstring and js_internucstringn are the unicode versions of the function. each jsruntime keeps a table of all existing interned strings. if an interned string already exists with the desired value, these functions return the existing string. otherwise a new string is created and added to the table. strings created with these functions are protected from garbage collection for the lifetime of the jsruntime. on success, these functions return a ...
JS_LookupProperty
he return value is true (to indicate no error occurred). on error or exception (such as running out of memory during the search), the return value is false, and the value left in *vp is undefined. there is no way to tell the difference between not finding any property and finding a property whose value is undefined. sorry. use js_getpropertydescriptorbyid instead. js_lookupucproperty is the unicode version of js_lookupproperty. flags js_lookuppropertywithflags and js_lookuppropertywithflagsbyid allow the caller to specify flags requesting special lookup behavior. when executing javascript code that uses properties, spidermonkey looks up properties using slightly different rules depending on the syntactic context in which the property name appears. (the javascript engine simply passes these ...
... flag is set. for example, mozilla's document.all property is hidden in this way. jsresolve_declaring behave as though the name were being declared in a var, const, or function declaration. jsresolve_classname search for the initial value of a standard class such as object, array, or error. do not automatically infer and enable other flags by looking at the currently executing bytecode. notes js_lookupproperty does not distinguish between a property with a value of undefined and a property that does not exist. use js_getpropertyattributes to distinguish these cases. js_lookupproperty differs from js_getproperty in that js_lookupproperty does not invoke the get handler for the property. internally, property lookups are implemented by the jsobjectops.lookupproperty callback. see...
JS_NewObject
fy a global object. if the parent is non-null, we assume it is part of a scope chain, walk to the end of that chain, and use the global object we find there. if the parent is null, we use the global object at the end of the scope chain in which the context is currently executing. in other words, the context's current scope acts as a default parent. ...
...other words, the context's current scope acts as a default parent. if the context is not currently executing any code, we use js_getglobalobject to find a global object associated with the context. next, we must find the given class's constructor in that global object. normally we simply use the class's name as the name of the property of the global object to fetch. however, although javascript code can freely redefine constructors, the ecmascript standard requires us in certain cases to use the original constructors' prototypes. if the global object's class's flags include jsclass_global_flags, then the global object always retains the original constructors for each standard class; we use these original constructors when they are available. finally, we must find a prototype. if the const...
JS_NewScriptObject
from garbage collection; when the script object is collected, the jsscript and its contents are freed. once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope). a script object has no properties, and its prototype is object.prototype. so a script object can be used to expose a jsscript to javascript code, but the code can't do much of anything with it. on success, js_newscriptobject returns a pointer to the script's object. otherwise it returns null. (the name "js_newscriptobject" suggests that the script object is freshly allocated; this was the case in older versions of the api, but now the script object is allocated along with the jsscript itself.) (some temporary scripts used internally by...
... mxr id search for js_newscriptobject bug 630209 ...
JS_PushArguments
any asterisks (*) in format are ignored. this function also takes in consideration any additional custom types defined in cx using js_addargumentformatter. for example, if format is "biob", then there must be four arguments after format. their types must be...
...any asterisks (*) in format are ignored. this function also takes in consideration any additional custom types defined in cx using js_addargumentformatter. for example, if format is "biob", then there must be four arguments after format. their types must be jsbool, jsdouble, jsobject *, and jsboo...
JS_SetFunctionCallback
obsolete since jsapi 37this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. sets a callback to be run whenever a javascript function is invoked or exited. this lets you trace the execution of code, and is particularly useful for javascript tracers and profilers since it works across all run modes (interpreter, method jit, trace jit). using this function may have a significant performance impact. see function tracing for an example. note: this method is only available if moz_trace_jscalls was defined at compile time using --enable-trace-jscalls. syntax void js_setfunctioncallback(jscontext *cx, jsfunctioncallback fcb); name type description cx jscontext * ...
...s request. in a js_threadsafe build, the caller must be in a request on this jscontext. fcb jsfunctioncallback the callback to execute when javascript functions are invoked and exited. specify null to stop calling the current callback. the callback must not modify the current state of execution. the call stack cannot be relied upon, because this callback may be invoked from the jit code when the stack frame and context are in an indeterminate state. description js_setfunctioncallback sets a c function to be called each time a javascript function is invoked or exits. fcb is a pointer to the c function to call. note that debuggers should probably use js_setcallhook in preference to this function, because it is invoked when the javascript stack is guaranteed to be in a co...
JS_SetOptions
n spidermonkey 15 ecmascript for xml (e4x) support: parse <!-- --> as a token, not backward compatible with the comment-hiding hack used in html script tags. only used if jsoption_allow_xml is set. mxr id search for jsoption_moar_xml jsoption_native_branch_callback the branch callback set by js_setbranchcallback may be called with a null script parameter, by native code that loops intensively. mxr id search for jsoption_native_branch_callback jsoption_dont_report_uncaught when returning from the outermost api call, prevent uncaught exceptions from being converted to error reports. mxr id search for jsoption_dont_report_uncaught jsoption_relimit added in spidermonkey 1.8 throw an exception if a r...
...ch for jsoption_relimit jsoption_anonfunfix added in spidermonkey 1.8 disallow function () {} in statement context, per ecma-262 edition 3. this behavior is the default in releases where this option has been removed. mxr id search for jsoption_anonfunfix jsoption_jit obsolete since jsapi 11 added in spidermonkey 1.8.1 enables the jit compilation of code in the context. note that you may currently (jan 2009) experience bugs with this option enabled. mxr id search for jsoption_jit jsoption_no_script_rval added in spidermonkey 1.8.1 by setting this option, the application promises to the compiler that a null rval out-param will be passed to each call to js_executescript. mxr id search for jsoption_no_script_rval ...
JSDBGAPI
the jsdbg api is obsolete and has been removed in spidermonkey 35. see bug 1069694. ...
...mefunctionobject js_isconstructorframe js_isdebuggerframe js_getframereturnvalue js_setframereturnvalue js_getframecalleeobject js_getscriptfilename js_getscriptbaselinenumber js_getscriptlineextent js_getscriptversion js_gettopscriptfilenameflags js_getscriptfilenameflags js_flagscriptfilenameprefix jsfilename_null jsfilename_system jsfilename_protected evaluating debug code js_evaluateinstackframe examining object properties typedef jspropertydesc jspd_enumerate jspd_readonly jspd_permanent jspd_alias jspd_argument jspd_variable jspd_exception jspd_error typedef jspropertydescarray js_propertyiterator js_getpropertydesc js_getpropertydescarray js_putpropertydescarray hooks js_setdebuggerhandler js_setsourcehandler js_setexecuteho...
Running Automated JavaScript Tests
r you can run all but selected tests with the --exclude option. now that the full set of test262 tests is included in the tree, jstests take a long time to complete. for a smoke test or if you are not changing language-level functionality, you may wish to use jstests.py path_to_js_shell --exclude=test262 other options allow you to show the test command lines being run, command output and return codes, run tests named in a given file, exclude tests named in a given file, hide the progress bar, change the timeout, run skipped tests, print output in tinderbox format, run a test in the debugger, or run tests in valgrind. run with the -h option to see all the options. the jstests test suite also includes some tests from web-platform-tests. by default, these are only run when no tests paths are s...
...ewing treeherder after a push to the mozilla repositories, jit-tests are run by calling make check, and appear under b. creating new tests for jit-tests creating new tests for jit-tests is easy. just add a new js file to the tests/basic directory (or any appropriate directory under 'tests'). the test harness will automatically find the test and run it. the test is considered to pass if the exit code of the js shell is zero (i.e., js didn't crash and there were no js errors). use the asserteq function to verify values in your test. there are some advanced options for tests. see the readme (in js/src/jit-tests) for details. ...
Using RAII classes in Mozilla
or in static storage. this involves just one addition to the class, and the inclusion of attributes.h: class moz_raii nsautoscriptblocker {...} this is much simpler and more thorough than the guardobject runtime assertions, but are unfortunately currently only run on mac os x and linux builds, which means that guardobject should still be used for raii guards which may be used in windows-only code. ...
...we have a set of macros that will cause a class to assert when it is instantiated at a temporary. they cause no extra complexity for users of the class, but they do slightly complicate the implementation of the class. ...
Exploitable crashes
t to look primarily for three things, in order: look at the top frame of the stack trace. if you see a hex address such as 0x292c2830 rather than a function name such as nslistboxbodyframe::getrowcount at the top of the stack, a bug has caused the program to transfer control to a "random" part of memory that isn't part of the program. these crashes are almost always exploitable to run arbitrary code. look at the crash reason, which will usually be something like "kern_protection_failure (0x0002) at 0x00000000". this is typically located right above the stack trace. the last number, in this case 0x00000000, is the memory address firefox was prevented from accessing. if the address is always zero (or close to zero, such as 0x0000001c), it's probably a null dereference bug. these bugs cause th...
...xploitable. most crashes fall into this category. check the length of the stack trace. if it's over 300 functions long, it's likely to be a too-much-recursion crash. like null dereferences, these crashes are not exploitable. any other crash where firefox tries to use memory it does not have access to indicates some kind of memory safety bug. these crashes can often be exploited to run arbitrary code, but you can't be as certain as in the case where you see a bogus address at the top of the stack in step 1. finding exploitable crashes exploitable crashes are most often discovered through normal testing and usage, when developers recognize a crash stack in gdb or submitted to a bug as exploitable. additionally, mozilla developers make heavy use of two tools in particular to find exploitable si...
Handling Mozilla Security Bugs
roup" by which mozilla contributors and others can participate in addressing security vulnerabilities in mozilla. this document describes how the new security organizational structure will work, and how security-related mozilla bug reports will be handled. note that the focus of this new structure is restricted solely to addressing actual security vulnerabilities arising from problems in mozilla code. this work is separate from the work of developers adding new security features (cryptographically-based or otherwise) to mozilla, although obviously many of the same people will be involved in both sets of activities. background security vulnerabilities are different from other bugs, because their consequences are potentially so severe: users' private information (including financial informati...
...d and acknowledge the concerns of those who believe that all information about security vulnerabilities should be publicly disclosed as soon as it is known, so that users may take immediate steps to protect themselves and so that problems can get the maximum amount of developer attention and be fixed as soon as possible. at the same time, the mozilla project receives substantial contributions of code and developer time from organizations that use (or plan to use) mozilla code in their own product offerings. some of these products may be used by large populations of end users, many of whom may not often upgrade or check for recent security fixes. we understand and acknowledge the concerns of those who believe that too-hasty disclosure of exploit details can provide a short-term advantage to po...
Task graph
how does this work? a "decision task" is created to decide what to do with the push. the decision task creates a lot of additional tasks. these tasks include build and test tasks, along with lots of other kinds of tasks to build docker images, build toolchains, perform analyses, check syntax, and so on. these tasks are arranged in a "task graph", with some tasks (e.g., tests) depending on others (builds). once its prerequisite tasks complete, a dependent task begins. the result of each task is sent to treeherder where developers and sheriffs can track the status of the push. ...
...uilds). once its prerequisite tasks complete, a dependent task begins. the result of each task is sent to treeherder where developers and sheriffs can track the status of the push. the outputs from each task, log files, firefox installers, and so on, appear attached to each task when it completes. these are viewable in the task inspector. all of this is controlled from within the gecko source code, through a process called task-graph generation. this means it's easy to add a new job or tweak the parameters of a job in a try push, eventually landing that change on an integration branch. the details of task-graph generation are documented in the source code itself, including a some quick recipes for common changes. ...
Embedded Dialog API
dll into or out of the library search path. other sets of dialogs and alerts, implemented in other components,can be overridden in exactly the same fashion. responsibilities of mozilla/gecko component authors writing replaceable dialogs dialogs posed by the browser ("up calls") any component which may be included in an embedded browser distribution and wishes to pose a dialog must group its ui (code which runs its dialogs) into a unique interface built just for that purpose. any such code which isn't already a component needs to be. all code which actually poses dialogs, if it does this directly using window.open, wants to be changed to go through the new interface. restated, in order for a piece of code's dialogs to be overrideable, they can't be implemented directly in the code. all ui-rel...
...nsipromptservice is the canonical example. of course this is a relatively simple example. more complex dialogs may themselves require their own interface. (examples to be added as they come online. ...
Using the Places history service
rer, flags for typed, hidden, and gecko flags (gecko flags is trunk only). the navhistory service has broken this into two tables (see history service design). the main url table stores the information about the page: url, host name, title, visit count, hidden, and typed. stored separately is the information specific to each visit. this information is called a "visit" in this document and in the code. a visit contains a reference to the url table for the page, the visit date, the transition type (typed, click, redirect, bookmark, etc.), a reference to the referring visit, and the session id. this separation of the global page information and the visit allows us to store information about each time the page was visited instead of just the last time. using the referrer information in each visi...
... you browse. the redirect flag is deprecated. see adddocumentredirect below. nsiglobalhistory3.adddocumentredirect: this is called by the docshell when a redirect occurs. it replaces the old redirect flag on adduri. it gives the old and new channels to the history service so that the source page of the redirect can be determined. nsibrowserhistory.addpagewithdetails: called by history importing code. new code should use nsinavhistoryservice.setpagedetails. nsinavhistoryservice.addvisit: this is an advanced function that allows the caller to set the exact referring visit, the time, the session, etc. it is designed for people writing synchronizing or backup services that need access to all the flags. under normal browsing, adduri and adddocumentredirect will infer this information for you. m...
The Publicity Stream API
use cases: 'adam got a high score in mafia wars', 'bethany bought a plane ticket to the caribbean', etc. activity is an object, formatted as per the fixme: deadlinkactivity streams open specification. onsuccess is a callback that will be invoked with no arguments if the activity is successfully posted. onerror is an error callback that will be invoked if the publicity fails. possible error codes include: denied - if the user refuses to publicize the activity permissiondenied - if the publicizing site is not allowed to post to the publicity stream networkerror - if the publicity server is unreachable activityparseerror - if the activity contains syntax errors (not proper json) invalidactivity - if the activity contains semantic errors (i.e. missing required properties) ...
...st be processed and condensed into an attractive, cohesive format for users (eg., multiple tweets show as 'adam tweeted 4 times'). onsuccess will be called with a single argument: a json list of the current user's socially relevant app activity in the fixme: deadlinkactivity streams open specification. onerror is an error callback that will be invoked if the installation fails. ...
Accessing the Windows Registry Using XPCOM
s registry values can have several data types, so you need to ensure that you read the correct type. you can check the type of a value using the method getvaluetype(). this method returns an integer indicating the data type of the value. the data types supported by this interface are defined as named constants on the interface as follows: type_none — probably not useful type_string — a unicode string value type_binary — binary data type_int — a 32 bit integer type_int64 — a 64 bit integer each of these types (except type_none) has a corresponding method to read the value data: readstringvalue() readbinaryvalue() readintvalue() readint64value() since javascript is a dynamically-typed language, you may wish to use the following code to handle all types of data. in this...
... .getservice(components.interfaces.nsiwindowsregistry); var id = wss.getregistryentry(wss.hklm, "software\\microsoft\\windows\\currentversion", "productid"); backwards compatibility if you need to support firefox 1.0 and other older browser versions, you should check to see which interfaces are available. ...
Generating GUIDs
x-xxxxxxxxxxxx, where each x stands for a hexadecimal digit. there are a number of tools that can be used to generate a guid in the canonical form. note: if you do choose to use an email-style id for your add-on, you probably don't want it to be a real email address, since it might attract spam. online tools generate guid online uuid (guid) generator on the web uuid generator for mozilla code (both idl and c++.h forms) you can get a guid from one of the bots (such as botbot, firebot) on #firefox irc channel by /msging "uuid" to them. windows windows users can use the guidgen tool from microsoft to obtain a guid. (this tool is also part of ms visual c++) linux use /usr/bin/uuidgen. this can be found in package uuid-runtime (debian). mac os x use /usr/bin/uuidgen. perl jkeis...
...this can be found in package uuid-runtime (debian). mac os x use /usr/bin/uuidgen. perl jkeiser's mozilla tools include a uuid generator with output format of both c++ and idl style. sfink's update-uuids will change the uuid for a given interface and all of its descendants, updating all *.idl files within a directory tree. nsiuuidgenerator a uuid can be generated from privileged mozilla code using nsiuuidgenerator. see the linked page for details. com/xpcom format when #define-ing iids and cids in mozilla c++ code, you generally use the following format: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx #define ns_...id \ { 0xxxxxxxxx, 0xxxxx, 0xxxxx, \ { 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx } } you can generate code in this format using one of the following tools. online tool...
Components.utils.evalInSandbox
the evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor. note: it's not safe to use evalinsandbox() to evaluate json strings; instead, use the techniques discussed in the article on json. you can also find firefox 3.5 specific information in using json in firefox. use to use evalinsandbox(), you must first create a sandbox object using its constructor, components.utils.sandbox. in the constructor you define the security principal for code running in the sandbox, and can make various properties available to code running in the sandbox. the sandbox will become the global scope object when you pass it to evalinsandbox(text, sandbox). you can import functions or objects into the sand...
...ult); // 17 console.log(mysandbox.x); // 7 operations on objects you insert into this sandbox global scope do not carry privileges into the sandbox: mysandbox.foo = components; // this will give a "permission denied" error components.utils.evalinsandbox("foo.classes", mysandbox); optional arguments you can optionally specify the js version, filename, and line number of the code being evaluated. for instance: var x = components.utils.evalinsandbox( "let x = 1;", sandbox, "1.8", // "latest" is recognized as a special case "http://foo.com/mycode.js", 25 ); the above will execute code using javascript 1.8. any exceptions raised by the evaluated code will show as originating from the above url. the evaluated code is assumed to start at line 25 of the document a...
Components.utils.isXrayWrapper
any expando properties are not visible, and if any native properties have been redefined, this has no effect. use this function to determine whether a given object is an xray or not. syntax boolean components.utils.isxraywrapper(obj); parameters obj the object to check. ...
...any expando properties are not visible, and if any native properties have been redefined, this has no effect. use this function to determine whether a given object is an xray or not. syntax boolean components.utils.isxraywrapper(obj); parameters obj the object to check. ...
Components.utils.schedulePreciseGC
this method lets scripts schedule a garbage collection cycle. the garbage collection cycle will occur sometime in the future, when no javascript code is executing. this is useful particularly when testing for memory leaks, because normal garbage collection is conservative when javascript code is running to ensure that in-use memory isn't inadvertently collected. note: garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. requires chrome privileges. ...
.... note: garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. requires chrome privileges. using scheduleprecisegc() when you call components.utils.scheduleprecisegc(), you specify a callback that is executed in once the scheduled garbage collection has been completed: components.utils.scheduleprecisegc( function() { // this code is executed when the garbage collection has completed } ); since the garbage collection doesn't occur until some time in the future (unlike, for example, components.utils.forcegc(), which causes garbage collection immediately but isn't able to collect all javascript-related memory), the callback lets you know when that's been finished. ...
Components.utils.unload
components.utils.unload was introduced in firefox 7 and is used to unload javascript code modules. this can be particularly handy with restartless (boostrapped) extensions, so that you can unload an old version of a code module when a new version of your add-on is installed. once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference. if the javascript code module has not yet been imported then this method will do nothing. you should not unload modules that are part of the application (anything under resource://gre/ or resource:/// or resource://app/) as these may be in use by other extensions and the application. only unload modules you include as part of your extension. syntax components.uti...
...:/// or resource://app/) as these may be in use by other extensions and the application. only unload modules you include as part of your extension. syntax components.utils.unload( url ); parameters url the "resource://" url of the script to unload. this must be the same url that was used to load the script. example you can unload a module called mymodule.jsm using the following line of code: components.utils.unload("resource://myaddon/modules/mymodule.jsm"); note: currently components.utils.unload clears the global object of an unloaded module. this may cause modules to misbehave after unloading even if you have a reference to them. see bug 769253 see also bug 481603 the documentation in xpccomponents.idl the tests in js/xpconnect/tests/unit/ ...
Profiling XPCShell
but then, you can't use the venkman ui. ...
...but then, you can't use the venkman ui. ...
XPCshell Test Manifest Expressions
ovided by the test harness via mozinfo.py, with many of the values initialized at configure time by writemozinfo.py which writes mozinfo.json into the root of the build directory. see also the official docs for this set of variables. ...
... you need something and it's not here, best check the source code! os - the operating system on which the test is being run one of: 'win', 'mac', 'linux', 'android' os_version - the version of the operating system on which the test is being run toolkit - the graphics toolkit used by this build one of: 'windows', 'cocoa', 'gtk2', 'android' processor - the cpu which the code is compiled for one of: 'x86', 'x86_64', 'arm' bits - the pointer size of the cpu architecture, in bits one of 32, 64, possibly unknown debug - set to true if this build is a debug build, false otherwise crashreporter - set to true if this build has crash reporting code enabled, false otherwise. comments if an expression contains a # (pound/hash) character outside of a...
NS_NewLocalFile
resolve symbolic links. this parameter has no effect on unix systems. on windows, passing true causes shortcuts to be automatically resolved, and on macos, passing true causes finder aliases to be automatically resolved. aresult [out] a reference to the newly created nsilocalfile instance. return values the ns_newlocalfile function returns ns_ok if successful. otherwise, it returns an error code. ...
...alfile instance. return values the ns_newlocalfile function returns ns_ok if successful. otherwise, it returns an error code. ns_error_file_unrecognized_path indicates that the specified path is invalid. this error is returned if a relative file path is passed to ns_newlocalfile. remarks on unix systems, the prefix "~/" is supported as a shorthand for the user's home directory. example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newlocalfile(nsembedstring(l"c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. nsembedstr...
nsresult
« xpcom api reference the nsresult data type is a strongly-typed enum used to represent a value returned by an xpcom function; these are typically error or status codes. for a list of defined result values, see error codes returned by mozilla apis. note: on compilers that do not support strongly-typed enums (that is, compilers that don't support this feature of c++11), it falls back to being an unsigned 32-bit integer, as in past versions of gecko. note: prior to gecko 19.0, nsresult was not strongly typed. as a result, it was possible for code to misuse it, such as returning an nsresult value from a function whose signature indicates it returns a boolean. because nsresult is strongly typed, code like the following will result in an error at compile time: bool foo() { ... ...
...r to gecko 19.0, nsresult was not strongly typed. as a result, it was possible for code to misuse it, such as returning an nsresult value from a function whose signature indicates it returns a boolean. because nsresult is strongly typed, code like the following will result in an error at compile time: bool foo() { ... if (something) { return ns_error_failure; } ... ...
Core XPCOM functions
...
... ...
IJSDebugger
js/ductwork/debugger/ijsdebugger.idlscriptable provides the javascript debugger service. you should usually interface with this using the javascript code module instead of directly. see the javascript debugger api guide for details. 1.0 66 introduced gecko 9.0 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) implemented by: @mozilla.org/jsdebugger;1 as a service: var jsdebugger = components.classes["@mozilla.org/jsdebugger;1"] .createinstance(components.interfaces.ijsdebugger); note: you should almost never directly use this service; instead, you should use the javascript code module that does this for you. the only time you should directly use this interface to create the debugger object...
...see the javascript debugger api guide for details on using the debugger api. ...
imgIContainerObserver
1.0 66 introduced gecko 1.7 inherits from: nsisupports last changed in gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9) if you wish to listen for activities on an imgicontainer, you should implement the framechanged() method. method overview void framechanged(in imgirequest arequest, in imgicontainer acontainer, [const] in nsintrect adirtyrect); native code only! methods native code only!framechanged called when the frame for an image container has changed. void framechanged( in imgirequest arequest, in imgicontainer acontainer, [const] in nsintrect adirtyrect ); parameters arequest the image request for which the change occurred. acontainer the image container that changed. adirtyrect a rectangle indicating th...
..., [const] in nsintrect adirtyrect ); parameters arequest the image request for which the change occurred. acontainer the image container that changed. adirtyrect a rectangle indicating the portion of the image container that changed. notes the arequest parameter was added to this method in gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9). see also imgidecoderobserver imgicontainer ...
mozIStorageFunction
led by the database engine when the function registered with mozistorageconnection.createfunction() is used in an executing sql statement or trigger. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code. likewise, if you execute sql on a different thread, this callback will be executed on that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! nsivariant onfunctioncall( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function. return value...
...k will be executed on that thread. this callback should be reentrant if any of the above applies to your use of the storage apis! nsivariant onfunctioncall( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function. return value an nsivariant this is the return value of the function. sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection. javascript starting in gecko 1.9.1.4 (firefox 3.0.15), you can directly pass your function into the mozistorageconnection method mozistorageconnection, like this: dbconn.createfunction("square", 1, function(aarguments) { let value = aarguments.getint32(0); return value * value; }); ...
mozIStorageService
the database. if this value is false, it is strongly recommended that the database be backed up with mozistorageconnection.backupdb() so user data is not lost. and then the database can be opened again with the mozistorageservice.opendatabase() method. warning: if you have more than one connection to a file, you must use the exact same name for the file each time, including case. the sqlite code uses a simple string comparison to see if there is already a connection. opening a connection to "foo.sqlite" and "foo.sqlite" will corrupt your database. if your database contains virtual tables (for example, for full-text indexes), you must use mozistorageservice.openunshareddatabase() to open it, since those tables are not compatible with a shared cache. if you use this method to open a datab...
...of sqlite that is incompatible with a shared cache, like virtual table and full text indexing support. if cache contention is expected, for instance when operating on a database from multiple threads, using unshared connections may be a performance win. warning: if you have more than one connection to a file, you must use the exact same name for the file each time, including case. the sqlite code uses a simple string comparison to see if there is already a connection. opening a connection to "foo.sqlite" and "foo.sqlite" will corrupt your database. note: the connection object returned by this function is not threadsafe. you must use it only from the thread you created it from. mozistorageconnection openunshareddatabase( in nsifile adatabasefile ); parameters adatabasefile ...
mozIVisitInfoCallback
toolkit/components/places/public/moziasynchistory.idlscriptable this interface provides callback handling functionality for moziasynchistory.updateplaces() 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) method overview void handleerror(in nsresult aresultcode, in moziplaceinfo aplaceinfo); void handleresult(in moziplaceinfo aplaceinfo); void oncomplete(in nsresult aresultcode, in moziplaceinfo aplaceinfo);obsolete since gecko 8.0 methods handleerror() called when a moziplaceinfo couldn't be processed. void handleerror( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason w...
...once). void handleresult( in moziplaceinfo aplaceinfo ); parameters aplaceinfo the information that was entered into the database. oncomplete() obsolete since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(). void oncomplete( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult of the change indicating success or failure reason. aplaceinfo the information that was being entered into the database. notes this method was replaced by the separate handleresult() and handleerror() methods in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). see also mozivisitinfo moziasynchistory ...
nsIAccessNode
e nsiaccessnode the next nsiaccessnode sibling. read only. obsolete since gecko 2.0 numchildren long the number of dom children for the dom node, which matches the number of nsiaccessnode children for this nsiaccessnode. read only. obsolete since gecko 2.0 ownerwindow voidptr the os window handle for the window this node is being displayed in. read only. native code only! obsolete since gecko 8.0 parentnode nsiaccessnode the parent nsiaccessnode. read only. obsolete since gecko 2.0 previoussiblingnode nsiaccessnode the previous nsiaccessnode sibling. read only. obsolete since gecko 2.0 rootdocument nsiaccessibledocument the root document accessible that this access node resides in. read only. uniqueid ...
... 2.0 previoussiblingnode nsiaccessnode the previous nsiaccessnode sibling. read only. obsolete since gecko 2.0 rootdocument nsiaccessibledocument the root document accessible that this access node resides in. read only. uniqueid voidptr a unique id calculated for this dom node, for the purposes of caching and referencing this object. read only. native code only! methods getchildnodeat() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) get the nth child of this node. nsiaccessnode getchildnodeat( in long childnum ); parameters childnum zero-based child index. return value the nth nsiaccessnode child. exceptions thrown ns_error_failure indicates that the access node is unattach...
nsIAppStartup
e. if one has not been made, this will create a browser window. void ensure1window( in nsicmdlineservice acmdlineservice ); parameters acmdlineservice the command line from which startup args can be read. enterlastwindowclosingsurvivalarea() serves for situations when all application windows will be closed but we don't want to take this as a signal to quit the application. bracket the code where the last window could close with these. void enterlastwindowclosingsurvivalarea(); parameters none. exitlastwindowclosingsurvivalarea() this method serves for situations when all application windows will be closed but we don't want to take this as a signal to quit the application. bracket the code where the last window could close with these. void exitlastwindowclosingsurvivalarea();...
... parameters aquitmode this parameter modifies how the app is shutdown. run() runs an application event loop: normally the main event pump which defines the lifetime of the application. if there are no windows open and no outstanding calls to enterlastwindowclosingsurvivalarea() this method will exit immediately. void run(); parameters none. return value returns ns_success_restart_app code. this return code indicates that the application should be restarted because quit was called with the erestart flag. see also nsicmdlineservice nsiappstartup_mozilla_2_0 ...
nsIAsyncInputStream
fication on any thread (possibly even recursively on the calling thread, that is synchronously), or specify that the notification be delivered to a specific event target. closewithstatus() this method closes the stream and sets its internal status. if the stream is already closed, then this method is ignored. once the stream is closed, the stream's status cannot be changed. ...
...tream is closed, the stream's status cannot be changed. any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close(). note: this method exists in part to support pipes, which have both an input end and an output end. if the input end of a pipe is closed, then writes to the output end of the pipe will fail. the error code returned when an attempt is made to write to a "broken" pipe corresponds to the status code passed in when the input end of the pipe was closed, which greatly simplifies working with pipes in some cases. void closewithstatus( in nsresult astatus ); parameters astatus the error that will be reported if this stream is accessed after it has been closed. ...
nsIAsyncOutputStream
fication on any thread (possibly even recursively on the calling thread, that is synchronously), or specify that the notification be delivered to a specific event target. closewithstatus() this method closes the stream and sets its internal status. if the stream is already closed, then this method is ignored. once the stream is closed, the stream's status cannot be changed. ...
...ream is closed, the stream's status cannot be changed. any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close(). note: this method exists in part to support pipes, which have both an input end and an output end. if the output end of a pipe is closed, then reads from the input end of the pipe will fail. the error code returned when an attempt is made to read to a "closed" pipe corresponds to the status code passed in when the output end of the pipe was closed, which greatly simplifies working with pipes in some cases. void closewithstatus( in nsresult reason ); parameters reason the error that will be reported if this stream is accessed after it has been closed. ...
nsIBrowserSearchService
access this service, use: var browsersearchservice = components.classes["@mozilla.org/browser/search-service;1"] .getservice(components.interfaces.nsibrowsersearchservice); attempting to use any method or attribute of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization. this is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup. if you need to write code that is executed during startup and makes use of nsibrowsersearchservice, you should make sure that this code is executed from the callback to init(). method overview void addengine(in astring engineurl, in ...
...n installed search engines. engines an array of the hidden installed nsisearchengines. init() initialize the service, or if the service is already initialized, do nothing. this method was introduced in firefox 16. attempting to call any method of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization. if your code requires nsibrowsersearchservice and is executed during startup, you should make sure that this code is executed from the callback to init(). void init( [optional] in nsibrowsersearchinitobserver observer ); parameters observer if specified, a callback called once initialization is complete, or immediately, if the service has already been initialized. in javascript, this observ...
nsIChannelEventSink
temporary redirect. the new uri may be identical to the old one. redirect_internal 1 << 2 this is an internal redirect, i.e. it was not initiated by the remote server, but is specific to the channel implementation. the new uri may be identical to the old one. methods asynconchannelredirect() called when a redirect occurs. this may happen due to an http 3xx status code. this method notifies the sink that a redirect is about to happen, but also to gives the sink the right to veto the redirect by throwing an exception or passing a failure code in the callback. note: vetoing the redirect simply means that newchannel will not be opened. it is important to understand that oldchannel will continue loading as if it received a response of http 200, which includes notif...
...of this method. exceptions thrown this method can throw any exception; if an exception occurs, the load will be canceled, and no network requests will occur for the new channel. the redirect will be canceled. onchannelredirect() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) called when a redirect occurs. this may happen due to an http 3xx status code. void onchannelredirect( in nsichannel oldchannel, in nsichannel newchannel, in unsigned long flags ); parameters oldchannel the channel that's being redirected. newchannel the new channel. this channel is not opened yet. flags flags indicating the type of redirect. a bitmask consisting of flags from above. one of redirect_temporary and redirect_permanent will al...
nsIConsoleService
called from the script. void getmessagearray( [optional] out pruint32 count, [retval, array, size_is(count)] out nsiconsolemessage messages ); parameters count the number of messages in the array. if no messages are logged, this function will return a count of 0, but allocating a placeholder word for messages, showing as a 0-length array when called from the script. note: see the code samples below for how to call getmessagearray. logmessage() void logmessage( in nsiconsolemessage message ); parameters message the nsiconsolemessage to log. logstringmessage() a convenient method for logging simple messages. void logstringmessage( in wstring message ); parameters message the string to log. registerlistener() registers a listener, to notify when an error ...
...he exact location of an error. acolumnnumber is used to draw the arrow pointing to the problem character. aflags — one of flags declared in nsiscripterror. at the time of writing, possible values are: nsiscripterror.errorflag = 0 nsiscripterror.warningflag = 1 nsiscripterror.exceptionflag = 2 and nsiscripterror.strictflag = 4. acategory — a string indicating what kind of code caused the error message. there are quite a few category strings and they do not currently seem to be listed in a single place. hopefully, they will all eventually be listed in nsiscripterror.idl. see also error console (deprecated) web console browser console nsiconsolemessage ...
nsIContentFrameMessageManager
tring aasciistring); domstring btoa(in domstring abase64data); dump() prints the specified string to standard output. parameters name type description astr string the message to log. atob() convert ascii base64 data to binary data. parameters name type description aasciistring string ascii string to decode. returns string: the decoded binary data. btoa() convert binary data to ascii base64 data . parameters name type description abase64data string binary data to encode as base64. returns string: the base64-encoded ascii string. attributes content nsidomwindow: the current top level window in the frame or null. read only. docshell nsidocshel...
... listeners who registered with services.mm.addmessagelistener get content message manager from browser this could would run in a nsidomwindow scope. var acfmm = gbrowser.selectedbrowser._docshell.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsicontentframemessagemanager); get content message manager from content window window here is a html window or any window inside a tab, this code would run from a framescript. var acfmm = window.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsidocshell) .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsicontentframemessagemanager); ...
nsIContentPrefService
preferences are saved as key/value pairs on a per-website basis. dom/interfaces/base/nsicontentprefservice.idlscriptable please add a summary to this article. last changed in gecko 2 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) inherits from: nsisupports implemented by: @mozilla.org/content-pref/service;1. ...
...nection mozistorageconnection the database connection to the content preferences database. useful for accessing and manipulating preferences in ways that are caller-specific or for which there is not yet a generic method, although generic functionality useful to multiple callers should generally be added to this unfrozen interface. also useful for testing the database creation and migration code. read only. grouper nsicontenturigrouper the component that the service uses to determine the groups to which uris belong. by default, this is the "hostname grouper," which groups uris by full hostname (in otherwords, by site). read only. methods addobserver() adds an observer that monitors a preference for changes. void addobserver( in astring aname, in nsicontentprefobs...
nsIContentSniffer
to read content from adata. ...
...ry { // this pref has been removed, see bug 910192 charset = services.prefs.getcomplexvalue("intl.charset.default", ci.nsipreflocalizedstring).data; } catch (e) { } let conv = cc["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(ci.nsiscriptableunicodeconverter); conv.charset = charset; try { let str = conv.convertfrombytearray(adata, alength); if (str.substring(0, 5) == "%pdf-") return "application/pdf"; // we detected a pdf file } catch (e) { // try to get information from arequest } ...
nsICrashReporter
ss to crash reporting functionality. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void annotatecrashreport(in acstring key, in acstring data); void appendappnotestocrashreport(in acstring data); void appendobjcexceptioninfotoappnotes(in voidptr aexception); native code only! void writeminidumpforexception(in voidptr aexceptioninfo); native code only! attributes attribute type description enabled boolean enable or disable the crashreporter at runtime. minidumppath nsilocalfile get or set the path on the local system to which minidumps will be written when a crash happens. exceptions thrown ns_error_not_initialized if crash reporting is not initia...
... "notes" field, to be submitted with a crash report. unlike annotatecrashreport(), this method will append to existing data. void appendappnotestocrashreport( in acstring data ); parameters data data to be added. exceptions thrown ns_error_invalid_arg if data contains invalid characters. the only invalid character is '\0'. ns_error_not_initialized if crash reporting not initialized. native code only!appendobjcexceptioninfotoappnotes append note containing an obj-c exception's info. void appendobjcexceptioninfotoappnotes( in voidptr aexception ); parameters aexception nsexception object to append note for. native code only!writeminidumpforexception write a minidump immediately, with the user-supplied exception information. this is implemented on windows only, because seh (structure...
nsIDOMHTMLSourceElement
ly manipulating this value after the page has loaded has no effect on the containing element; instead, change the src attribute of that element (audio or video) instead. type domstring the type attribute gives the type of the media resource, to help the user agent determine if it can play this media resource before fetching it. if specified, its value must be a valid mime type. the codecs parameter may be specified and might be necessary to specify exactly how the resource is encoded. media unimplemented domstring the media attribute gives the intended media type of the media resource, to help the user agent determine if this media resource is useful to the user before fetching it. its value must be a valid media query. example <video controls> <source s...
...d might be necessary to specify exactly how the resource is encoded. media unimplemented domstring the media attribute gives the intended media type of the media resource, to help the user agent determine if this media resource is useful to the user before fetching it. its value must be a valid media query. example <video controls> <source src="foo.webm" type="video/webm; codecs=&quot;vp9, opus&quot;"> your browser does not support the <code>video</code> element. </video> this example specifies that a video object with playback controls should be drawn, playing the file "foo.ogg". the type is specified as "video/ogg", and the source element also specifies that the video file uses the dirac and speex codecs. ...
nsIDOMProgressEvent
terface represents the events sent with progress information while uploading data using the xmlhttprequest object. 1.0 66 introduced gecko 1.9.1 deprecated gecko 22 inherits from: nsidomevent last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) the nsidomprogressevent is used in the media elements (<video> and <audio>) to inform interested code of the progress of the media download. this implementation is a placeholder until the specification is complete, and is compatible with the webkit progressevent. method overview void initprogressevent(in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in boolean lengthcomputablearg, in unsigned long long loadedarg, in unsigned long long totalarg); deprecated since...
...gned long long the total number of bytes of content that will be transferred during the operation. if the total size is unknown, this value is zero. read only. methods initprogressevent() deprecated since gecko 22.0 this method has been removed from use in javascript in gecko 22.0. use the regular constructor to construct a synthetic progressevent. it still is usable from native c++ code. initializes the progress event object. void initprogressevent( in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in boolean lengthcomputablearg, in unsigned long long loadedarg, in unsigned long long totalarg ); parameters typearg the type of event. must be one of "abort", "error", "load", "loadstart", or "progress". canbubblearg specifies whether or...
nsIDataSignatureVerifier
return value true if the signature matches the data, false if not. ...
...ring asignature, in acstring apublickey); methods verifydata() verifies that the data matches the data that was used to generate the signature. boolean verifydata( in acstring adata, in acstring asignature, in acstring apublickey ); parameters adata the data to be tested. asignature the signature of the data, base64 encoded. apublickey the public part of the key used for signing, der encoded then base64 encoded. return value true if the signature matches the data, false if not. ...
nsIDocumentLoader
documentchannel nsichannel read only. loadgroup nsiloadgroup read only. methods ...
...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. void getcontentviewercontainer( in nsisupports adocumentid, out nsicontentviewercontainer aresult ); parameters adocumentid ...
nsIDownloadProgressListener
/toolkit/components/downloads/nsidownloadprogresslistener.idlscriptable this interface gives applications and extensions a way to monitor the status of downloads being processed by the download manager. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) to use simply implement this interface in your code, then call nsidownloadmanager.addlistener() to start listening. when you no longer need to listen to the download manager's state, call nsidownloadmanager.removelistener() to stop listening. as the states of downloads change, the methods described here are called by the download manager so your code can take whatever steps it needs to. this interface works very similarly to the nsiwebprogress interface. it is important to n...
... see also nsidownloadmanager nsidownload nsiwebprogresslistener ...
nsIDragSession
p originated in the same document. read only. sourcenode nsidomnode the dom node that was originally dragged to start the session, which will be null if the drag originated outside the application. read only. targetsize nssize sets the current width and height of the drag target area. it will contain the current size of the frame that the drag is currently in. native code only! methods getdata() gets data from a drag and drop operation. can be called while the drag is in process or after the drop has completed. void getdata( in nsitransferable atransferable, in unsigned long aitemindex ); parameters atransferable the transferable for the data to be put into. aitemindex which of multiple drag items, zero-based. must be less than numdropitems. ...
...opitems. isdataflavorsupported() checks to see if any of the native data on the clipboard matches a given data flavor. if numdropitems is greater than one, there is no indication as to which of the items matches the data flavor. boolean isdataflavorsupported( in string adataflavor ); parameters adataflavor a string representing the mime type of the data to be matched, such as "text/unicode". return value true if the specified flavor matches any of the native data on the clipboard, otherwise false. ...
nsIEditorSpellCheck
oolean 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 getcurrentdictionary(); parameters none. return value the name of the dictionary currently in use. typically, this is an iso language code, such as "en-us". getdictionarylist() retrieves a list of the currently available dictionaries. the strings will typically be language ids, such as "en-us". void getdictionarylist( [array, size_is(count)] out wstring dictionarylist, out pruint32 count ); parameters dictionarylist an array into which the list of dictionary name strings are placed. count on return, contains th...
...refox 9.0 / thunderbird 9.0 / seamonkey 2.6). since spelling dictionaries can now be selected per-site, this method is no longer needed. void savedefaultdictionary(); parameters none. setcurrentdictionary() selects the main dictionary to use. void setcurrentdictionary( in astring dictionary ); parameters dictionary the name of the dictionary to use. typically, this is an iso language code such as "en-us". setfilter() used to filter the content (for example, to skip blockquotes in email from spell checking). call this before calling initspellchecker(); calling it after initialization will have no effect. void setfilter( in nsitextservicesfilter filter ); parameters filter an nsitextservicesfilter describing the filter to apply. this filter lets you avoid spell checking...
nsIEventTarget
lement this interface in order to support receiving events from other threads. 1.0 66 introduced gecko 1.6 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void dispatch(in nsirunnable event, in unsigned long flags); boolean isoncurrentthread(); void postevent(in pleventptr aevent); native code only! obsolete since gecko 1.9 constants dispatch flags constant value description dispatch_normal 0 this flag specifies the default mode of event dispatch, whereby the event is simply queued for later processing. when this flag is specified, dispatch() returns immediately after the event is queued. dispatch_sync ...
...s that event is null. isoncurrentthread() check to see if this event target is associated with the current thread. boolean isoncurrentthread(); parameters none. return value returns true if events dispatched to this event target will run on the current thread (that is, the thread calling this method). if events dispatched to this target will be processed on another thread, returns false. native code only!postevent 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. method for posting an asynchronous event to the event target. if this method succeeds, then the event will be dispatched on the target thread. void postevent( in pleventptr aevent ); para...
nsIFeedContainer
ry objects, except that interface has not been implemented yet. contributors nsiarray an array of nsifeedperson objects describing contributors to the feed or entry. fields nsiwritablepropertybag2 provides access to all the fields found in the document. common atom and rss fields are normalized, including some namespaced extensions such as "dc:subject" and "content:encoded". consumers can avoid normalization by checking the feed type and accessing specific fields. common namespaces are accessed using prefixes, such as get("dc:subject");. see nsifeedresult.registerextensionprefix() for more information about prefixes. id astring a string that identifies the feed or entry. not all feeds have these, but all major feed formats have ids for each ...
... the feed or entry's rights or license text. title nsifeedtextconstruct the feed or entry's title. keep in mind that some feeds have no title, and some use markup in their titles, so be cautious when decoding this attribute. updated astring a string containing the date the feed or entry was last updated, in rfc822 form. this string is parsable by javascript and mail code. methods normalize() synchronizes a container's fields with its convenience attributes. void normalize(); parameters none. see also nsiuri nsifeedtextconstruct interwiki link ...
nsIFeedEntry
oviding attributes allowing access to the entry's data. 1.0 66 introduced gecko 1.8 inherits from: nsifeedcontainer last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) attributes attribute type description content nsifeedtextconstruct the full text of the entry's content. this comes from the atom:content and/or content:encoded fields. enclosures nsiarray an array of all the enclosures included in the entry. these are used by podcasts, photocasts, and so forth. mediacontent nsiarray an array of all the enclosures or other media that might be displayed inline in the entry. parent nsifeedcontainer a reference to the entry's parent, which is either a feed (nsifeed or another en...
... an array of all the enclosures or other media that might be displayed inline in the entry. parent nsifeedcontainer a reference to the entry's parent, which is either a feed (nsifeed or another entry. published astring a string indicating the date on which the entry was published, in rfc822 format. this date is parsable by both javascript (via date.parse()) and mail code. note, that the related updated attribute is available from the nsifeedcontainer interface. summary nsifeedtextconstruct a summary of the feed entry's content. this is generated automatically using the entry's description, subtitle, summary, content, and appropriate extensions. see also nsifeedcontainer interwiki lin ...
nsIFilePicker
sions may be included, separated by a semicolon and a space. example some example filter strings: "*.ics" "*.txt; *.doc; *.rtf" appendfilters() appends a list of file extension filters, from the predefined list, to the dialog. void appendfilters( in long filtermask ); parameters note: if appendfilters is the first (or only) call to set the file filters the filter with the smallest code will be used as default filter when displaying the nsifilepicker dialog. if you would like to use another you must append it separately before the others you want to go into the drop down list. filtermask a combination of the filters you wish to use. you may or multiple filters together; for example filterall | filterhtml. init() initialize the file picker widget. the file picker is not va...
...cker.modeopen); fp.appendfilters(nsifilepicker.filterall | nsifilepicker.filtertext); fp.open(function (rv) { if (rv == nsifilepicker.returnok || rv == nsifilepicker.returnreplace) { var file = fp.file; // get the path as string. note that you usually won't // need to work with the string paths. var path = fp.file.path; // work with returned nsilocalfile... } }); if your code is a component and window is not defined, you can get one using nsiwindowmediator. when selecting multiple files: .... fp.init(window, "dialog title", nsifilepicker.modeopenmultiple); .... var files = fp.files; var paths = []; while (files.hasmoreelements()) { var arg = files.getnext().queryinterface(components.interfaces.nsilocalfile).path; paths.pu...
nsIHttpServer
hile the server is running the handler * throws an exception while responding to a request, an http 500 response * will be returned * @throws ns_error_invalid_arg * if path does not begin with a "/" or does not end with a "/" */ void registerprefixhandler(in string prefix, in nsihttprequesthandler handler); /** * registers a custom error page handler. * * @param code * the error code which is to be handled by handler * @param handler * an object which will handle any requests which generate the given status * code, or null to remove any existing handler. if the handler throws an * exception during server operation, fallback is to the genericized error * handler (the x00 version), then to 500, using a user-defined error * hand...
...er default handler otherwise. fallback * will never occur from a user-provided handler that throws to the same * handler as provided by the server, e.g. a throwing user 404 falls back to * 400, not a server-provided 404 that might not throw. * @note * if the error handler handles http 500 and throws, behavior is undefined. */ void registererrorhandler(in unsigned long code, in nsihttprequesthandler handler); /** * maps all requests to paths beneath path to the corresponding file beneath * dir. * * @param path * the absolute path on the server against which requests will be served * from dir (e.g., "/", "/foo/", etc.); must begin and end with a forward * slash * @param dir * the directory to be used to serve all requests for pat...
nsIINIParserFactory
e); methods createiniparser() creates an ini parser, returning the nsiiniparser object that you can use to parse it. nsiiniparser createiniparser( in nsilocalfile ainifile ); parameters ainifile the ini file to parse. return value the nsiiniparser object you can use to parse the ini file. ...
...ou can use to parse it. nsiiniparser createiniparser( in nsilocalfile ainifile ); parameters ainifile the ini file to parse. return value the nsiiniparser object you can use to parse the ini file. ...
nsIMsgMessageService
te it to a string. amsgwindow nsimsgwindow for progress and status feedback. aurllistener an nsiurllistener that is notified when url starts and stops. aconvertdata if aconvertdata is true, it will create a stream converter from message rfc2822 to */*. aadditionalheader header added to the uri. ...
...nsimsgwindow for progress and status feedback. aurllistener an nsiurllistener that is notified when url starts and stops. aconvertdata if aconvertdata is true, it will create a stream converter from message rfc2822 to */*. aadditionalheader header added to the uri. ...
nsINavHistoryObserver
/ thunderbird 3.3 / seamonkey 2.1) note: this method was removed in gecko 2.0. use ondeletevisits() instead. called when a history entry expires. this notification is sent to indicate that a specific visit has expired, and includes the time of that visit. when the last visit for a history entry expires, the history entry itself is deleted and the awholeentry parameter is true. if your code only cares about whole entries being deleted instead of individual visits, you can simply act only when awholeentry is true. it's possible for a history entry to be deleted even though it has no visits if something is out of sync after a bookmark with no visits is deleted; this results in the entire history entry being freed). in such cases, avisittime is 0. void onpageexpired( in nsiuri auri, ...
...d each time it is called, since often consumers will want to display the user title if available, falling back to the title specified by the page's <title> element if there is no user title. it's important to note that there is a difference between an empty title and a null title. an empty string means the title was specifically set to be nothing. null means the title was not set at all. from c++ code, use the isvoid() and setisvoid() methods to see whether an empty string is "null" or not; in either case it will always be an empty string. void ontitlechanged( in nsiuri auri, in astring apagetitle ); parameters auri the uri of the page whose title changed. apagetitle the new title of the page. onvisit() called when a resource is visited. this is called the first time a r...
nsIPlacesView
rather, each view is responsible for translating its own selection format into one the controller can understand. ...
...rather, each view is responsible for translating its own selection format into one the controller can understand. ...
nsIProfile
.getservice(components.interfaces.nsiprofile); note: this interface was used by seamonkey up through seamonkey 1.1 versions, which were based off gecko 1.8.1. however, it hasn't been used in firefox since before firefox 1.0. ...
...eating a copy of it with a new name. void cloneprofile( in wstring profilename ); parameters profilename the name to assign to the new clone of the current profile. createnewprofile() creates a new profile. appropriate default values will be copied into the preferences in the new profile. void createnewprofile( in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir ); parameters profilename the name to assign to the new profile. nativeprofiledir the pathname of the directory to use as the profile directory; if you specify null, a new folder will be created in the default profiles directory. langcode the locale to use for the new profile. useexistingdir if true, an existing directory may be used;...
nsIProgressEventSink
status message for the given request. void onstatus( in nsirequest arequest, in nsisupports acontext, in nsresult astatus, in wstring astatusarg ); parameters arequest the request being observed (may qi to nsichannel). acontext if arequest is a channel, then this parameter is the listener context passed to nsichannel.asyncopen(). astatus status code (not necessarily an error code) indicating the state of the channel (usually the state of the underlying transport). see nsisockettransport for socket specific status codes. astatusarg status code argument to be used with the string bundle service to convert the status message into localized, human readable text. the meaning of this parameter is specific to the value of the status c...
...ror code) indicating the state of the channel (usually the state of the underlying transport). see nsisockettransport for socket specific status codes. astatusarg status code argument to be used with the string bundle service to convert the status message into localized, human readable text. the meaning of this parameter is specific to the value of the status code. for socket status codes, this parameter indicates the host:port associated with the status code. ...
nsIScreenManager
read only. primaryscreen nsiscreen the primary display screen; this is the screen with the menu bar (on the mac) or taskbar or equivalent on windows or linux. read only. methods ...
... nsiscreen screenforrect( in long left, in long top, in long width, in long height ); attributes attribute type description numberofscreens unsigned long the number of screens on the user's computer. read only. primaryscreen nsiscreen the primary display screen; this is the screen with the menu bar (on the mac) or taskbar or equivalent on windows or linux. read only. methods native code only!screenfornativewidget returns the nsiscreen instance for the native widget pointer. this pointer's definition is specific to the platform's native widget implementation, and is typically of the same type as ns_native_window. nsiscreen screenfornativewidget( in voidptr nativewidget ); parameters nativewidget the native widget for which to obtain an nsiscreen instance. return value the n...
nsISelection2
read only. methods getrangesforinterval() return array of ranges intersecting with the given...
...noffset endnode endoffset these four parameters represent the range to compare against the selection. allowadjacent specifies whether the returned ranges are allowed to touch the input range rather than merely overlapping it. resultcount returns the number of ranges that overlap (or touch) the input range. results returns the ranges that overlap (or touch) the input range. native code only!getrangesforintervalcomarray void getrangesforintervalcomarray( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results ); parameters beginnode beginoffset endnode endoffset these four parameters represent the range to compare against the selection. allowadjacent specifies wh...
nsISessionStore
the api operates on top-level browser.xul and navigator.xul windows; see note on windows for details. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in versions of firefox prior to 3.5, the user preference browser.sessionstore.enabled must be true for these calls to be successful. starting in firefox 3.5, this preference is no longer used. ...
...nt to use in nsisessionstore, you need a nsidomwindow object containing browser.xul. this will be the outermost or root nsidomwindow in a nsixulwindow (the window seen by users as a moveable frame on the display). this kind of domwindow object can be obtained from other nsidomwindow objects (like the sidebar window object) by applying the 'mainwindow' statement from working_with_windows_in_chrome_code. this outermost or root window can also be obtained from the list returned by nsiwindowmediator; see example #3 in working_with_windows_in_chrome_code. it can also be obtained from an nsixulwindow using if (xul_win.docshell instanceof nsiinterfacerequestor) { var win = xul_win.docshell.getinterface(nsidomwindow); ... note on tabs the nsisessionstore apis referencing nsidomnode atab re...
nsISound
please use the html 5 <audio> tag instead. note that nsisound instances may play the sounds using another thread; however, this is not controlled by the caller. implemented by: @mozilla.org/sound;1. ...
...d to. void init(); parameters none. play() plays a sound specified by url. void play( in nsiurl aurl ); parameters aurl the url of the sound file to play. playeventsound() plays the system sound for the specified event. if the user's system is configured to not play system sound effects for the event, this will do nothing. warning: this method should not be used in modern code. please use the html 5 <audio> tag instead. void playeventsound( in unsigned long aeventid ); parameters aeventid an event id which is defined in the constants. playsystemsound() plays the system sound whose name is specified. if the user's system is configured to not play system sound effects, this will do nothing. note: this function is not supported on the macintosh. voi...
nsISpeculativeConnect
1.0 66 introduced gecko 15.0 inherits from: nsisupports last changed in gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) to use this service, simply call nsisupports.queryinterface() on the nsiioservice you plan to use for the connection, to get access to the i/o service's implementation of nsispeculativeconnect. ...
...culativeconnect. then call speculativeconnect() to let the networking layer know what you might be doing in the future. method overview void speculativeconnect(in nsiuri auri, in nsiinterfacerequestor acallbacks, in nsieventtarget atarget); methods speculativeconnect() call this method to hint to the networking layer that a new transaction for the specified uri is likely to happen soon. the code implementing this method may use this information to start a tcp and/or ssl level handshake for that resource immediately so that it is ready (or at least in the process of becoming ready) when the transaction is actually submitted. no obligation is taken on by the implementer, nor is the submitter obligated to actually open the new channel. void speculativeconnect( in nsiuri auri, in nsiinte...
nsIStringBundle
); nsisimpleenumerator getsimpleenumeration(); wstring getstringfromid(in long aid); wstring getstringfromname(in wstring aname); methods formatstringfromid() returns a formatted string with the given id from the string bundle, where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array. you may also use other formatting codes. you can only pass unicode strings in. the id should refer to a string in the bundle that uses %s, and the number of strings you pass must be the same here and in the properties file (that is you can't omit %1 and use only %2). do not try to use any other types. this uses nstextformatter::smprintf. wstring formatstringfromid( in long aid, [array, size_is(length)] in wstring params, in uns...
...d of the string to retrieve. params parameters to pass in to the string. length the length of the parameter list. return value returns the formatted string. formatstringfromname() returns a formatted string with the given key name from the string bundle, where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array. you may also use other formatting codes, but can only pass unicode strings in. the name should refer to a string in the bundle that uses %s, and the number of strings you pass must be the same here and in the properties file (that is you can't omit %1 and use only %2). do not try to use any other types. this uses nstextformatter::smprintf to do the dirty work. wstring formatstringfromname( in wstring aname, [array, size_is(length...
nsIStringBundleService
n value an extensible bundle corresponding to the properties file(s). flushbundles() flushes the string bundle cache - useful when the locale changes or when we need to get some extra memory back. (automatically called for the memory-pressure and chrome-flush-caches global observer topics.) void flushbundles(); parameters none. formatstatusmessage() formats a message string from a status code and status arguments. typically used to format a message received by a nsiprogresseventsink's onstatus method. wstring formatstatusmessage( in nsresult astatus, in wstring astatusarg ); parameters astatus the status code. this is mapped into a string id and and used in the string lookup process (see nsierrorservice). astatusarg the status message argument(s). multiple arguments can b...
... onstatus method. wstring formatstatusmessage( in nsresult astatus, in wstring astatusarg ); parameters astatus the status code. this is mapped into a string id and and used in the string lookup process (see nsierrorservice). astatusarg the status message argument(s). multiple arguments can be separated by newline ('\n') characters. return value the formatted message. see also code snippets : miscellaneous : using string bundles from javascript how to localize html pages, xul files, and js/jsm files from bootstrapped add-ons. the localizing js/jsm files uses the nsistringbundleservice: bootstrapped extensions :: localization (l10n) nsistringbundle ...
nsIStructuredCloneContainer
ast changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) you can copy an object into an nsistructuredclonecontainer using initfromvariant() or initfrombase64(). it is an error to initialize an nsistructuredclonecontainer more than once. once you've initialized the container, you can get a copy of the object it stores by calling deserializetovariant(). you can also get a base-64-encoded string containing a copy of the container's serialized data, using getdataasbase64(). method overview nsivariant deserializetovariant(); astring getdataasbase64(); void initfrombase64(in astring adata,in unsigned long aformatversion); void initfromvariant(in nsivariant adata); attributes attribute type description formatversion unsigned long get the version of the structured clo...
...ffer. read only. serializednbytes unsigned long long get the size in bytes of this container's serialized data. read only. methods deserializetovariant() deserialize the object this container holds, returning it wrapped as an nsivariant. nsivariant deserializetovariant(); parameters none. return value an nsivariant. getdataasbase64() get this structured clone container's data as a base-64-encoded string. astring getdataasbase64(); parameters none. return value a base-64-encoded string. initfrombase64() initialize this structured clone container from a base-64-encoded byte stream. void initfrombase64( in astring adata, in unsigned long aformatversion ); parameters adata a base-64-encoded byte stream. aformatversion the version of the structured clone algorithm which was used to gen...
nsISupports proxies
obsolete since gecko 12 (firefox 12 / thunderbird 12 / seamonkey 2.9)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. xpcom proxies were a technology which allowed code to make asynchronous or synchronous xpcom calls to a different thread on arbitrary xpcom interfaces. this technology has been removed in firefox 12 because it was very complex and often lead to strange deadlock conditions. it is no longer needed because javascript code can no longer run on arbitrary threads, and compiled code can use compiled runnable to achieve the same effect in a much simpler manner. for more information about alternatives, see making cross-thread calls using runnables. the following interf...
...h enables a method of any class which is derived from nsisupports and has a typelib to be called on any in-process thread. the main reason for nsisupports proxies is that javascript and ui are on a single thread. when one is busy, the other is blocked. a good example of this is the old install.js scripts that were used in xpinstall in older mozilla versions. they from the majority of javascript code, which is small and can be quickly run. xpinstall installation scripts are sometimes very complex and can require long execution time due to unzipping or native file system actions. if xpinstall ran on the ui thread, the product would appear frozen until the script was complete. this is definitely bad. because of this, xpinstall was moved to its own thread. now xpinstall can do its installations ...
nsIThreadManager
the nsithreadmanager interface lets applications and extensions create and manage threads, each of which is represented by an nsithread. xpcom/threads/nsithreadmanager.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview nsithread getthreadfromprthread(in prthread prthread); native code only! nsithread newthread(in unsigned long creationflags); attributes attribute type description currentthread nsithread the currently executing thread. if the calling thread does not already have a nsithread associated with it, one is created and associate with the current prthread. read only. ismainthread boolean this attribute is true if the call...
...he currently executing thread. if the calling thread does not already have a nsithread associated with it, one is created and associate with the current prthread. read only. ismainthread boolean this attribute is true if the calling thread is the main thread of the application process. read only. mainthread nsithread the main thread. read only. methods native code only!getthreadfromprthread given a prthread, this method returns the corresponding nsithread. returns null if there isn't a corresponding nsithread. nsithread getthreadfromprthread( in prthread prthread ); parameters prthread the prthread for which to retrieve the corresponding nsithread. return value the nsithread matching the specified prthread, or null if there is no matching nsit...
nsITimer
ed. method overview void cancel(); void init(in nsiobserver aobserver, in unsigned long adelay, in unsigned long atype); void initwithcallback(in nsitimercallback acallback, in unsigned long adelay, in unsigned long atype); void initwithfunccallback(in nstimercallbackfunc acallback, in voidptr aclosure, in unsigned long adelay, in unsigned long atype); native code only! attributes attribute type description callback nsitimercallback the nsitimercallback object passed to initwithcallback(). read only. closure voidptr the opaque pointer pass to initwithfunccallback(). read only. native code only! delay unsigned long the timeout delay in millisecond. note: re-setting the delay on a ...
... call. void initwithcallback( in nsitimercallback acallback, in unsigned long adelay, in unsigned long atype ); parameters acallback an nsitimercallback interface to call when timer expires. adelay timeout delay in milliseconds. atype defines the timer type: one shot, repeating slack or repeating precise. must be one of the constants defined under constants on this page. native code only!initwithfunccallback initialize a timer to fire after the given millisecond interval. this version takes a function to call and a closure to pass to that function. void initwithfunccallback( in nstimercallbackfunc acallback, in voidptr aclosure, in unsigned long adelay, in unsigned long atype ); parameters acallback a nstimercallbackfunc interface compatible function to call ...
nsITreeColumn
the nsitreecolumn interface represents a tree column. layout/xul/base/src/tree/public/nsitreecolumns.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void getidconst([shared] out wstring idconst); native code only! nsitreecolumn getnext(); nsitreecolumn getprevious(); void invalidate(); attributes attribute type description atom nsiatom the atom attribute of nsitreecolumn which returns an nsiatom for the column, making it fast to do comparisons. read only. native code only! columns nsitreecolumns the nsitreecolumns containing this column. read only. cycler boolean if true, then the column is a cycler column. if the cycler attribute is not set, the column cells are regular text cel...
...e. read only. type short the type of the column, see constants. read only. width long the width of nsitreecolumn. read only. x long the x position in the tree of the left edge of the nsitreecolumn. read only. constants constant value description type_text 1 text column type. type_checkbox 2 checkbox column type. type_progressmeter 3 progress meter column type. methods native code only!getidconst void getidconst( [shared] out wstring idconst ); parameters idconst getnext() get the next column in the nsitreecolumns. nsitreecolumn getnext(); parameters none. return value the next nsitreecolumn in the nsitreecolumns. getprevious() get the previous column in the nsitreecolumn. nsitreecolumn getprevious(); parameters none. return value the previous nsitreecolumn in the ...
nsIURL
if the url denotes a path to a directory and not a file, for example http://host/foo/bar/, then the directory attribute ac...
... this if it can be made relative to the uri passed in. ...
nsIUUIDGenerator
nsidptr generateuuid(); parameters none. return value this method returns a nsidptr containing a unique id. exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not availabl...
...ethods generateuuid() obtains a new uuid using appropriate platform-specific methods to obtain a nsid that can be considered to be globally unique. nsidptr generateuuid(); parameters none. return value this method returns a nsidptr containing a unique id. exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtain a new uuid like the generateuuid() method, but place it in the provided nsid pointer instead of allocating a new nsid. void generateuuidinplace( in nsnonconstidptr id ); parameters id an existing nsid pointer where the uuid will be stored. exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is no...
nsIVersionComparator
+" then "number-a" is incremented by 1 and "string-b" becomes "pre". 1.0pre1 < 1.0pre2 < 1.0 == 1.0.0 == 1.0.0.0 < 1.1pre == 1.1pre0 == 1.0+ < 1.1pre1a < 1.1pre1 < 1.1pre10a < 1.1pre10 implemented by: @mozilla.org/xpcom/version-comparator;1. the service can be accessed directly via services.vc after loading services.jsm or with the following code: var versioncomparator = components.classes["@mozilla.org/xpcom/version-comparator;1"] .getservice(components.interfaces.nsiversioncomparator); method overview long compare(in acstring a, in acstring b); methods compare() compare two version strings. long compare( in acstring a, in acstring b ); parameters a the first version. b ...
...see here: nsixulappinfo components.utils.import("resource://gre/modules/services.jsm"); var curentbrowserversion = services.appinfo.platformversion; //example: '31.*' var comparetothisversion = '25.*'; var compareresult = services.vc.compare(curentbrowserversion, comparetothisversion); if (compareresult == -1) { //currentbrowserversion is less than '25.*' (comparetothisversi...
nsIWebBrowserChrome
methods destroybrowserwindow() asks the implementer to destroy the window associated with this webbrowser object. void destroybrowserwindow(); parameters none. exitmodaleventloop() exit a modal event loop if we're in one. the implementation should also exit out of the loop if the window is destroyed. void exitmodaleventloop( in nsresult astatus ); parameters astatus the result code to return from showasmodal(). iswindowmodal() is the window modal (that is, currently executing a modal loop)? boolean iswindowmodal(); parameters none. return value true if it's a modal window. setstatus() called when the status text in the chrome needs to be updated. void setstatus( in unsigned long statustype, in wstring status ); parameters statustype indicates what is setting...
...d when the status text in the chrome needs to be updated. void setstatus( in unsigned long statustype, in wstring status ); parameters statustype indicates what is setting the text. status status string. null is an acceptable value meaning no status. showasmodal() shows the window as a modal window. void showasmodal(); parameters none. return value note: the function error code returned by this corresponds to the status value specified in exitmodaleventloop. sizebrowserto() tells the chrome to size itself such that the browser will be the specified size. void sizebrowserto( in long acx, in long acy ); parameters acx new width of the browser. acy new height of the browser. ...
nsIWebContentHandlerRegistrar
nted to the user as a string. contentwindow the dom content window from which the method has been called. note: script must execute from same domain as uri or else it will throw permission error. can bypass this by opening about:config and setting preference of gecko.handlerservice.allowregisterfromdifferenthost to true. examples register a webmail service as mailto handler the following code aims to add "outlook.com live mail" to list of webservice handlers. in the image below "gmail" and "yahoo! mail" already exist as webservice handlers. cu.import('resource://gre/modules/services.jsm'); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getservice(ci.nsiwebcontenthandlerregistrar); var htmlcontentwindow = undefined; var regis...
...rmission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler' when calling method: [nsiwebcontenthandlerregistrar::registerprotocolhandler] if the host names do match then a confirmation like this will be seen: this domain check can be bypassed by setting the preference of gecko.handlerservice.allowregisterfromdifferenthost to true as in this code here: var {classes: cc, interfaces: ci, utils: cu} = components; cu.import("resource://gre/modules/services.jsm"); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getservice(ci.nsiwebcontenthandlerregistrar); var allowregisterfromdifferenthost = services.prefs.getboolpref('gecko.handlerservice.allowregisterfromdifferenthost'); if (!allowreg...
nsIWebNavigationInfo
is configured by using nsiwebbrowsersetup). return value returns one of the support type constants, indicating whether or not the specified mime type is supported, and in what form that support exists. ...
...rt type constants, indicating whether or not the specified mime type is supported, and in what form that support exists. ...
nsIXFormsNSInstanceElement
nsixformsnsinstanceelement is implemented by all xforms <instance/> elements, defining mozilla extensions. extensions/xforms/nsixformsnsinstanceelement.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) interface code [scriptable, uuid(80669b92-8331-4f92-aaf8-06e80e6827b3)] interface nsixformsnsinstanceelement : nsisupports { nsidomdocument getinstancedocument(); }; methods getinstancedocument nsidomdocument getinstancedocument(); getinstancedocument returns a dom document that corresponds to the instance data associated with the instance element. essentially it is just a shortcut to nsixformsmodelelement::getinstancedocument() for the given instance element. related interfaces nsixformsmodeleleme...
... ...
nsIXULTemplateBuilder
d. the default conditions specified inside the <rule> tag are applied before the rule filter is applied, meaning that the filter may be used to further filter out results but not reaccept results that have already been rejected. void addrulefilter( in nsidomnode arule, in nsixultemplaterulefilter afilter ); parameters arule the rule to apply the filter to. afilter the filter to add. ...
...[noscript] void createcontents( in nsicontent aelement, in boolean aforcecreation ); parameters aelement the element whose contents need to be built. ...
nsIXULWindow
underbird 3.3 / seamonkey 2.1) an nsixulwindow is created as part of the creation of a top-level chrome window. when the window is destroyed, it will fire a "xul-window-destroyed" notification through the global observer service. this signals the application in case it needs to quit. ...
... raisedz 6 the z level of an independent window opened with the "alwaysraised" chrome flag. highestz 9 methods addchildwindow() tell this window that it has picked up a child xul window.note that xul windows do not currently track child xul windows. void addchildwindow( in nsixulwindow achild ); parameters achild the child window being added. native code only!applychromeflags back-door method to force application of chrome flags at a particular time. do not call this unless you know what you are doing! in particular, calling this when this xul window does not yet have a document in its docshell could cause problems. void applychromeflags(); parameters none. assumechromeflagsarefrozen() begin assuming chromeflags do not change hereafter, ...
nsIZipReader
methods for reading compressed (zip) files. inherits from: nsisupports last changed in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) implemented by: @mozilla.org/libjar/zip-reader;1. to create an instance, use: var zipreader = components.classes["@mozilla.org/libjar/zip-reader;1"] .createinstance(components.interfaces.nsizipreader); about character sets and code pages note: nsizipreader has a code page problem; that is, in the zip specification, filenames are supposed to use 7-bit ascii; however, most modern filesystems use 8 bit code pages, such as utf-8. this can mismatch characters in the nsizipreader api. starting in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), the nsizipreader api supports a limited 8 bit code page usage. all func...
...les list contents of xpi and read file contents this example uses findentries, getentry, getinputstream, open, and close. it also uses nsiscriptableinputstream to read the stream returned by getinputstream. xpi files are zip files, just firefox needs the extension to be xpi. change "portabletester@jetpack.xpi" to the name of a xpi file in your extensions folder. then you can copy and paste this code in scratchpad to run it. var zr = cc["@mozilla.org/libjar/zip-reader;1"].createinstance(ci.nsizipreader); cu.import('resource://gre/modules/osfile.jsm'); cu.import('resource://gre/modules/fileutils.jsm'); var reusablestreaminstance = cc['@mozilla.org/scriptableinputstream;1'].createinstance(ci.nsiscriptableinputstream); var pathtoxpitoread = os.path.join(os.constant...
nsIZipWriter
if updating the zip file fails. ...
...ug 433295), so for the code above to work you need something like: const pr_rdonly = 0x01; const pr_wronly = 0x02; const pr_rdwr = 0x04; const pr_create_file = 0x08; const pr_append = 0x10; const pr_truncate = 0x20; const pr_sync = 0x40; const pr_excl = 0x80; see pr_open documentation or file i/o snippets for details. adding a file to a zip archive this code synchronously adds the file specified by the nsifile thefile to the zip archive. var zipwriter = components.constructor("@mozilla.org/zipwriter;1", "nsizipwriter"); var zipw = new zipwriter(); zipw.open(myzipfilepath, pr_rdwr | pr_create_file | pr_truncate); zipw.addentryfile("path/for/this/file/in/zip archive", components.interfaces.nsizipwriter.compression_default, thefile, false); zipw.close...
XPCOM Interface Reference
iaccessibleapplicationiaccessiblecomponentiaccessibleeditabletextiaccessiblehyperlinkiaccessiblehypertextiaccessibleimageiaccessiblerelationiaccessibletableiaccessibletable2iaccessibletablecelliaccessibletextiaccessiblevalueidispatchijsdebuggeramiinstallcallbackamiinstalltriggeramiwebinstallinfoamiwebinstalllisteneramiwebinstallpromptamiwebinstallerimgicacheimgicontainerimgicontainerobserverimgidecoderimgidecoderobserverimgiencoderimgiloaderimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolorcallbackmozispellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletionca...
...lproxyservicensiproxyinfonsipushmessagensipushservicensipushsubscriptionnsiradiointerfacelayernsirandomgeneratornsirequestnsirequestobservernsiresumablechannelnsirunnablensishentrynsishistorynsishistorylistenernsisockssocketinfonsisslerrorlistenernsisslsocketcontrolnsiscreennsiscreenmanagernsiscripterrornsiscripterror2nsiscriptableionsiscriptableinputstreamnsiscriptableunescapehtmlnsiscriptableunicodeconverternsiscrollablensisearchenginensisearchsubmissionnsisecuritycheckedcomponentnsiseekablestreamnsiselectionnsiselection2nsiselection3nsiselectioncontrollernsiselectionimageservicensiselectionprivatensiserversocketnsiserversocketlistenernsiservicemanagernsisessionstartupnsisessionstorensisimpleenumeratornsismsdatabaseservicensismsrequestmanagernsismsservicensisocketprovidernsisocketproviderser...
NS_CStringContainerInit
summary the ns_cstringcontainerinit function initializes a nscstringcontainer instance for use as a nsacstring. #include "nsstringapi.h" nsresult ns_cstringcontainerinit( nscstringcontainer& astring ); parameters astring [in] a nscstringcontainer instance to be initialized. return values the ns_cstringcontainerinit function returns ns_ok if successful. otherwise, it returns an error code. ...
...therefore, it is generally better to use nsembedcstring, to instantiate a nsacstring object, since it automatically releases allocated memory when the object goes out of scope. ...
NS_CStringCutData
[in] a nsacstring instance to be modified. acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. pass pr_uint32_max to specify the length from acutstart to the end of the string. return values the ns_cstringcutdata function returns ns_ok if successful. otherwise, it returns an error code. ...
...e, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. pass pr_uint32_max to specify the length from acutstart to the end of the string. return values the ns_cstringcutdata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange . example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello world"); // remove " world" portion of string ns_cstringcutdata(str, 5, pr_uint32_max); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. ...
NS_CStringInsertData
pecifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_cstringinsertdata function returns ns_ok if successful. otherwise, it returns an error code. ...
...tring. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_cstringinsertdata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringinsertdata(str, 5, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_cstringsetdatarange, nsacstri...
NS_CStringToUTF16
nscstringencoding asrcencoding, nsastring& adest ); parameters asrc [in] a nsacstring instance containing the source string to be converted. asrcencoding [in] the character encoding of the source string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsastring instance that will contain the result of the conversion. ...
...nverted. asrcencoding [in] the character encoding of the source string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsastring instance that will contain the result of the conversion. the result will be encoded using the host byte order. return values the ns_cstringtoutf16 function returns ns_ok if successful. otherwise, it returns an error code. the set of possible error codes is currently unspecified. example code nsembedcstring str("hello"); nsembedstring ustr; ns_cstringtoutf16(str, ns_cstring_encoding_ascii, ustr); const prunichar *unicharbuf = ustr.get(); history this function was frozen for mozilla 1.7. see bug bug 239123 for details. see also nsacstring, nsastring, nscstringencoding ...
NS_StringAppendData
[in] a nsastring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringappenddata function returns ns_ok if successful. otherwise, it returns an error code. ...
...ata need not be null terminated. return values the ns_stringappenddata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringappenddata(str, l" world"); const prunichar* data; ns_stringgetdata(str, &data); // data now points to the string: l"hello world" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringsetdatarange, nsastrin...
NS_StringCopy
nother. this is a low-level api. #include "nsstringapi.h" nsresult ns_stringcopy( nsastring& adeststring, const nsastring& asrcstring ); parameters adeststring [in] a nsastring instance to be modified. asrcstring [in] a nsastring instance containing the new string value. return values the ns_stringcopy function returns ns_ok if successful. otherwise, it returns an error code. ...
...rcstring [in] a nsastring instance containing the new string value. return values the ns_stringcopy function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example code /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsastring& avalue) { return ns_stringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsastring& avalue) { return ns_stringcopy(mvalue, avalue); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsastring ...
NS_StringCutData
n] a nsastring instance to be modified. acutstart [in] the starting index of the section to remove, measured in storage units. acutlength [in] the length of the section to remove, measured in storage units. pass pr_uint32_max to specify the length from acutstart to the end of the string. return values the ns_stringcutdata function returns ns_ok if successful. otherwise, it returns an error code. ...
...cutstart to the end of the string. return values the ns_stringcutdata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange. note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello world"); // remove " world" portion of string ns_stringcutdata(str, 5, pr_uint32_max); const prunichar* data; ns_stringgetdata(str, &data); // data now ponts to the string: l"hello" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. ...
NS_StringInsertData
ifying where to place the given characters. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringinsertdata function returns ns_ok if successful. otherwise, it returns an error code. ...
...a need not be null terminated. return values the ns_stringinsertdata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_stringsetdatarange . note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringinsertdata(str, 5, l" world"); const prunichar* data; ns_stringgetdata(str, &data); // data now points to the string: l"hello world" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringsetdatarange , nsac...
NS_StringSetDataRange
ection to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringsetdatarange function returns ns_ok if successful. otherwise, it returns an error code. ...
...ce, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringsetdatarange function returns ns_ok if successful. otherwise, it returns an error code. ...
NS_UTF16ToCString
a nsastring instance from utf-16 to the specified multi-byte encoding and stores the result in a nsacstring instance. #include "nsstringapi.h" nsresult ns_utf16tocstring( const nsastring& asrc, nscstringencoding adestencoding, nsacstring& adest ); parameters asrc [in] a nsastring instance containing the source utf-16 string to be converted. the source string should be encoded using the host byte order. adestencoding [in] the character encoding of the destination string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsacstring instance that will contain the result of the conversion. return values the ns_utf16tocstring function returns ns_ok if successful. otherwise, it returns an error code. the set of po...
...ost byte order. adestencoding [in] the character encoding of the destination string. see nscstringencoding for the set of values that can be passed for this parameter. adest [out] a nsacstring instance that will contain the result of the conversion. return values the ns_utf16tocstring function returns ns_ok if successful. otherwise, it returns an error code. the set of possible error codes is currently unspecified. example code // convert utf-16 (or ucs-2) string to utf-8 void copyutf16toutf8(const nsastring& in, nsacstring& out) { ns_utf16tocstring(in, ns_cstring_encoding_utf8, out); } history this function was frozen for mozilla 1.7. see bug bug 239123 for details. see also nsacstring, nsastring, nscstringencoding ...
XPCOM Thread Synchronization
ck()) has a matching function in nspr (pr_lock()). this is no accident, as mozilla:: primitives are merely bare-minimum wrappers around nspr's. this article covers the api of mozilla synchronization only. for a higher-level introduction to thread synchronization, see introduction_to_nspr. quick reference: difference between nsautolock api and new api old construction note: this is deprecated code that is shown only to compare with approved code. prlock* mlock; prmonitor* mmonitor; prcondvar* mcvar; fooconstructor() { } nsresult init() { mlock = nsautolock::newlock("foo lock"); // check for null mmonitor = nsautomonitor::newmonitor("foo monitor"); // check for null mcvar = pr_newcondvar(mrawlock); // check for null // ... } ne...
...check for null mcvar = pr_newcondvar(mrawlock); // check for null // ... } new construction using namespace mozilla; mutex mlock; monitor mmonitor; condvar mcvar; fooconstructor() : mlock("foo lock"), mmonitor("foo monitor"), mcvar(mlock, "foo condvar") { } nsresult init() { // ... } old usage note: this is deprecated code that is shown only to compare with approved code. concurrentmethod() { nsautolock al(mlock); nsautomonitor am(mmonitor); if (needexpensivecomputation()) { nsautounlock au(mlock); } am.wait(); pr_notifycondvar(mcvar); } new usage using namespace mozilla; concurrentmethod() { mutexautolock al(mlock); monitorautoenter am(mmonito...
Using nsIDirectoryService
le locations. c++ nscomptr<nsifile> dir; ns_getspecialdirectory(prop, getter_addrefs(dir)); if (!dir) return ns_error_failure; javascript: var file = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); (the example is taken from the code snippets section of this site.) adding a location: there are currently two ways to add a file location to the directory service: directly and delayed. you can directly add a new nsifile with any property string using the nsiproperties interface: components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .se...
...here are things in the startup process that need these locations at a very early point - even before registering components. if you want to use mpfilelocprovider, or something like it, to provide one fixed profile, just construct it and call its initialize method - it will register itself. again, if you do this, do not initialize the profile service - it's either one or the other. related pages code_snippets:file_i/o original document information authors: conrad carlen, doug turner last updated date: september 26, 2000 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Using nsIPasswordManager
for similar functionality in toolkit 1.9, see using nsiloginmanager. working with password manager extensions often need to securely store passwords to external sites, web applications, and so on. ...
...for similar functionality in toolkit 1.9, see using nsiloginmanager. working with password manager extensions often need to securely store passwords to external sites, web applications, and so on. ...
pyxpidl
pyxpidl has been in use for a while, but replaced xpidl in the gecko sdk starting in gecko 9.0. using pyxpidl pyxpidl is in the sdk in the sdkdir/sdk/bin/ directory. ...
... pyxpidl has been in use for a while, but replaced xpidl in the gecko sdk starting in gecko 9.0. using pyxpidl pyxpidl is in the sdk in the sdkdir/sdk/bin/ directory. ...
XSLT 2.0
natively supported in firefox, it is possible via saxon-b (java) or, more recently, saxon-ce (javascript) to perform xslt 2.0. for users saxon-ce no extensions are required, saxon-ce runs whenever a html page is loaded that links to the saxon-ce javascript library. saxon-b the xsl results extension uses the new incarnation of liveconnect (handled by java 1.6v12+ instead of mozilla-specific code) to connect with the java-based saxon-b library, and adds support for having xslt performed automatically when visiting a page with the appropriate xslt processing instruction (and which isn't processed by firefox's own xslt 1.0 processor). for developers saxon-ce a javascript api is provided for initiating an xslt 2.0 transform from a web page. error and diagnostics output from saxon-ce can b...
...age with the appropriate xslt processing instruction (and which isn't processed by firefox's own xslt 1.0 processor). for developers saxon-ce a javascript api is provided for initiating an xslt 2.0 transform from a web page. error and diagnostics output from saxon-ce can be reviewed in the firefox developer console or in firebug. saxon-b the extension demonstrates how one can use liveconnect code to communicate with the saxon-b library, but one might find the javascript code module approach used inside the extension xquseme as a more reusable approach. the code does not currently work on the mac (except for server edition supporting java 1.6) due to its lagging java support (and thus liveconnect support). ...
Mozilla technologies
starting with mozilla 1.9, it was phased out in favor of sqlite, a more widely-supported file format.placesplaces is the bookmarks and history management system introduced in firefox 3. it offers increased flexibility and complex querying to make handling the places the user goes easier and mor...
... to publicize application usage for the purpose of notifying a user's friends of the applications which their friends are using. it is not meant as a general application messaging system. toolkit apithe mozilla toolkit is a set of programming interfaces (apis) built on top of gecko which provide advanced services to xul applications. these services include:viewing and searching mozilla source code onlinesource code for all mozilla projects hosted in the mercurial repositories can be searched and viewed online using searchfox, a fast indexed search engine that runs on aws.xml extrasthe xml extras module contains several features that allow developers to treat xml as data i.e. not as just another document format. the module is structured as a drop-in component and exposes its xml-as-data fea...
Address book sync client design
er that the ab sync authorization operation has begun. * */ void onstartauthoperation(); /** * notify the observer that the ab sync operation has been completed. * * this method is called regardless of whether the the operation was * successful. * * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the error (if any). * acookie - hmmm...cooookies! */ void onstopauthoperation(in nsresult astatus, in wstring amsg, in string acookie); /** * notify the observer that the ab sync operation has begun. this method is * called only once, at the beginning of a sync transaction ...
...tatus message for sync operation */ void onstatus(in print32 atransactionid, in wstring amsg); /** * notify the observer that the ab sync operation has been completed. * * this method is called regardless of whether the the operation was * successful. * * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the error (if any). */ void onstopoperation(in print32 atransactionid, in nsresult astatus, in wstring amsg); }; ...
Creating a gloda message query
creating your first message query... import gloda gloda's api is exposed in the "gloda" object that is contributed to your namespace. ...
...sation instance. somewhat magic attributes: headermessageid: the contents of the message-id header of the message. you probably should not be using this. foldermessage: return the nsimsgdbhdr that corresponds to the message. an nsimsgdbhdr is the low-level, old-school, thunderbird xpcom representation of a message. you should not need to use this unless you are dealing with other old-school code or you need to manipulate the state of a message. in the future, the steel layer should provide wrappers to make manipulation clean and fun. note that this message may return "null" if gloda is unable to locate the underlying message anymore. attributes provided by fundattr.js: from: a single glodaidentity corresponding to the author of the message. to: a list of glodaidentity instances cor...
Filelink Providers
ature names that were used while filelink was under construction. both refer to the filelink feature. filelink storage providers must implement the nsimsgcloudfileprovider interface. the hightail implementation is a great place to look for examples and inspiration. the nsimsgcloudfileprovider implementation must be registered as a component. if the provider is being merged into the comm-central code repository (and thus added to the official thunderbird build), you must also add the components to the cloudfile/cloudfilecomponents.manifest, cloudfile/jar.mn, and installer/package-manifest.in. if the nsimsgcloudfileprovider is being created as part of an add-on, the add-on must register the component in chrome.manifest. also, you must add the component's contract id to the "cloud-file" catego...
...to use html5 form validation. for each input event, the checkvalidity method of the form is automatically called. the button to set up the account will only become enabled once the checkvalidity method for the form returns true. saving custom settings in preferences custom settings for a provider are saved using the preferences api. saving the preferences is handled automatically by the dialog code. providers need only provide an extraargs function in the iframe content which returns an object specifying the name, type, and value to save. the format for the returned object is: { field_name: {type: field_type, value: field_value} } where field_type is "int", "bool", or "char". for example, the hightail implementation provides the following function: function extraargs() { var usern...
Mail composition back end
back end, so i thought it would be helpful to put together a small doc on the new interfaces and how one can use them. the mail composition back end is responsible for the assembly and creation of rfc822 messages to be delivered either via smtp or nntp services. you also have the ability to save rfc822 files to disk, should you need this data for some reason. included in this functionality is the code to copy the messages to the appropriate locations after delivery (i.e. a "sent" folder) as well as the ability to store messages for features like "drafts" and "templates". several (but not all) of these interfaces are specified in idl. this will change in the coming weeks and allow for developers to write javascript to take advantage of the back end services. also, i will talk about some feature...
...d completion of the copy operation. nsimsgsendlistener the following describes the methods of the nsimsgsendlistener interface: onstartsending the onstartsending interface is called when the sending operation has begun. this is called after messages creation has completed. if message creation fails, the nsimsgsend operation will return an ns_failed() return code. ns_imethod onstartsending(const char *amsgid, - the message id for the message being sent pruint32 amsgsize) = 0; - the total message size for the message being sent onprogress the onprogress interface is called with progress notification on the send operation. ns_imethod onprogress(const char *amsgid, - the message id for the message being...
Mail event system
onitemintpropertychanged notifyitemboolpropertychanged onitemboolpropertychanged notifyitemunicharpropertychanged onitemunicharpropertychanged notifyitempropertyflagchanged onitempropertyflagchanged notifyitemevent onitemevent notifyfolderloaded onfolderloaded notifydeleteormovemessages ondeleteormovemessages sample code in this example, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerhasfired = false; var totalmessageslistenerhasfired = false; // the listening function that will react to changes function myonintpropertychanged(item, property, oldvalue, newvalue) { listenerhasfired=true; var propertystring = pr...
...mple, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerhasfired = false; var totalmessageslistenerhasfired = false; // the listening function that will react to changes function myonintpropertychanged(item, property, oldvalue, newvalue) { listenerhasfired=true; var propertystring = property.getunicode(); dump("onintpropertychanged has fired with property + " + propertystring + "!\n"); if (propertystring == "totalmessages") { totalmessageslistenerhasfired=true; //now show us visually var folder = item.queryinterface(components.interfaces.nsimsgfolder); dump("the folder " + folder.prettyname + " now has " + newvalue + " messages."); } else if (propertystrin...
Building a Thunderbird extension 1: introduction
2,3 and 5. all thunderbird builds are available from the ftp site. references and resources tools and helper extensions there are many tools available that help with developing thunderbird extensions. at a minimum you will need: text editor: any editor that is capable of writing plain text can be used to write extensions. however, most developers use an editing program optimized for writing code (also known as an integrated development environment). these provide features like syntax highlighting and code coloration, indentation, auto-complete, etc. file archive utility: any utility that is capable of creating archive files can be used. there are also a number of extension and applications that are useful for testing and debugging thunderbird extensions, such as javascript consoles an...
...extension and applications that are useful for testing and debugging thunderbird extensions, such as javascript consoles and xpcom inspectors. these are described on the page "setting up an extension development environment". documentation thunderbird extensions (documentation overview) firefox addons developer guide (many topics are applicable to thunderbird) mozilla cross-reference source code browser ("comm-central" contains the thunderbird code repository) community the thunderbird development community has a mailing list with an extensive searchable archive with an extensive searchable archive. you can also talk with the community on the #maildev irc channel. next » ...
Demo Addon
demos are explained in the following sections. only the interesting parts are shown, it's recommended that you download the add-on and have a look at its files. the basics the interesting parts covered in this article are in the content folder. the toolbar button and its functionality are defined in overlay.xul and overlay.js. we make use of fixiterator(). it is a handy library that keeps your code cleaner and simpler. it lets you iterate over any collection and transforms your collection elements in the given objects, to use fixiterator, you have to import it with cu.import("resource:///modules/iteratorutils.jsm");. demo 1 - iterate over all the accounts this demo is implemented in demo1.html in the content folder. it lists all your email accounts with their account type - either pop3 or...
...on the screen and mark it with an * if it is the inbox. afterwards, we check every folder for subfolders. we then go into each subfolder and start over. to list some messages of the folder we use: for each (let msghdr in fixiterator(inbox.msgdatabase.enumeratemessages(), ci.nsimsgdbhdr)) { if (++i >= 10 && lastmsghdr != null) break; messages.push({ author: msghdr.mime2decodedauthor, subject: msghdr.mime2decodedsubject, date: new date(msghdr.date/1000), }); //... } to get a collection of messages in the inbox, we use inbox.msgdatabase.enumeratemessages(). each message is a nsimsgdbhdr. we iterate over the first ten of them and extract author, subject and date for each one. demo 3- search messages by subject this demo shows how to find message...
Filter Incoming Mail
msgadded: function(amsghdr) { if( !amsghdr.isread ) { // here we are, a new mail has popped // let get a javascript string object from the subject property // querying mime conversion interface var mimeconvert = components.classes["@mozilla.org/messenger/mimeconverter;1"] .getservice(components.interfaces.nsimimeconverter); var subject = mimeconvert.decodemimeheader(amsghdr.subject, null, false, true); // here with have a string to modify with javascript. by example, setting it to lower case subject = subject.tolocalelowercase(); // then we rebuild a subject objet by rencoding the string // and assign it to the message headers and we're done amsghdr.subject = mimeconvert.encodemimepartiistr_utf8(subject, false, "utf-8"...
... ...
Use SQLite
if you'd like to use an sqlite database in your extension you'll need to look over the storage docs for an api reference, however this code should get you started. be careful of multi-thread access to your database. this will create an sqlite db named tbird.sqlite inside your profile directory with a table called attachments. you can see the schema for the attachments table in the code. to double check the information you've inserted you can query the tbird.sqlite file using regular sqlite programs. ...
...lite db named tbird.sqlite inside your profile directory with a table called attachments. you can see the schema for the attachments table in the code. to double check the information you've inserted you can query the tbird.sqlite file using regular sqlite programs. const cc = components.classes; const ci = components.interfaces; var tbirdsqlite = { onload: function() { // initialization code this.initialized = true; this.dbinit(); }, dbconnection: null, dbschema: { tables: { attachments:"id integer primary key, \ name text \ encoded text not null" } }, dbinit: function() { var dirservice = cc["@mozilla.org/file/directory_service;1"]. getservice(ci.nsiproperties); var dbf...
Thunderbird extensions
is extremely powerful and is used heavily by add-ons such as thunderbird conversations. learn more about gloda: an overview of gloda how to create your first message query and read the gloda examples gloda internals: gloda debugging, gloda indexing more thunderbird-specific links some links may be out of date, but they still provide valuable information on the codebase. an overview of thunderbird components developer reference docs: folder classes db views (message list) message summary database mailnews protocols mailnews filters error reporting tools steel library (obsolete as of thunderbird 52, use https://github.com/protz/thunderbird-stdlib) developing new account typ...
... developing new account types useful newsgroup discussions (anything that's very old should be regarded suspiciously, because there has been significant api rewrite over the past years making most techniques considerably easier) thunderbird api docs (mostly a collection of out-of-date pages, relevance is rather dubious) general links finding the code for a feature mozillazine articles on thunderbird community / communications thunderbird specific : add-ons section on developer.thunderbird.net thunderbird communication channels add-on developers forum/mailing list #maildev irc channel more general : mozillazine extension development forum general developer channels ...
Using popup notifications
ed by clicking anywhere outside the notification, then clicking on the notification icon to bring it back again. a popup notification can include a text message, a button action, and zero or more additional actions provided in a drop-down menu accessed through the notification's button. creating a popup notification popup notifications can be created using the popupnotifications.jsm javascript code module. this code module is imported by the browser, so you don't need to do it explicitly yourself. then you can create the popup notification at the appropriate time like this: popupnotifications.show(gbrowser.selectedbrowser, "sample-popup", "this is a sample popup notification.", null, /* anchor id */ { label: "do something", accesskey: "d", ...
...ull /* secondary action */ ); in this case, we aren't providing any secondary actions; that is, actions provided to the user through the drop-down menu. this notification looks like this: that's not very pretty; where's the icon? adding an icon to your notification adding an icon to a notification is simple. you just need to provide the appropriate css. the popupnotifications.jsm code module adds a popupid attribute to the notification object's icon element. you can use this to style the icon, like this: .popup-notification-icon[popupid="sample-popup"] { list-style-image: url("chrome://popupnotifications/skin/mozlogo.png"); } with this css in place, the result is the look we want: adding secondary options to provide options in the drop-down menu, add an array of notif...
Using the Mozilla source server
using the mozilla source server is now even more feature-packed. ...
...set up symbols follow the instructions for using the mozilla symbol server. once the symbol path is set you must now enable source server. using the source server in windbg in the windbg command line, type .srcfix and hit enter. this enables source server support. now, when you click on a frame in the "calls" window, windbg will prompt you about running cvs to download the associated source code. if you click "yes", windbg will display *busy* in the status bar while it downloads the source, and then it will automatically open the file and highlight the current line. using the source server in visual studio note: source server support does not work correctly out of the box in visual studio 2005. if you install windbg, and copy srcsrv.dll from the windbg install dir to the visual st...
Virtualenv
import paths). it is written by mozilla's own ian bicking. creating a virtualenv installs setuptools (or optionally distribute) into the virtual environment. it is recommended that you use virtualenv for installing anything other than system software that you are working on. you will obviate the need to have access to your system packages and you won't mess up your system packages with whatever code you install into the site-packages directory of the virtualenv. site-packages should mostly be for system-installed python and not python that you are installing as a user. this page is mostly a stub for how virtualenv is used at mozilla. for more information on virtualenv in general, see the virtualenv web site. python packaging at mozilla is covered in python. getting virtualenv virtualenv ...
...y install. again, you may need to use sudo to install globally. if you're running ubuntu, there is also an ubuntu package available: sudo apt-get install python-virtualenv virtualenv.py may also be run as standalone software with the same functionality. it will require it to be part of a clone of the github repository or have internet access to fetch setuptools. on mac os x, you will need xcode to use virtualenv. see this article for details. using virtualenv once you have virtualenv installed, you can make virtual environments: > virtualenv tmp new python executable in tmp/bin/python installing setuptools............done. installing pip...............done. a python binary, as well as easy_install and pip are available in the bin/ subdirectory (or scripts on windows). > ls tmp/bi...
Examples
pes with js-ctypes. standard os libraries some examples on how to get cursor position on each os. mac os x these examples require mac os x to operate. add image to iphoto an extension that adds a contextual menu item to images that lets you easily add them to iphoto on mac os x. using objective-c from js-ctypes an example how to use objective-c from js-ctypes, by converting objective-c code into c code. using com from js-ctypes an example how to use com api of windows systems from js-ctypes, by converting c++ code to c code. using jni from js-ctypes an example how to use java from js-ctypes, by converting java code into c code. js-macosx an extension that demonstrates javascript-cocoa bridge for mac os x. lightweight bridge for calling cocoa frameworks from javascript, js-ma...
... ...
Declaring types
cked structure; that is, using #pragma pack. field descriptors each field descriptor is comprised of a field name and its data type, represented as a string and a ctype object, respectively. the format, then, looks like this: [ { field1: type1 }, { field2: type2 }, ... ...
...ter to any user-defined type, including structures: const userrecord = new ctypes.structtype("userrecord", [{"name": ctypes.char.ptr}, {"id": ctypes.int32}]); const userrecordptr = new ctypes.pointertype(userrecord); in this example, a new userrecord type is defined, along with a new pointer type that can be used to reference it. the equivalent c code looks like this: typedef struct userrecord { char *name; int id; // assuming int is 32-bit here } userrecord; typedef userrecordptr *userrecord; ...
Memory Management
it is usually best to expose a freeing function from the binary. keeping objects alive the following js-ctypes objects will hold references to objects, keeping them alive. this is not an exhaustive list, but will help you to understand memory management and how it affects your use of js-ctypes: a function or static data declared using the declare() method will hold that library alive. ...
...tant to note that getting direct access to the contents of a cdata object using address(), addressofelement(), or contents, will result in a cdata object that does not hold its referent alive. be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it. closures you also need to be sure to retain references to any javascript code that native code may call back into. this should be obvious, but is important enough to be worth stating explicitly. when in doubt, malloc() when you need to keep data around, you can use malloc() to allocate it directly. this bypasses javascript's memory management and lets you handle memory management yourself. ...
PKCS #11 Netscape Trust Objects - Network Security Services
ven usage or purpose. conceptually a trust object contains the following: certificate reference purpose + level of trust (multiple) purpose + level of trust a trust object ultimately denotes a level of trust in a certificate. the trust is expressed for a specific purpose (or usage). a trust object contains multiple purposes and the level of trust for each one. examples of purposes are: email, code signing, authenticating a server. the levels of trust are: untrusted: the certificate is explicitly untrusted. unknown: the trust is not known and should be determined elsewhere. trusted: the certificate itself is explicitly trusted. trusted delegator: the certificate is trusted as a certificate authority trust root, and confers its trust to other certificates. certificate reference each tr...
...oding of the certificate. required for trust anchor objects. cka_cert_md5_hash byte array md5 hash of the der-encoding of the certificate. required for trust anchor objects. cka_trust_server_auth ck_trust level of trust for server authentication purpose. cka_trust_client_auth ck_trust level of trust for client authentication purpose. cka_trust_code_signing ck_trust level of trust for code signing purpose. cka_trust_email_protection ck_trust level of trust for email protection purpose. cka_trust_ipsec_end_system ck_trust level of trust for ipsec end system purpose. cka_trust_ipsec_tunnel ck_trust level of trust for ipsec tunnel purpose. cka_trust_ipsec_user ck_trust l...
Drawing and Event Handling - Plugins
window contains the window in which the plug-in should print. on ms windows, note that the coordinates for the window rectangle are in twips format. for this reason, you need to convert the x - and y - coordinates using the windows api call dptolp when you output text. setting the window the browser calls the npp_setwindow function to set the window in which a plug-in draws or returns an error code. this window is valid for the life of the instance, or until npp_setwindow is called again with a different value. subsequent calls to npp_setwindow for a given instance usually mean that the window has been resized. if either window or window->window is null, the plug-in must not perform any additional graphics operations on the window and should free any associated resources. nperror npp_setw...
...s this mechanism for both windowed and windowless plug-ins; on this platform, npp_handleevent is the only way the plug-in can receive events from its host application. int16 npp_handleevent(npp instance, npevent *event); the instance parameter represents the current plug-in. for a list of event types the application is responsible for delivering to the plug-in, see the npevent structure. ...
Initialization and Destruction - Plugins
« previousnext » this chapter describes the methods that provide the basic processes of initialization, instance creation and destruction, and shutdown. initialization: the browser calls the plug-in api function np_initialize when the plug-in code is first loaded. instance creation: the browser calls the plug-in api function npp_new when the instance is created. instance destruction: the plug-in instance is deleted when the user leaves the instance page or closes the instance window; the browser calls the function npp_destroy to tell the plug-in that the instance is being deleted. shutdown: when the last instance of a plug-in is deleted, the plug-in code is unloaded from memory and the browser calls the function np_shutdown. plug-ins consume no resources, other than dis...
...ted, the browser calls np_shutdown, which releases the memory or resources allocated by np_initialize. for an example that shows the use of both the np_initialize and np_shutdown methods, see initialize and shutdown example. during initialization, when the browser encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it loads the plug-in code into memory (if it hasn't been loaded already) and creates a new instance of the plug-in. for more information, see registering plug-ins. plug-ins are native code libraries: .dll files on windows, .so or .dso files on unix, and powerpc shared library files or 68k code resources on mac os. to reduce memory overhead, plug-ins are usually loaded only when needed and released as soon as possible. i...
Streams - Plugins
as the stream is inherently seekable; npn_requestread automatically changes the mode to np_seek. for streams that are not inherently seekable: the stream must be put in np_seek mode initially, because the browser must cache all the stream data on disk in order to access it randomly. for streams that are not inherently seekable and not initially in mode np_seek: npn_requestread returns the error code nperr_stream_not_seekable. the npn_requestread method has the following syntax: nperror npn_requestread(npstream *stream, npbyterange *rangelist); the stream parameter is the stream from which to read bytes; the rangelist parameter specifies the range of bytes in the form of a linked list of npbyterange objects, which the plug-in must allocate. because these objects are copied by the browser,...
...reated by either the browser or the plug-in. the reason parameter represents the reason the stream was stopped, as follows: npres_done (most common): the stream completed normally; the plug-in sent all data to the browser. npres_user_break: the plug-in terminated the stream because of a user request. npres_network_err: the stream failed because of network problems. for the complete list of codes, see "result codes." for an example that demonstrates using this function with npn_newstream and npn_write, see "example of sending a stream." example of sending a stream the following code creates a new stream of html text displayed by the browser in a new window, writes it, and destroys the stream. error handling has been omitted for simplicity. npstream* stream; char* mydata = "<html><hea...
Version, UI, and Status Information - Plugins
or and minor version numbers, which are determined when the plug-in and navigator are compiled, and compare them. if the versions are not compatible, the plug-in can let the user know. the plug-in can also use the version number to find out whether a particular feature exists on the version of the browser that the plug-in is running in. the browser and plug-in api major version numbers represent code release numbers, and their minor version numbers represent point release numbers. for example, plug-in api version 6.03 has a major version number of 6 and a point release number of 3. differing version numbers may mean that the current plug-in api and the browser versions are incompatible. changes to the minor version numbers indicate a smaller difference than changes to the major version. chan...
...it gets the values from the plug-in rather than from the browser. void npn_version(int *plugin_major, int *plugin_minor, int *netscape_major, int *netscape_minor); this function returns the plug-in version number in plugin_major, the plug-in point release number in plugin_minor, the browser version number in netscape_major, and the browser point release number in netscape_minor. this code declares variables to hold the version numbers and calls npn_version to return the major and minor version numbers for the browser and the plug-in api. int plugin_major, plugin_minor, netscape_major, netscape_minor; // declare variables to hold version numbers void npn_version( &plugin_major, &plugin_minor, &netscape_major, &netscape_minor ); // find version numbers finding out if a fea...
Gecko Plugin API Reference - Plugins
kies. npn_status displays a message on the status line of the browser window. npn_useragent returns the browser's user agent field. npn_version returns version information for the plug-in api. npn_write pushes data into a stream produced by the plug-in and consumed by the browser. ...
... npn_evaluate npn_getproperty npn_setproperty npn_removeproperty npn_hasproperty npn_hasmethod npn_setexception npclass structures npanycallbackstruct npbyterange npembedprint npevent npfullprint npp np_port npprint npprintcallbackstruct nprect npregion npsaveddata npsetwindowcallbackstruct npstream npwindow constants error codes result codes plug-in version constants version feature constants external resources external projects and articles for plugin creation original document information copyright information: netscape communication ...
Application - Firefox Developer Tools
ee it there, you can enable it by going to the "three dot" menu and selecting settings (also accessible by pressing f1), then checking the application checkbox under default developer tools. ...
...y pressing f1), then checking the application checkbox under default developer tools. ...
Use watchpoints - Firefox Developer Tools
in the firefox debugger, this information can be provided by watchpoints. by setting a watchpoint on the property, rather than a breakpoint at a particular line, you can discover where that access occurs. there are three types of watchpoints: get, set, and get or set. a get watchpoint pauses whenever a property is read; a set watchpoint pauses whenever a property value changes; a get or set watchpoint pauses whenever a property value is accessed in either way. set a watchpoint run and then pause the debugger. ...
...atchpoint icon appears to the right of the property in the scopes pane. set watchpoint icons are blue, get watchpoint icons are reddish, and get or set watchpoint icons are dark yellow. click play or press f8 to resume execution. view a watchpoint when the watched property is accessed in the way specified by the watchpoint type (get or set), the debugger pauses, enabling you to see line of code responsible, and to inspect anything else you wish at that time. in the following screenshot, the debugger pauses at line 7, where obj.a is set. the message panel in the upper right corner indicates that the debugger is "paused on property set". delete a watchpoint locate the watched property in the scopes pane. click the watchpoint icon, or right-click and choose remove watchpoint. the w...
The Firefox JavaScript Debugger - Firefox Developer Tools
the javascript debugger enables you to step through javascript code and examine or modify its state to help track down bugs. you can use it to debug code running locally in firefox or running remotely, for example on an android device running firefox for android. see remote debugging to learn how to connect the debugger to a remote target. to find your way around the debugger, here's a quick tour of the ui. how to to find out what you can do with the debugger, refer to the following how-to guides. open the debugger pretty-print a minified file search use a source map pause execution you probably want to pause the execution of your code, in order to see what is going on at various points. there are multiple ways to tell the debugger how and when to pause: set a breakpoint ...
...hat is going on at various points. there are multiple ways to tell the debugger how and when to pause: set a breakpoint set a conditional breakpoint set an xhr breakpoint set event listener breakpoints break on exceptions use watchpoints for property reads and writes break on dom mutation disable breakpoints control execution what can you do after execution pauses? step through code black box a source debug worker threads debug eval sources look at values you probably want to see the value of variables or expressions, either during execution or when it is paused. set a logpoint set watch expressions reference keyboard shortcuts source map errors ...
All keyboard shortcuts - Firefox Developer Tools
end end end style editor command windows macos linux open the style editor shift + f7 shift + f7 shift + f7 open autocomplete popup ctrl + space cmd + space ctrl + space scratchpad command windows macos linux open the scratchpad shift + f4 shift + f4 shift + f4 run scratchpad code ctrl + r cmd + r ctrl + r run scratchpad code, display the result in the object inspector ctrl + i cmd + i ctrl + i run scratchpad code, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd +...
... ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl + p show autocomplete suggestions ctrl + space ctrl + space ctrl + space show inline documentation ctrl + shift + space ctrl + shift + space ctrl + shift + space eyedropper command windows macos linux select the current color enter return enter dismiss the eyedro...
Aggregate view - Firefox Developer Tools
his case, you can see that the first three arrays have a fairly large shallow size (5% of the total heap usage) and a much larger retained size (26% of the total). on the right-hand side is a pane that just says "select an item to view its retaining paths". if you select an item, you'll see the retaining paths panel for that item: call stack the call stack shows you exactly where in your code you are making heap allocations. because tracing allocations has a runtime cost, it must be explicitly enabled by checking "record call stacks" before you allocate the memory in the snapshot. you'll then see a list of all the functions that allocated objects, ordered by the size of the allocations they made: the structure of this view is very much like the structure of the call tree, only ...
...s very much like the structure of the call tree, only it shows allocations rather than processor samples. so, for example, the first entry says that: 4,832,592 bytes, comprising 93% of the total heap usage, were allocated in a function at line 35 of "alloc.js", or in functions called by that function we can use the disclosure triangle to drill down the call tree, to find the exact place your code made those allocations. it's easier to explain this with reference to a simple example. for this we'll use the dom allocation example. this page simply runs a script that creates a large number of dom nodes (200 htmldivelement objects and 4000 htmlspanelement objects). let's get an allocation trace: open the memory tool check "record call stacks" load https://mdn.github.io/performance-scen...
DOM allocation example - Firefox Developer Tools
...
... ...
Dominators view - Firefox Developer Tools
the function, we can see those nodes. in this way you can quickly get a sense of which objects retain the most memory in the snapshot. you can use alt + click to expand the whole graph under a node. call stack in the toolbar at the top of the tool is a dropdown called "label by": by default, this is set to "type". however, you can set it instead to "call stack" to see exactly where in your code the objects are being allocated. this option is called "allocation stack" in firefox 46. to enable this, you must check the box labeled "record call stacks" before you run the code that allocates the objects. then take a snapshot, then select "call stack" in the "label by" drop-down. now the node's name will contain the name of the function that allocated it, and the file, line number and ch...
...ction in the graph is labeled with the variable name for the referenced object. sometimes there's more than one retaining path back from a node: here there are three paths back from the documentprototype node to a gc root. if one were removed, then the documentprototype would still not be garbage-collected, because it's still retained by the other two path. example let's see how some simple code is reflected in the dominators view. we'll use the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name. taking a snapshot to see what it looks like in the dominators view: load the page enable the memory tool in the settings, if you haven't already open the memory tool check "record call stacks" press the b...
Memory - Firefox Developer Tools
the basics opening the memory tool taking a heap snapshot comparing two snapshots deleting snapshots saving and loading snapshots recording call stacks analyzing snapshots the tree map view is new in firefox 48, and the dominators view is new in firefox 46. ...
...ew shows memory usage as a treemap. the aggregate view shows memory usage as a table of allocated types. the dominators view shows the "retained size" of objects: that is, the size of objects plus the size of other objects that they keep alive through references. if you've opted to record allocation stacks for the snapshot, the aggregate and dominators views can show you exactly where in your code allocations are happening. concepts dominators example pages examples used in the memory tool documentation. monster example dom allocation example ...
Inspecting web sockets - Firefox Developer Tools
le explores what functionality the web socket inspector makes available. accessing the inspector when you are inspecting a web app that utilizes a web socket connection, the web socket requests are listed in the list of requests in the network monitor along with all other requests. you can use the ws button to filter the list for just web socket connections. only requests with the 101 status code (websocket protocol handshake) are visible, which indicates that the server is switching to a web socket connection. clicking on a web socket request opens the usual sidebar to reveal additional details. choose the reponse tab to inspect web socket frames sent and received through the selected connection. the live-updated table shows data for sent (green arrow) and received (red arrow) frames...
...xcept control messages). control (available starting in firefox 76). displays messages for control frames (ping, pong, or close). this filter can be combined with the others, to display, for example, only messages for control frames sent by the browser. columns in the response pane in the response pane, you can choose to show the following information about each frame: data size time opcode maskbit finbit the data and time columns are visible by default, but you can customize the interface to see more columns by choosing which ones to show from the context menu that is opened by right-clicking in the table header. expanding each message selecting a message in the list shows a preview of the data being sent in that message, at the bottom of the response pane. supported ws ...
Network request details - Firefox Developer Tools
ity (only for secure pages) stack trace (only when the request has a stack trace, e.g. a script called by another script). clicking the icon at the right-hand end of the toolbar closes the details pane and returns you to the list view. headers tab the headers tab has a toolbar, followed by three main sections. this includes: information about the request status: the response status code for the request; click the "?" icon to go to the reference page for the status code. version: the version of http used. transferred: the amount of data transferred for the request. referrer policy: the value of the referrer-policy header. http response headers http request headers each section has a disclosure triangle to expand the section to show more information. headers too...
...ancel to cancel editing. request information the following information is shown only when the section is expanded: scheme: the scheme used in the url host: the server involved in the request filename: the full path to the file requested address: the ip address of the host the following information is shown in both the collapsed and the expanded states: status: the http response code for the request. version: the http version used transferred: the amount of data transferred with the request the referrer policy, which governs which referrer information, sent in the referer header, should be included with requests. (see referrer-policy for a description of possible values) blocking: if the request is to a site that is associated with a known tracker, an icon and a message a...
Work with animations - Firefox Developer Tools
lightning bolt icon in the bar has been replaced with a grey lightning bolt icon, to indicate that only some of the relevant properties are being optimized by the compositor. the bar tooltip also includes this information, as a further reminder. you'll get a message of "some animation properties are optimized." properties whose animation is not being optimized, but could be if you improved your code, are now given a dotted underline — see transform in the screenshot below. hovering over this gives you a tooltip that explains why. in this case, the message is "animations of 'transform' cannot be run on the compositor when geometric properties are animated on the same element at the same time." edit @keyframes any @keyframes rules associated with the currently selected element are displ...
...an specify a timing function: this determines the rate at which the animation progresses. one way to specify the timing function is with a cubic bézier curve. timing functions defined as cubic bézier curves get an icon in the rules view. if you click the icon you get a visual editor for the curve, enabling you to drag p1 and p2, and see the results in the page: this feature uses open source code from lea verou’s cubic-bezier.com. the cubic bézier editor includes a number of presets, grouped under "ease-in", "ease-out", and "ease-in-out": ...
UI Tour - Firefox Developer Tools
ect a different recording, click its entry in the pane. to save the recording as a json file click "save". recording overview this displays an overview of the entire recording, with the x-axis representing time. it contains two elements: an overview of the waterfall and a frame rate graph. waterfall overview this presents a compressed view of the waterfall: recorded operations are color-coded using the same scheme as in the main waterfall view. frame rate graph the frame rate gives you an overview of the browser's responsiveness during the recording: see the separate article on frame rate. correlating events because these elements are synchronized, you can correlate events in one element with events in another. for example, in the screenshot below a long-running paint operati...
...aints. the x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's execution. to learn much more about the waterfall, see the separate waterfall page. call tree the call tree is a sampling profiler for javascript running in the page. it periodically samples the state of the javascript engine, and records the stack for the code executing at the time the sample was taken. statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser is spending executing it, so you can identify bottlenecks in your code. to learn much more about the call tree, see the separate call tree page. flame chart if the call tree tells you, statistically, which functi...
Performance - Firefox Developer Tools
this view only appears if you checked "record allocations" in the performance tool settings. getting started ui tour to find your way around the performance tool, here's a quick tour of the ui. how to basic tasks: open the tool, create, save, load, and configure recordings components of the performance tool frame rate understand y...
...ng started ui tour to find your way around the performance tool, here's a quick tour of the ui. how to basic tasks: open the tool, create, save, load, and configure recordings components of the performance tool frame rate understand your site's overall responsiveness. call tree find bottlenecks in your site's javascript. allocations see the allocations made by your code over the course of the recording. waterfall understand the work the browser's doing as the user interacts with your site. flame chart see which javascript functions are executing, and when, over the course of the recording. scenarios animating css properties uses the waterfall to understand how the browser updates a page, and how animating different css properties can affect...
Settings - Firefox Developer Tools
lete suggestions. screenshot behavior screenshot to clipboard when you click the icon for the screenshot tool, copy the screenshot image to the clipboard (the image will still be saved to your downloads directory). new in firefox 53. play camera shutter sound when you click the icon for the screenshot tool, play a shutter sound. new in firefox 53. editor preferences preferences for the codemirror source editor, which is included in firefox and used by several developer tools, including scratchpad and the style editor. detect indentation auto-indent new lines based on the current indentation. autoclose brackets determines whether typing an opening character like [ or { will cause the editor to insert the matching closing character ] or } for you. indent using spaces when chec...
...ndentation. autoclose brackets determines whether typing an opening character like [ or { will cause the editor to insert the matching closing character ] or } for you. indent using spaces when checked, indentation will be performed using spaces, when off, the editor will use tabs instead. tab size the frequency of tab stops in the editor. select 2, 4, or 8. keybindings choose the default codemirror keybindings or keybindings from one of several popular editors: vim emacs sublime text advanced settings show gecko platform data a setting to control whether or not profiles should include gecko platform symbols. disable http cache disable the browser http cache to simulate first-load performance in all tabs that have the toolbox open. this setting persists, meaning ...
Shader Editor - Firefox Developer Tools
rograms called shaders which are called at the appropriate stages of the opengl rendering pipeline: a vertex shader, which computes the clip space coordinates of each vertex to be drawn, and a fragment shader, which determines the color for each pixel to be drawn. these shaders are written in opengl shading language, or glsl. in webgl they can be included in a page in several ways: as text hardcoded in javascript strings, as separate files included using <script> tags, or retrieved from the server as plain text. javascript code running in the page then sends them for compilation using the webgl apis, and they're executed on the device's gpu when needed. with the shader editor, you can examine and edit the source of the vertex and fragment shaders. here's another screencast, showing how yo...
...are shown in the other two panes, and you can edit them. ...
Rich output - Firefox Developer Tools
t output to the clipboard once you have output in the console window, you can save it to the clipboard by right-clicking on the output and selecting export visible messages to clipboard: this will copy all of the output to the clipboard. then you can paste it into a document. the output will look something like this: console.log(todolist) array(4) [ {…}, {…}, {…}, {…} ] debugger eval code:1:9 undefined if you expand objects, such as arrays, you get slightly different content. for example, by expanding the array in the above list, i get the following: console.log(todolist) (4) […] ​ 0: object { status: "done", description: "morning pages", datecreated: 1552404478137 } ​ 1: object { status: "in progress", description: "refactor styles", datecreated: 1552404493169 } ​ 2: ob...
... ...
about:debugging (before Firefox 68) - Firefox Developer Tools
file, and select any file in that directory. the temporary add-on will be displayed under the "temporary extensions" header. you don't have to package or sign the add-on. the add-on will stay installed until you restart firefox. the big advantages of this method, compared with installing an add-on from an xpi, are: you don't have to rebuild an xpi and reinstall when you change the add-on's code you can load an add-on without signing it and without needing to disable signing. updating a temporary add-on if you install the add-on in this way, what happens when you update the add-on's files? before firefox 48 if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content...
... at https://serviceworke.rs/push-simple/. debugging workers for a service worker, if it is already running, you'll see two buttons next to it, labeled "debug" and "push". if it's not already running, you'll see one button, labeled "start": click this to start the service worker. clicking "debug" connects the javascript debugger and console to this worker. you can set breakpoints, step through code, watch variables, evaluate code, and so on: registering workers at first, you won't see any workers listed under service workers or shared workers. as soon as a worker is registered, the listing is updated: before firefox 47, service workers were only shown when they were actually running. unregistering service workers new in firefox 48. starting in firefox 48, you'll see a link nam...
about:debugging - Firefox Developer Tools
and select its manifest file. the temporary extension is then displayed under the temporary extensions header. you don't have to package or sign the extension before loading it, and it stays installed until you restart firefox. the major advantages of this method, compared with installing an add-on from an xpi, are: you don't have to rebuild an xpi and reinstall when you change the add-on's code; you can load an add-on without signing it and without needing to disable signing. once you have loaded a temporary extension, you can see information about it and perform operations on it. you can use the following buttons: inspect loads the extension in the debugger. reload reloads the temporary extension. this is handy when you have made changes to the extension. remove unloads t...
... you can see information about it and perform operations on it. you can use the following buttons: inspect loads the extension in the debugger. reload reloads the temporary extension. this is handy when you have made changes to the extension. remove unloads the temporary extension. other information about the extension is displayed: location the location of the extension's source code on your local system. extension id the temporary id assigned to the extension. internal uuid the internal uuid assigned to the extension. manifest url if you click the link, the manifest for this extension is loaded in a new tab. updating a temporary extension if you install an extension in this way, what happens when you update the extension? if you change files that are loaded on de...
AbstractRange - Web APIs
nt.createrange(); prange.selectnodecontents(document.queryselector("#entry1 p")); since we wish to select the entire contents of the <p> element, including its descendants, this works perfectly. ...
...ike this: notice especially that the contents of this fragment are all below the shared common parent of the topmost nodes within it. the parent <section> is not needed to replicate the cloned content, so it is isn't included. example consider this simple html fragment of html. <p><strong>this</strong> is a paragraph.</p> imagine using a range to extract the word "paragraph" from this. ...
AbstractWorker - Web APIs
ith abstractworker. properties the abstractworker interface doesn't inherit any properties. event handlers abstractworker.onerror an eventlistener which is invoked whenever an errorevent of type error bubbles through the worker. methods the abstractworker interface doesn't implement or inherit any methods. example as an abstract interface, you won't directly use abstractworker in your code. instead, you'll interact with either worker or sharedworker, both of which inherit the properties of abstractworker. this code snippet demonstrates the creation of a new worker using the worker() constructor; it also shows how to then send a message to the worker. var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value, second.value]); conso...
...redworker, both of which inherit the properties of abstractworker. this code snippet demonstrates the creation of a new worker using the worker() constructor; it also shows how to then send a message to the worker. var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } the worker's code is loaded from the file "worker.js". this code assumes that there's an <input> element represented by first; an event handler for the change event is established so that when the user changes the value of first, a message is posted to the worker to let it know. you can find more examples on the mdn web docs github repository: basic dedicated worker example (run dedicated worker). basic share...
Animation.onremove - Web APIs
nt handler for the remove event. this event is sent when the animation is removed (i.e., put into an active replace state). syntax var removehandler = animation.onremove; animation.onremove = removehandler; value a function to be called to handle the remove event, or null if no remove event handler is set. ...
...the event handler sets up an animation that animates the <div> element to the position of the mouse pointer. this could result in a huge animations list, which could create a memory leak. for this reason, modern browsers automatically remove overriding forward filling animations. a console message is logged each time an animation it removed, invoked when the remove even...
Animation.persist() - Web APIs
Web › API › Animation › persist
the persist() method of the web animations api's animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's automatically removing filling animations behavior. syntax animation.persist(); parameters none. return value none. ...
...the event handler sets up an animation that animates the <div> element to the position of the mouse pointer. this could result in a huge animations list, which could create a memory leak. for this reason, modern browsers automatically remove overriding forward filling animations. you can see the replacestate of the animation being logged at the end of the handler. this ...
Animation.replaceState - Web APIs
ctive: the initial value of the animation's replace state; when the animation has been removed by the browser's automatically removing filling animations behavior. persisted: the animation has been explicitly persisted by invoking animation.persist() on it. removed: the animation has been explicitly removed. ...
...the event handler sets up an animation that animates the <div> element to the position of the mouse pointer. this could result in a huge animations list, which could create a memory leak. for this reason, modern browsers automatically remove overriding forward filling animations. you can see the replacestate of the animation being logged at the end of the handler. this ...
Attr - Web APIs
Web › API › Attr
2px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">attr</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} warning: starting in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4), a number of deprecated properties and methods output warning messages to the console. you should revise your code accordingly. see deprecated properties and methods for a complete list. properties name read only the attribute's name. namespaceuri read only a domstring representing the namespace uri of the attribute, or null if there is no namespace. localname read only a domstring representing the local part of the qualified name of the attribute. prefix read only a domstring representing the ...
...the dom living standard reintroduced the property. gecko outputs a deprecation note starting from gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4). this note was removed again in gecko 49.0 (firefox 49.0 / thunderbird 49.0 / seamonkey 2.46). specified read only this property always returns true. originally, it returned true if the attribute was explicitly specified in the source code or by a script, and false if its value came from the default one defined in the document's dtd. value the attribute's value. note: dom level 3 defined namespaceuri, localname and prefix on the node interface. in dom4 they were moved to attr. this change is implemented in chrome since version 46.0 and firefox since version 48.0. deprecated properties and methods the following properties h...
AudioBuffer - Web APIs
once put into an audiobuffer, the audio can then be played by being passed into an audiobuffersourcenode. objects of these types are designed to hold small audio snippets, typically less than 45 s. for longer sounds, objects implementing the mediaelementaudiosourcenode are more suitable. ...
...he first channel). audiobuffer.copyfromchannel() copies the samples from the specified channel of the audiobuffer to the destination array. audiobuffer.copytochannel() copies the samples to the specified channel of the audiobuffer, from the source array. example the following simple example shows how to create an audiobuffer and fill it with random white noise. you can find the full source code at our webaudio-examples repository; a running live version is also available. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; // just random values between ...
AudioBufferSourceNode.loop - Web APIs
uffersourcenode.loop = true | false; value a boolean which is true if looping is enabled; otherwise, the value is false. when looping is enabled, the sound begins playing at the time specified as the start point when start() is called. when the time specified by the loopend property is reached, playback continues at the time specified by loopstart example in this example, the audiocontext.decodeaudiodata function is used to decode an audio track and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackrate property value on the fly. when the audio is played, it loops. you can run the full example live (or view the source.) function getdata() { source = audioctx.createbuffersource(); requ...
...backrate property value on the fly. when the audio is played, it loops. ...
AudioBufferSourceNode.playbackRate - Web APIs
ate. consider a sound buffer containing audio sampled at 44.1 khz (44,100 samples per second). let's see what a few values of playbackrate do: a playbackrate of 1.0 plays the audio at full speed, or 44,100 hz. a playbackrate of 0.5 plays the audio at half speed, or 22,050 hz. a playbackrate of 2.0 doubles the audio's playback rate to 88,200 hz. example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track, and put it into an audiobuffersourcenode. buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackrate property value on the fly. you can run the example live (or view the source.) play the song and alter the playback rate for some fun results. <input class="playback-rate-control" type="...
...class="playback-rate-control" type="range" min="0.25" max="3" step="0.05" value="1"> <span class="playback-rate-value">1.0</span> function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio, and range slider control...
AudioBufferSourceNode.start() - Web APIs
specifications specification status comment web audio apithe definition of 'start()' in that specification. working draft ...
...nning — you don't need to specify any parameters in this case: source.start(); the following more complex example will, 1 second from now, start playing 10 seconds worth of sound starting 3 seconds into the audio buffer. source.start(audioctx.currenttime + 1,3,10); for a more complete example showing start() in use, check out our audiocontext.decodeaudiodata() example, you can also run the code example live, or view the source. specifications specification status comment web audio apithe definition of 'start()' in that specification. working draft ...
AudioBufferSourceNode - Web APIs
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 between -1.0 and 1.0 for (var channel = 0; channel < myarrayb...
... // get an audiobuffersourcenode. // this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; // connect the audiobuffersourcenode to the // destination so we can hear the sound source.connect(audioctx.destination); // start the source playing source.start(); for a decodeaudiodata() example, see the audiocontext.decodeaudiodata() page. specifications specification status comment web audio apithe definition of 'audiobuffersourcenode' in that specification. working draft ...
AudioConfiguration - Web APIs
e being tested when calling mediacapabilities.encodinginfo() or mediacapabilities.decodinginfo() to query whether a specific audio configuration is supported, smooth, and/or power efficient. properties the audioconfiguration dictionary is made up of four audio properties, including: contenttype: a valid audio mime type, for information on possible values and what they mean, see the web audio codec guide. channels: the number of channels used by the audio track. bitrate: the number of bits used to encode one second of the audio file. samplerate: the number of audio samples making up one second of the audio file. examples //create media configuration to be tested const mediaconfig = { type : 'file', // 'record', 'transmission', or 'media-source' audio : { contenttype...
...: the number of audio samples making up one second of the audio file. examples //create media configuration to be tested const mediaconfig = { type : 'file', // 'record', 'transmission', or 'media-source' audio : { contenttype : "audio/ogg", // valid content type channels : 2, // audio channels used by the track bitrate : 132700, // number of bits used to encode 1s of audio samplerate : 5200 // number of audio samples making up that 1s. } }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ? '' : 'not ') + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : 'no...
AudioWorkletGlobalScope - Web APIs
as the global execution context is shared across the current baseaudiocontext, it's possible to define any other variables and perform any actions allowed in worklets — apart from defining audioworkletprocessor-derived classes. ...
... as the global execution context is shared across the current baseaudiocontext, it's possible to define any other variables and perform any actions allowed in worklets — apart from defining audioworkletprocessor-derived classes. ...
AuthenticatorAttestationResponse.attestationObject - Web APIs
as an attestationobject for that keypair. the public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, android or tpm attestations). syntax attestobj = authenticatorattestationresponse.attestationobject properties after decoding the cbor encoded arraybuffer, the resulting javascript object will contain the following properties: authdata the same as authenticatorassertionresponse.authenticatordata. note that in authenticatorassertionresponse, the authenticatordata is exposed as a property in a javascript object while in authenticatorattestationresponse, the authenticatordata is a property in a cbor map. the same authenticatorasserti...
... recommendation initi...
BaseAudioContext.createConvolver() - Web APIs
emise is that you create an audiobuffer containing a sound sample to be used as an ambience to shape the convolution (called the impulse response,) and apply that to the convolver. the example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = aja...
...udiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ... convolver.buffer = concerthallbuffer; specifications specification status comment web audio apithe definition...
BasicCardRequest - Web APIs
cardrequest.supportedtypes optional secure context this obsolete property was used to provide an optional array of domstrings representing the card types that the retailer supports (e.g. credit, debit, prepaid). if the property is missing, it implies that all the card types are supported. instead of using this property, it is up to the server to check support for the card given the information coded into the account number. card network identifiers the w3c maintains an official list of approved card network identifier strings, which may be used in the supportednetworks list. those are: amex cartebancaire diners discover jcb mastercard mir unionpay visa examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes ...
...es successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'basiccardrequest' in that specification. working draft initial definition. ...
Using the Beacon API - Web APIs
ar data = json.stringify({ location: location.href, time: date() }); navigator.sendbeacon('/analytics', data); }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identically to the usual method, but is accessible from worker global scope. in the following example, a worker sends a beacon using the url and data from the global context. ...
...object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworker.postmessage([url, data]); // set up a message handler to receive the success/fail message from the worker myworker.onmessage = function(event) { var msg = event.data; // log worker's send status console.log("worker reply: sendbeacon() status = " + msg); }; } this code snippet is for the worker (worker-using.js): onmessage = function(event) { var msg = event.data; // split the url and data from the message var url = msg[0]; var data = msg[1]; // if the browser supports worker sendbeacon(), then send the beacon; otherwise // return failure message to the global context if (self.navigator.sendbeacon) { var status = self.navigator.sendbeacon(ur...
Beacon API - Web APIs
-blocking request to a web server. beacon requests use the http post method and requests typically do not require a response. requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest). example use cases of the beacon api are logging activity and sending analytics data to the server. example code of the interfaces described in this document is included in using the beacon api. why use beacon? the beacon interface addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server before unloading the document. sending the data any sooner may result in a missed opportunity to gather data. however, ensuring that the data is sent during the unloading ...
... server before unloading the document. sending the data any sooner may result in a missed opportunity to gather data. however, ensuring that the data is sent during the unloading of a document is something that has traditionally been difficult for developers. user agents will typically ignore asynchronous xmlhttprequests made in an unload handler. to solve this problem, analytics and diagnostics code will typically make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data. the synchronous xmlhttprequest forces the browser to delay unloading the document, and makes the next navigation appear to be slower. there is nothing the next page can do to avoid this perception of poor page load performance. there are other techniques used to ensure that data is submitted...
Body.arrayBuffer() - Web APIs
Web › API › Body › arrayBuffer
you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track. we also use audiocontext.createbuffersource to create an audio buffer source. when the fetch is successful, we read an arraybuffer out of the response using arraybuffer(), decode the audio data using audiocontext.decodeaudiodata, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the audiocontext.destination. once getdata() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.) function get...
...g, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.) function getdata() { source = audioctx.createbuffersource(); var myrequest = new request('viper.ogg'); fetch(myrequest).then(function(response) { return response.arraybuffer(); }).then(function(buffer) { audioctx.decodeaudiodata(buffer, function(decodeddata) { source.buffer = decodeddata; source.connect(audioctx.destination); }); }); }; // wire up buttons to stop and play audio play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); } reading files the response() constructor accepts files and blobs, so it may be used to read a file into other...
CSSMathValue.operator - Web APIs
interface value cssmathsum "sum" cssmathproduct "product" cssmathmin "min" cssmathmax "max" cssmathclamp "clamp" cssmathnegate "negate" cssmathinvert "invert" examples we create an element with a width determined using a calc() function, then console.log() the operator. ...
...face value cssmathsum "sum" cssmathproduct "product" cssmathmin "min" cssmathmax "max" cssmathclamp "clamp" cssmathnegate "negate" cssmathinvert "invert" examples we create an element with a width determined using a calc() function, then console.log() the operator. ...
CanvasRenderingContext2D.drawWindow() - Web APIs
context2d.drawwindow() method of the canvas 2d api renders a region of a window into the canvas. the contents of the window's viewport are rendered, ignoring viewport clipping and scrolling. this api cannot be used by web content. it is synchronous, and as such can't be compatible with fission. if you're using it from an extension, you should switch to tabs.capturetab. if you're writing chrome code, you probably want windowglobalparent.drawsnapshot from the parent process. syntax void ctx.drawwindow(window, x, y, w, h, bgcolor [, flags]); parameters window the window to render. x the x-axis coordinate of the window. y the y-axis coordinate of the window. w the width of the window. h the height of the window. bgcolor a domstring that specifies the color the canvas is filled...
...ow_draw_view 0x04 draw scrollbars and scroll the viewport if they are present. drawwindow_use_widget_layers 0x08 use the widget layer manager if available. this means hardware acceleration may be used, but it might actually be slower or lower quality than normal. it will, however, more accurately reflect the pixels rendered to the screen. drawwindow_async_decode_images 0x10 do not synchronously decode images - draw what we have. example this method draws a snapshot of the contents of a dom window into the canvas. for example, ctx.drawwindow(window, 0, 0, 100, 200, 'rgb(255,255,255)'); ... would draw the contents of the current window, in the rectangle (0,0,100,200) in pixels relative to the top-left of the viewport, on a white ba...
CanvasRenderingContext2D.fillText() - Web APIs
ll adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. return value undefined. examples drawing filled text this example writes the words "hello world" using the filltext() method. html first, we need a canvas to draw into. ...
...o a smaller font size in order to fit the text in the specified width. return value undefined. examples drawing filled text this example writes the words "hello world" using the filltext() method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels across. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.filltext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context. with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call filltext() to draw ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
2d path to check against. if unspecified, the current path is used. return value boolean a boolean, which is true if the specified point is contained in the current or specified path, otherwise false. examples checking a point in the current path this example uses the ispointinpath() method to check if a point is within the current path. ...
.... if unspecified, the current path is used. return value boolean a boolean, which is true if the specified point is contained in the current or specified path, otherwise false. examples checking a point in the current path this example uses the ispointinpath() method to check if a point is within the current path. html <canvas id="canvas"></canvas> <p>in path: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innertext = ctx.ispointinpath(30, 70); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in a circular path2d path. if yes...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
. if unspecified, the current path is used. return value boolean a boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. examples checking a point in the current path this example uses the ispointinstroke() method to check if a point is within the area of the current path's stroke. ...
...rrent path is used. return value boolean a boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. examples checking a point in the current path this example uses the ispointinstroke() method to check if a point is within the area of the current path's stroke. ...
CanvasRenderingContext2D.strokeText() - Web APIs
ust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. return value undefined. examples drawing text outlines this example writes the words "hello world" using the stroketext() method. html first, we need a canvas to draw into. ...
...smaller font size in order to fit the text in the specified width. return value undefined. examples drawing text outlines this example writes the words "hello world" using the stroketext() method. html first, we need a canvas to draw into. this code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.stroketext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context. with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call stroketext() to d...
Compositing example - Web APIs
this sample program demonstrates a number of compositing operations. the output looks like this: compositing example this code sets up the global values used by the rest of the program. var canvas1 = document.createelement("canvas"); var canvas2 = document.createelement("canvas"); var gco = [ 'source-over','source-in','source-out','source-atop', 'destination-over','destination-in','destination-out','destination-atop', 'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity' ].reverse(); var gcotext = [ 'this is the default setting and draws new shapes on top of the existing canvas con...
...he top layer.', 'preserves the luma and hue of the bottom layer, while adopting the chroma of the top layer.', 'preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.', 'preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.' ].reverse(); var width = 320; var height = 340; main program when the page loads, this code runs to set up and run the example: window.onload = function() { // lum in srgb var lum = { r: 0.33, g: 0.33, b: 0.33 }; // resize canvas canvas1.width = width; canvas1.height = height; canvas2.width = width; canvas2.height = height; lightmix() colorsphere(); runcomposite(); return; }; and this code, runcomposite(), handle...
Compositing and clipping - Web APIs
sting 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 is like a normal canvas shape but it acts as a mask to hide unwanted parts of shapes. this is visualized in the image on the right. the red star shape is our clipping path. everything that falls outside of this path won't get drawn on the canvas. if we compare clipping paths to the globalcompositeoperation property we've seen above, w...
...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...
Finale - Web APIs
Web › API › Canvas API › Tutorial › Finale
html5 canvas tutorials examples for most canvas apis. game development gaming is one of the most popular computer activities. ...
... html5 canvas tutorials examples for most canvas apis. game development gaming is one of the most popular computer activities. ...
CloseEvent.initCloseEvent() - Web APIs
event before it is dispatched, using eventtarget.dispatchevent(). once dispatched, it doesn't do anything anymore. do not use this method anymore as it is deprecated. instead use specific event constructors, like closeevent(). the page on creating and triggering events gives more information about the way to use these. syntax event.initmouseevent(type, canbubble, cancelable, wasclean, reasoncode, reason); parameters type the string to set the event's type to. possible types for mouse events include: click, mousedown, mouseup, mouseover, mousemove, mouseout. canbubble whether or not the event can bubble. sets the value of event.bubbles. cancelable whether or not the event's default action can be prevented. sets the value of event.cancelable. wasclean whether or not the connecti...
... the string to set the event's type to. possible types for mouse events include: click, mousedown, mouseup, mouseover, mousemove, mouseout. canbubble whether or not the event can bubble. sets the value of event.bubbles. cancelable whether or not the event's default action can be prevented. sets the value of event.cancelable. wasclean whether or not the connection was cleanly closed. reasoncode the reason of the close. reason a domstring describing the reason of the close in shuman-readable way. specifications this is no part of any specifications, though it was in some early drafts. ...
ConstantSourceNode - Web APIs
then the constantsourcenode is created by calling audiocontext.createconstantsource(), and the gain parameters of each of the two gain nodes are connected to the constantsourcenode. after starting the constant source by calling its start() method. finally, the two gain nodes are conn...
...d to the constantsourcenode. after starting the constant source by calling its start() method. finally, the two gain nodes are connected to the audio destination (typically speakers or headphones). now, whenever the value of constantnode.offset changes, the gain on both gainnode2 and gainnode3 will change to have that same value. to see this example in action, as well as to read the rest of the code from which these snippets were derived, see controlling multiple parameters with constantsourcenode. specification specification status comment web audio apithe definition of 'constantsourcenode' in that specification. working draft ...
ConvolverNode - Web APIs
impulse response from the buffer will be scaled by an equal-power normalization when the buffer attribute is set, or not. methods no specific method; inherits methods from its parent, audionode. convolvernode example the following example shows basic usage of an audiocontext to create a convolver node. note: you will need to find an impulse response to complete the example below. ...
...to complete the example below. see this codepen for an applied example. let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ... let reverb = await createreverb(); // someotheraudionode -> reverb -> destination someotheraudionode.connect(reverb); reverb.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'convolvernode' in that specification. working draft ...
DOMPointReadOnly() - Web APIs
syntax point = new dompointreadonly(x, y, z, w); parameters x optional the value of the horizontal coordinate, x, as a floating point number. the default value is 0. y optional the value of the vertical coordinate, y, as a floating point number. the default value is 0. z optional the value of the depth coordinate, z, as a floating point number. the default value is 0. ...
...ault value is 0. w optional the value of the perspective, w, as a floating point number. the default is 1. note: each of these values is what's called an unrestricted number. in addition to any finite floating-point value, you may use special values such as ±infinity and nan. return value a new dompointreadonly object representing the specified location in space. examples the following code demonstrates creating both 2d and 3d points. var point2d = new dompointreadonly(50, 25); var point3d = new dompointreadonly(50, 0, 10); var perspectivepoint3d = new dompointreadonly(50, 50, 25, 0.5); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly' in that specification. candidate recommendation ini...
DedicatedWorkerGlobalScope - Web APIs
er, which is a regular performance object, but with a subset of its properties and methods available. event handlers this interface inherits event handlers from the workerglobalscope interface, and its parent eventtarget, and therefore implements event handlers from windowtimers, windowbase64, and windoweventhandlers. dedicatedworkerglobalscope.onmessage is an eventhandler representing the code to be called when the message event is raised. these events are of type messageevent and will be called when the worker receives a message from the document that started it (i.e. from the worker.postmessage method.) dedicatedworkerglobalscope.onmessageerror is an eventhandler representing the code to be called when the messageerror event is raised. methods this interface inherits methods fro...
...arent document that first spawned the worker. inherited from workerglobalscope workerglobalscope.dump() writes a message to the console. workerglobalscope.importscripts() imports one or more scripts into the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding. 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 ex...
Document.documentURIObject - Web APIs
the document.documenturiobject read-only property returns an nsiuri object representing the uri of the document. this only works for privileged (universalxpconnect) scripts, including extension code. for web content this property doesn't have any special meaning and can be used just like any other custom property. privileged code must be careful not to try getting or setting this property on a non-wrapped content object (e.g., on a wrappedjsobject of an xpcnativewrapper). see bug 324464's comments for details. ...
... and can be used just like any other custom property. privileged code must be careful not to try getting or setting this property on a non-wrapped content object (e.g., on a wrappedjsobject of an xpcnativewrapper). see bug 324464's comments for details. syntax var uri = document.documenturiobject; example // check that the uri scheme of the current tab in firefox is 'http', // assuming this code runs in context of browser.xul let uriobj = content.document.documenturiobject; let uriport = uriobj.port; if (uriobj.schemeis('http')) { ... } specifications not part of any specification. ...
Document: keypress event - Web APIs
event has been deprecated, you should look to use beforeinput or keydown instead. ...
...vate event; other event examples addeventlistener keypress example this example logs the keyboardevent.code value whenever you press a key. ...
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
obsolete css object model (cssom) view modulethe definition of 'elementsfrompoint()' in that specification. working draft ...
... obsolete css object model (cssom) view modulethe definition of 'elementsfrompoint()' in that specification. working draft ...
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
syntax var node = document.nodefrompoint(x, y); parameters x a double representing the horizontal coordinate of a point. y a double representing the vertical coordinate of a point. returns a node object. ...
...ct. examples html content <div> <p>some text</p> </div> <p>top node at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodefrompoint) { var node = document.nodefrompoint(30, 20); output.textcontent += node.localname; } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code>document.nodefrompoint()</code>" + "</span>"; } specifications not part of any specification at present. ...
Introduction to the DOM - Web APIs
page, which can be modified with a scripting language such as javascript. the w3c dom and whatwg dom standards are implemented in most modern browsers. many browsers extend the standard, so care must be exercised when using them on the web where documents may be accessed by various browsers with different doms. for example, the standard dom specifies that the getelementsbytagname method in the code below must return a list of all the <p> elements in the document: const paragraphs = document.getelementsbytagname("p"); // paragraphs[0] is the first <p> element // paragraphs[1] is the second <p> element, etc. alert(paragraphs[0].nodename); all of the properties, methods, and events available for manipulating and creating web pages are organized into objects (for example, the document object...
...!"); heading.appendchild(heading_text); document.body.appendchild(heading); } </script> </head> <body> </body> </html> fundamental data types this reference tries to describe the various objects and types in simple terms. but there are a number of different data types being passed around the api that you should be aware of. note: because the vast majority of code that uses the dom revolves around manipulating html documents, it's common to refer to the nodes in the dom as elements, although strictly speaking not every node is an element. the following table briefly describes these data types. data type (interface) description document when a member returns an object of type document (e.g., the ownerdocument property of an el...
Document Object Model (DOM) - Web APIs
to achieve this, the following interfaces present in the different dom level 3 or earlier specifications have been removed. it is uncertain whether some may be reintroduced in the future or not, but for the time being they should be consid...
...to achieve this, the following interfaces present in the different dom level 3 or earlier specifications have been removed. it is uncertain whether some may be reintroduced in the future or not, but for the time being they should be considered obsolete a...
EXT_shader_texture_lod - Web APIs
the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl1 contexts. in webgl2, the functionality of this extension is available on the webgl2 context by default. it requires glsl #version 300 es. ...
...d, float lod) vec4 texture2dgradext(sampler2d sampler, vec2 p, vec2 dpdx, vec2 dpdy) vec4 texture2dprojgradext(sampler2d sampler, vec3 p, vec2 dpdx, vec2 dpdy) vec4 texture2dprojgradext(sampler2d sampler, vec4 p, vec2 dpdx, vec2 dpdy) vec4 texturecubegradext(samplercube sampler, vec3 p, vec3 dpdx, vec3 dpdy) examples enabling the extensions: gl.getextension('ext_shader_texture_lod'); shader code that avoids artifacts when wrapping texture coordinates: <script type="x-shader/x-fragment"> #extension gl_ext_shader_texture_lod : enable #extension gl_oes_standard_derivatives : enable uniform sampler2d mytexture; varying vec2 texcoord; void main(){ gl_fragcolor = texture2dgradext(mytexture, mod(texcoord, vec2(0.1, 0.5)), dfdx(texcoord), dfdy(texcoord)); }...
EffectTiming.fill - Web APIs
Web › API › EffectTiming › fill
} all this does is specify the size, border, and color information, as well as indicate that the box should be centered both vertically and horizontally inside its container. note that there's no rotation applied. javascript content now let's check out the javascript. first we'll define the two objects that describe the keyframes and the timing configuration to use, then we'll actually see the code that triggers and runs the animation when the "animatebutton" button is clicked. var boxrotationkeyframes = [ { transform: "rotate(-90deg)" }, { transform: "rotate(90deg)" } ]; the boxrotationkeyframes object is an array of keyframes, each describing the state of the affected element at a point in the animation process. in this case, we have just two keyframes; the first defines what affec...
...that the fill mode should be "none". as defined above, the "none" fill mode means that the element will be rendered in its natural, unaltered condition anytime the animation isn't actively running. document.getelementbyid("animatebutton").addeventlistener("click", event => { document.getelementbyid("box").animate( boxrotationkeyframes, boxrotationtiming ); }, false); the rest of the code is pretty simple: it adds an event listener to the "animate" button so that when it's clicked by the user, the box is animated by calling element.animate() on it, providing the boxrotationkeyframes and boxrotationtiming objects to describe the animation that should occur. result below we see what the result looks like. notice how before the animation starts running, the box is upright, then upo...
Element.getElementsByClassName() - Web APIs
document.getelementbyid('main').getelementsbyclassname('test'); matching multiple classes to find elements whose class lists include both the red and test classes: element.getelementsbyclassname('red test'); examining the results you can use either the item() method on the returned htmlcollection or standard array syntax to examine individual elements in the collection. however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed. var matches = element.getelementsbyclassname('colorbox'); for (var i=0; i<matches.length; i++) { matches[i].classlist.remove('colorbox'); matches.item(i).classlist.add('hueframe'); } instead, use another method, such as: var matches = element.getelementsbyclassname('colorbox'); wh...
...another element (if any are left) will then become item(0). filtering the results using array methods we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value. here we'll find all <div...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
ute: 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 replaced with a display of the page's entire source code. document.documentelement.innerhtml = "<pre>" + document.documentelement.innerhtml.replace(/</g,"&lt;") + "</pre>"; operational details what exactly happens when you set value of innerhtml? doing so causes the user agent to follow these steps: the specified value is parsed as html or xml (based on the document type), resulting in a documentfragment object representing t...
...' onerror='alert(1)'>"; el.innerhtml = name; // shows the alert for that reason, it is recommended that you do not use innerhtml when inserting plain text; instead, use node.textcontent. this doesn't parse the passed content as html, but instead inserts it as raw text. warning: if your project is one that will undergo any form of security review, using innerhtml most likely will result in your code being rejected. for example, if you use innerhtml in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process. example this example uses innerhtml to create a mechanism for logging messages into a box on a web page. javascript function log(msg) { var logelem = document.queryselector(".log"); var time = new date(); var timestr = ...
Element.insertAdjacentText() - Web APIs
eforebegin and afterend positions work only if the node is in a tree and has an element parent. example beforebtn.addeventlistener('click', function() { para.insertadjacenttext('afterbegin',textinput.value); }); afterbtn.addeventlistener('click', function() { para.insertadjacenttext('beforeend',textinput.value); }); have a look at our insertadjacenttext.html demo on github (see the source code too.) here we have a simple paragraph. you can enter some text into the form element, then press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext(). note that the existing text node is not added to — further text nodes are created containing the new additions. polyfill you can polyfill the insertadjacenttext() method ...
...e form element, then press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext(). note that the existing text node is not added to — further text nodes are created containing the new additions. ...
Element.requestFullscreen() - Web APIs
document or in an <iframe> which has the allowfullscreen attribute applied to it. additionally, of course, the feature policy "fullscreen" permission must be granted. detecting full-screen activation you can determine whether or not your attempt to switch to full-screen mode is successful by using the promise returned by requestfullscreen(), as seen in the example below. to learn when other code has toggled full-screen mode on and off, you should establish listeners for the fullscreenchange event on the document. it's also important to listen for fullscreenchange to be aware when, for example, the user manually toggles full-screen mode, or when the user switches applications, causing your application to temporarily exit full-screen mode. examples this function toggles the first <video>...
...value—we call the video's requestfullscreen() method. we don't need to do anything special if successful, but if the request fails, our promise's catch() handler presents an alert with an appropriate error message. if, on the other hand, full-screen mode is already in effect, we call document.exitfullscreen() to disable full-screen mode. you can see this example in action or view or remix the code on glitch. specifications specification status comment fullscreen apithe definition of 'element.requestfullscreen()' in that specification. living standard initial definition ...
Event - Web APIs
Web › API › Event
click() method of an element, or by defining the event, then sending it to a specified target using eventtarget.dispatchevent(). there are many types of events, some of which use other interfaces based on the main event interface. event itself contains the properties and methods which are common to all events. many dom elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. event-handlers are usually connected (or "attached") to various html elements (such as <button>, <div>, <span>, etc.) using eventtarget.addeventlistener(), and this generally replaces using the old html event handler attributes. further, when properly added, such handlers can also be disconnected if needed using removeeventlistener(). note: one element...
...ious html elements (such as <button>, <div>, <span>, etc.) using eventtarget.addeventlistener(), and this generally replaces using the old html event handler attributes. further, when properly added, such handlers can also be disconnected if needed using removeeventlistener(). note: one element can have several such handlers, even for the exact same event—particularly if separate, independent code modules attach them, each for its own independent purposes. (for example, a webpage with an advertising-module and statistics-module both monitoring video-watching.) when there are many nested elements, each with its own handler(s), event processing can become very complicated—especially where a parent element receives the very same event as its child elements because "spatially" they overlap...
ExtendableEvent - Web APIs
bleevent object. properties doesn't implement any specific properties, but inherits properties from its parent, event. methods inherits methods from its parent, event. extendableevent.waituntil() extends the lifetime of the event. it is intended to be called in the install eventhandler for the installing worker and on the activate eventhandler for the active worker. examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall, delaying treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resources have been fetched and cached, or else when any exception occurs. the ...
...though there's only one cache in this example, the same approach can be used for multiple caches. it maps a shorthand identifier for a cache to a specific, versioned cache name. ...
FetchEvent.request - Web APIs
t read-only property of the fetchevent interface returns the request that triggered the event handler. this property is non-nullable (since version 46, in the case of firefox.) if a request is not provided by some other means, the constructor init object must contain a request (see fetchevent.fetchevent().) syntax var recentrequest = fetchevent.request; value a request object. example this code snippet is from the service worker fetch sample (run the fetch sample live). the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code fetches a response from the network. the cod...
....respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the serviceworkerglobalscope.fetch operation. note that an http error response (e.g., 404) will not trigger an exception. it will return a normal response object that has the appropriate error code set. self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache. about to fetch from network...'); ...
FileEntrySync - Web APIs
hod overview filewritersync createwriter () raises (fileexception); file file () raises (fileexception); methods createwriter() creates a new filewriter associated with the file that the fileentry represents. void createwriter ( ) raises (fileexception); parameter none. returns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. file() returns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. returns file exceptions th...
...d_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. file() returns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. returns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-...
FileReader.readAsDataURL() - Web APIs
the readasdataurl method is used to read the contents of the specified blob or file. when the read operation is finished, the readystate becomes done, and the loadend is triggered. at that time, the result attribute contains the data as a data: url representing the file's data as a base64 encoded string. note: the blob's result cannot be directly decoded as base64 without first removing the data-url declaration preceding the base64-encoded data. to retrieve only the base64 encoded string, first remove data:*/*;base64, from the result. syntax instanceoffilereader.readasdataurl(blob); parameters blob the blob or file from which to read. example html <input type="file" onchange="previewfile()"><br> <img src="" height="200" alt="image preview..."> javascript function previe...
...see also this more powerful example. specifications specification status comment file apithe definition of 'readasdataurl()' in that specification. working draft initial definition ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
yentry object representing the directory in question. errorcallback optional a method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. return value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the fileerror.code specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the directory doesn't exist. fileerror.path_exists_err the create and exclusive options were both true, indicating that the directory should be created but must not already exist, but the directory does in fact already exist. fileerror.security_err...
...n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is pass...
FileSystemDirectoryEntry.getFile() - Web APIs
y object representing the file in question. errorcallback optional a method to be called if an error occurs. receives as its sole input parameter a fileerror object describing the error which occurred. return value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the {domxref("fileerror.code")}} specifies what type of error occurred, as follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the file doesn't exist. fileerror.path_exists_err the create and exclusive options were both true, indicating that the file should be created but must not already exist, but the file does in fact already exist. fileerror.security_err the reque...
...n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is pass...
FileSystemEntry.toURL() - Web APIs
able to your web site or app, you can call tourl() to get its url for use in html. if your site is located at http://my-awesome-website.woot, and you have a temporary file system that contains an image file named awesomesauce.jpg, the url returned by tourl() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". ...
...ile named awesomesauce.jpg, the url returned by tourl() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". code that makes use of this might look like this: let img = document.createelement("img"); img.src = imagefileentry.tourl(); document.body.appendchild(img); assuming the scenario mentioned before the code, the result would be html that looks like this being appended to the end of the document: <img src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"> browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. d...
FontFace.FontFace() - Web APIs
Web › API › FontFace › FontFace
e that will be used as the font face value for font properties. takes the same type of values as the font-family descriptor of @font-face . source the font source. this can be either: a url binary font data descriptors optional a set of optional descriptors passed as an object. ...
... used as the font face value for font properties. takes the same type of values as the font-family descriptor of @font-face . source the font source. this can be either: a url binary font data descriptors optional a set of optional descriptors passed as an object. ...
Guide to the Fullscreen API - Web APIs
n full-screen mode by simply calling its requestfullscreen() method. let's consider this <video> element: <video controls id="myvideo"> <source src="somevideo.webm"></source> <source src="somevideo.mp4"></source> </video> we can put that video into full-screen mode as follows: var elem = document.getelementbyid("myvideo"); if (elem.requestfullscreen) { elem.requestfullscreen(); } this code checks for the existence of the requestfullscreen() method before calling it. presentation differences it's worth noting a key difference here between the gecko and webkit implementations at this time: gecko automatically adds css rules to the element to stretch it to fill the screen: "width: 100%; height: 100%". webkit doesn't do this; instead, it centers the fullscreen element at the same siz...
...r page, changing tabs, or switching to another application (using, for example, alt-tab) while in fullscreen mode exits fullscreen mode as well. example in this example, a video is presented in a web page. pressing the return or enter key lets the user toggle between windowed and fullscreen presentation of the video. view live examples watching for the enter key when the page is loaded, this code is run to set up an event listener to watch for the enter key. document.addeventlistener("keydown", function(e) { if (e.keycode == 13) { togglefullscreen(); } }, false); toggling fullscreen mode this code is called when the user hits the enter key, as seen above. function togglefullscreen() { if (!document.fullscreenelement) { document.documentelement.requestfullscreen(); } e...
Fullscreen API - Web APIs
errors occur during the process of changing between full-screen and windowed modes. event handlers for these events are available on the document and element interfaces. note: these event handler properties are not available as html content attributes. in other words, you cannot specify event handlers for fullscreenchange and fullscreenerror in the html content. they must be added by javascript code. event handlers on documents document.onfullscreenchange an event handler for the fullscreenchange event that's sent to a document when that document is placed into full-screen mode, or when that document exits full-screen mode. this handler is called only when the entire document is presented in full-screen mode. document.onfullscreenerror an event handler for the fullscreenerror event t...
...ther page, changing tabs, or switching to another application using any application switcher (or alt-tab) will likewise exit full-screen mode. example in this example, a video is presented in a web page. pressing the return or enter key lets the user toggle between windowed and full-screen presentation of the video. view live examples watching for the enter key when the page is loaded, this code is run to set up an event listener to watch for the enter key. document.addeventlistener("keypress", function(e) { if (e.keycode === 13) { togglefullscreen(); } }, false); toggling full-screen mode this code is called by the event handler above when the user hits the enter key. function togglefullscreen() { if (!document.fullscreenelement) { document.documentelement.requestfu...
GlobalEventHandlers.onanimationcancel - Web APIs
@keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the animation is described as taking place an infinite number of times, alternating direction each time, the box will glide back and forth between the two corners until stopped or the page is closed. javascript before we get to the animation code, we define a function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.in...
...function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the handlecancelevent() function, which is called in response to the animationcancel event, as set up in the html above. all we do here is log information to the console, but you might find other use cases, such as starting a new animation ...
GlobalEventHandlers.onanimationiteration - Web APIs
e target, where the target object is an html element (htmlelement), document (document), or window (window). the function receives as input a single parameter: an animationevent object describing the event which occurred. example let's create an animation which automatically pauses at the end of each iteration, allowing the user to choose whether or not to start the next iteration. much of this code is the same as in other examples of animation events, so it may look familiar. html <div class="main"> <div id="box"> <div id="text">box</div> </div> </div> <div class="button" id="play"> begin demonstration </div> css :root { --boxwidth:50px; } .main { width: 300px; height:300px; border: 1px solid black; } .button { cursor: pointer; width: 300px; border: 1px sol...
... 0s infinite alternate both paused slidebox; } the animation's keyframes are defined next; they describe an animation which causes the box to migrate from the top-left corner of the container to the bottom-right corner. @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } javascript some javascript code will need to be written to handle the click on the button to start the next iteration. let's have a look. var box = document.getelementbyid("box"); var iterationcounter = 0; box.onanimationiteration = function(event) { box.style.animationplaystate = "paused"; document.getelementbyid("play").innerhtml = "start iteration #" + (iterationcounter+1); }; this sets up two global variables: box, ...
GlobalEventHandlers.onkeydown - Web APIs
the onkeydown property of the globaleventhandlers mixin is an eventhandler that processes keydown events. the keydown event fires when the user presses a keyboard key. syntax target.onkeydown = functionref; value functionref is a function name or a function expression. the function receives a keyboardevent object as its sole argument. ...
...sion. the function receives a keyboardevent object as its sole argument. example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element. html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeydown = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result specifications specification status comment html living standardthe definition of 'onkeydown' in that specification. living standard ...
GlobalEventHandlers.onkeyup - Web APIs
the onkeyup property of the globaleventhandlers mixin is an eventhandler that processes keyup events. the keyup event fires when the user releases a key that was previously pressed. syntax target.onkeyup = functionref; value functionref is a function name or a function expression. the function receives a keyboardevent object as its sole argument. ...
...xpression. the function receives a keyboardevent object as its sole argument. example this example logs the keyboardevent.code value whenever you release a key inside the <input> element. html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeyup = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result specifications specification status comment html living standardthe definition of 'onkeyup' in that specification. living standard ...
GlobalEventHandlers.onpointerdown - Web APIs
r = target.onpointerdown; value a function to handle the pointerdown event for the target element, document, or window. it receives as input the pointerevent describing the pointerdown event. example this example demonstrates how to watch for and act upon pointerdown events using onpointerdown. you could also use addeventlistener(), of course. javascript first, let's look at the javascript code that handles the pointerdown event. var targetbox = document.getelementbyid("target"); targetbox.onpointerdown = handledown; function handledown(evt) { var action; switch(evt.pointertype) { case "mouse": action = "clicking"; break; case "pen": action = "tapping"; break; case "touch": action = "touching"; break; default: action = "i...
...fault() method is called to ensure that the mousedown event isn't triggered, potentially causing events to be handled twice if we had a handler for those events in case pointer event support is missing. we also have a handler for pointerup events: targetbox.onpointerup = handleup; function handleup(evt) { targetbox.innerhtml = "tap me, click me, or touch me!"; evt.preventdefault(); } this code's job is to just restore the original text into the target box after the user's interaction with the element ends (for example, when they release the mouse button, or when they lift the stylus or finger from the screen). in addition, the event's preventdefault() method is called to ensure that the mouseup event isn't triggered unnecessarily. html the html is extremely simple: <div id="targe...
GlobalEventHandlers.onresize - Web APIs
ze property of the globaleventhandlers interface is an eventhandler that processes resize events. the resize event fires after the window has been resized. syntax window.onresize = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. ...
...f the globaleventhandlers interface is an eventhandler that processes resize events. the resize event fires after the window has been resized. syntax window.onresize = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. ...
HTMLCanvasElement.toBlob() - Web APIs
es 0.92 and 0.80 are used for image/jpeg and image/webp respectively. other arguments are ignored. return value none. exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents come from secure examples getting a file representing the canvas once you have drawn content into a canvas, you can convert it into a file of any supported image format. the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a new <img> element to the document, whose source image is the one created using the canvas. var canvas = document.getelementbyid('canvas'); canvas.toblob(function(blob) { var newimg = document.createelement('img'), url = url.createobjecturl(blob); ...
... var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconname) { return function(b) { var r = new filereader(); r.onloadend = function () { /...
HTMLElement.hidden - Web APIs
otherwise, the value is false. example here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request. javascript document.getelementbyid("okbutton") .addeventlistener("click", function() { document.getelementbyid("welcome").hidden = true; document.getelementbyid("awesome").hidden = false; }, false); this code sets up a handler for the welcome panel's "ok" button that hides the welcome panel and makes the follow-up panel—with the curious name "awesome"—visible in its place. html the html for the two boxes are shown here. the welcome panel <div id="welcome" class="panel"> <h1>welcome to foobar.com!</h1> <p>by clicking "ok" you agree to be awesome every day!</p> <button class="button" id="o...
...el"> <h1>welcome to foobar.com!</h1> <p>by clicking "ok" you agree to be awesome every day!</p> <button class="button" id="okbutton">ok</button> </div> this html creates a panel (in a <div> block) that welcomes the user to a site and tells them what they're agreeing to by clicking the ok button. the follow-up panel once the user clicks the "ok" button in the welcome panel, the javascript code swaps the two panels by changing their respective values for hidden. the follow-up panel looks like this in html: <div id="awesome" class="panel" hidden> <h1>thanks!</h1> <p>thank you <strong>so</strong> much for agreeing to be awesome today! now get out there and do awesome things awesomely to make the world more awesome!</p> </div> css the content is styled using the css below. .pan...
HTMLElement - Web APIs
element. htmlelement.translate is a boolean representing the translation. event handlers most event handler properties, of the form onxyz, are defined on the documentandelementeventhandlers, globaleventhandlers or toucheventhandlers interfaces and implemented by htmlelement. in addition, the following handlers are specific to htmlelement. htmlelement.oncopy returns the event handling code for the copy event (bug 280959). htmlelement.oncut returns the event handling code for the cut event (bug 280959). htmlelement.onpaste returns the event handling code for the paste event (bug 280959). toucheventhandlers.ontouchstart returns the event handling code for the touchstart event. toucheventhandlers.ontouchend returns the event handling code for the touchend event. touch...
...returns the event handling code for the cut event (bug 280959). htmlelement.onpaste returns the event handling code for the paste event (bug 280959). toucheventhandlers.ontouchstart returns the event handling code for the touchstart event. toucheventhandlers.ontouchend returns the event handling code for the touchend event. toucheventhandlers.ontouchmove returns the event handling code for the touchmove event. toucheventhandlers.ontouchenter returns the event handling code for the touchenter event. toucheventhandlers.ontouchleave returns the event handling code for the touchleave event. toucheventhandlers.ontouchcancel returns the event handling code for the touchcancel event. methods inherits methods from its parent, element, and implements those from documentan...
HTMLImageElement.complete - Web APIs
s disabled. it's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running. examples consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. these photos may be very large, so you don't want to wait for them to load, so your code uses async/await to load the images in the background. but imagine that you have other code that needs to only run when the image has completed loading, such as a command that performs red-eye removal on the image in the lightbox. while ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. so the f...
...image in the lightbox. while ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. so the fixredeyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { ...
HTMLImageElement.srcset - Web APIs
hould have a simple border around it. also provided is the word-break attribute, using the break-all value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur. ...
...reak: break-all; } .box img { width: 200px; } javascript the following code is run within a handler for the window's load event. it uses the image's currentsrc property to fetch and display the url selected by the browser from the srcset. let box = document.queryselector(".box"); let image = box.queryselector("img"); let newelem = document.createelement("p"); newelem.innerhtml = `image: <code>${image.currentsrc}</code>`; box.appendchild(newelem); result in the displayed output below, the selected url will correspond with whether your display results in selecting the 1x or the 2x version of the image. if you happen to have both standard and high density displays, try moving this window between them and reloading the page to see the results change. for additional examples, see our...
HTMLImageElement - Web APIs
may be null if cors is not used. htmlimageelement.currentsrc read only returns a usvstring representing the url from which the currently displayed image was loaded. this may change as the image is adjusted due to changing conditions, as directed by any media queries which are in place. htmlimageelement.decoding an optional domstring representing a hint given to the browser on how it should decode the image. if this value is provided, it must be one of the possible permitted values: sync to decode the image synchronously, async to decode it asynchronously, or auto to indicate no preference (which is the default). read the decoding page for details on the implications of this property's values. htmlimageelement.height an integer value that reflects the height html attribute, indicating th...
...ion of the same image. this was once used by browsers under constrained network conditions or on slow devices. htmlimageelement.name a domstring representing the name of the element. htmlimageelement.vspace an integer value specifying the amount of empty space, in pixels, to leave above and below the image. methods inherits properties from its parent, htmlelement. htmlimageelement.decode() returns a promise that resolves when the image is decoded and it's safe to append the image to the dom. this prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the dom. errors if an error occurs while trying to load or render the image, and an onerror event handler has been configured to handle the error event, ...
HTMLInputElement - Web APIs
ng previously stored value off: the user must explicity enter a value max string: returns / sets the element's max attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value. maxlength long: returns / sets the element's maxlength attribute, containing the maximum number of characters (in unicode code points) that the value can have. (if you set this to a negative number, an exception will be thrown.) min string: returns / sets the element's min attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum (max attribute) value. minlength long: returns / sets the element's minlength attribute, containing th...
... (if you set this to a negative number, an exception will be thrown.) min string: returns / sets the element's min attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum (max attribute) value. minlength long: returns / sets the element's minlength attribute, containing the minimum number of characters (in unicode code points) that the value can have. (if you set this to a negative number, an exception will be thrown.) pattern string: returns / sets the element's pattern attribute, containing a regular expression that the control's value is checked against. use the title attribute to describe the pattern to help the user. this attribute applies when the value of the type attribute is text, sear...
HTMLMediaElement - Web APIs
as soon as enough media is available to do so without interruption. note: automatically playing audio when the user doesn't expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions. see the autoplay guide for media and web audio apis for more information. keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working. htmlmediaelement.buffered read only returns a timeranges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed. htmlmediaelement.controller is a mediacontroller object that represents the media controller assigned to the element, or null if none is assigned. htmlmedia...
... interface also inherits methods from its ancestors htmlelement, element, node, and eventtarget. htmlmediaelement.addtexttrack() adds a text track (such as a track for subtitles) to a media element. htmlmediaelement.capturestream() returns mediastream, captures a stream of the media content. htmlmediaelement.canplaytype() given a string specifying a mime media type (potentially with the codecs parameter included), canplaytype() returns the string probably if the media should be playable, maybe if there's not enough information to determine whether the media will play or not, or an empty string if the media cannot be played. htmlmediaelement.fastseek() directly seeks to the given time. htmlmediaelement.load() resets the media to the beginning and selects the best available source ...
The HTML DOM API - Web APIs
with these, we can access the properties and methods that provide information about and grant control over these elements. the htmlinputelement object for the "send" button's disabled property is set to true, which disables the "send" button so it ...
...t control over these elements. the htmlinputelement object for the "send" button's disabled property is set to true, which disables the "send" button so it can't be clicked. in addition, the user name input field is made the active focus by calling the focus() method it inherits from htmlelement. then addeventlistener() is called to add a handler for the input event to the user name input. this code looks at the length of the current value of the input; if it's zero, then the "send" button is disabled if it's not already disabled. otherwise, the code ensures that the button is enabled. with this in place, the "send" button is always enabled whenever the user name input field has a value, and disabled when it's empty. html the html for the form looks like this: <p>please provide the infor...
File drag and drop - Web APIs
rop files on a web page. this document describes how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page. the main steps to drag and drop are to define a drop zone (i.e. a target element for the file drop) and to define event handlers for the drop and dragover events. these steps are described below, including example code snippets. the full source code is available in mdn's drag-and-drop repository (pull requests and/or issues are welcome). note: html drag and drop defines two different apis to support dragging and dropping files. one api is the datatransfer interface and the second api is the datatransferitem and datatransferitemlist interfaces. this example illustrates the use of both apis (and does not use any...
...d drop defines two different apis to support dragging and dropping files. one api is the datatransfer interface and the second api is the datatransferitem and datatransferitemlist interfaces. this example illustrates the use of both apis (and does not use any gecko specific interfaces). define the drop zone the target element of the drop event needs an ondrop global event handler. the following code snippet shows how this is done with a <div> element: <div id="drop_zone" ondrop="drophandler(event);"> <p>drag one or more files to this drop zone ...</p> </div> typically, an application will include a dragover event handler on the drop target element and that handler will turn off the browser's default drag behavior. to add this handler, you need to include a ondragover global event handler...
IDBCursorSync - Web APIs
objects that share the current key. direction readonly unsigned short the direction of traversal of the cursor. see constants for possible values. key readonly any the key for the record at the cursor's position. value any the value for the record at the cursor's position. setting this attribute can raise an idbdatabaseexception with the following codes: data_err if the underlying object store uses in-line keys and the property at the key path does not match the key in this cursor's position. not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode, or if an index record cannot be changed because the underlying index is auto-p...
...the cursor has reached the end of its range; otherwise returns true. bool continue ( in optional any key ); parameters key the key to which to move the cursor's position. remove() deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (databaseexception); exceptions this method can raise an idbdatabaseexception with the following code: not_allowed_err if the underlying index or object store does not support updating the record because it is open in the read_only or snapshot_read mode. ...
IDBKeyRange - Web APIs
the value range a–z. a key range can be a single value or a range with upper and lower bounds or endpoints. if the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. a bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). ...
...e can be a single value or a range with upper and lower bounds or endpoints. if the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded. a bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). ...
IDBRequest.error - Web APIs
Web › API › IDBRequest › error
the error read-only property of the idbrequest interface returns the error in the event of an unsuccessful request. note: this feature is available in web workers. syntax var myerror = request.error; value a domerror containing the relevant error. in chrome 48+/firefox 58+ this property returns a domexception because domerror has been removed from the dom standard. the following error codes are returned under certain conditions: error explanation aborterror if you abort the transaction, then all requests still in progress receive this error. constrainterror if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. you get this error, for example, if you try to add a new key that already exis...
...u run out of disk quota and the user declined to grant you more space. unknownerror if the operation failed for reasons unrelated to the database itself. a failure due to disk io errors is such an example. noerror if the request succeeds. versionerror if you try to open a database with a version lower than the one it already has. in addition to the error codes sent to the idbrequest object, asynchronous operations can also raise exceptions. the list describes problems that could occur when the request is being executed, but you might also encounter other problems when the request is being made. for example, if the the request failed and the result is not available, the invalidstateerror exception is thrown. example the following example requests a g...
IDBTransaction - Web APIs
transaction failures transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback: abort due to bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint. this causes an er...
...ransactions that were started using the setversion() method of idbdatabase objects. transactions of this mode cannot run concurrently with other transactions. transactions in this mode are known as "upgrade transactions." even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in chrome the change was made in version 21). you should code defensively in case the object is not available anymore: var myidbtransaction = window.idbtransaction || window.webkitidbtransaction || { read_write: "readwrite" }; examples in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transacti...
Basic concepts - Web APIs
there are sanity measures baked in. it's not that different from the way that xmlhttprequest works. indexeddb uses a lot of requests. requests are objects that receive the success or failure dom events that were mentioned previously. they have onsuccess and onerror properties, and you can call addeventlistener() and removeeventlistener() on them. they also have readystate, result, and errorcode properties that tell you the status of the request. the result property is particularly magical, as it can be many different things, depending on how the request was generated (for example, an idbcursor instance, or the key for a value that you just inserted into the database). indexeddb uses dom events to notify you when results are available. dom events always have a type property (in ind...
...while the database can't store data in a specific internationalized order, you can sort the data that you've read out of the database yourself. note, however, that locale-aware sorting has been allowed with an experimental flag enabled (currently for firefox only) since firefox 43. synchronizing. the api is not designed to take care of synchronizing with a server-side database. you have to write code that synchronizes a client-side indexeddb database with a server-side database. full text searching. the api does not have an equivalent of the like operator in sql. in addition, be aware that browsers can wipe out the database, such as in the following conditions: the user requests a wipe out. many browsers have settings that let users wipe all data stored for a given website, including c...
Checking when a deadline is due - Web APIs
xample application we will be referring to in this article is to-do list notifications, a simple to-do list application that stores task titles and deadline times and dates via indexeddb, and then provides users with notifications when deadline dates are reached, via the notification, and vibration apis. you can download the to-do list notifications app from github and play around with the source code, or view the app running live. the basic problem in the to-do app, we wanted to first record time and date information in a format that is both machine readable and human understandable when displayed, and then check whether each time and date is occurring at the current moment. basically, we want to check what the time and date is right now, and then check each stored event to see if any of th...
...ng zero equivalents, e.g. 09 -> 9. this is needed because javascript date number values never have leading zeros, but our data might. the notified == "no" check is designed to make sure you will only get one notification per to-do item. ...
Keyboard - Web APIs
Web › API › Keyboard
properties none. methods keyboard.getlayoutmap() returns a promise that resolves with an instance of keyboardlayoutmap which is a map-like object with functions for retrieving the strings associated with specific physical keys. ...
... properties none. methods keyboard.getlayoutmap() returns a promise that resolves with an instance of keyboardlayoutmap which is a map-like object with functions for retrieving the strings associated with specific physical keys. ...
KeyboardEvent() - Web APIs
the keyboardevent() constructor creates a new keyboardevent. syntax event = new keyboardevent(typearg, keyboardeventinit); values typearg is a domstring representing the name of the event. keyboardeventinitoptional is a keyboardeventinit dictionary, having the following fields: "key", optional and defaulting to "", of type domstring, that sets the value of keyboardevent.key. "code", optional and defaulting to "", of type domstring, that sets the value of keyboardevent.code. "location", optional and defaulting to 0, of type unsigned long, that sets the value of keyboardevent.location. "ctrlkey", optional and defaulting to false, of type boolean, that sets the value of keyboardevent.ctrlkey. "shiftkey", optional and defaulting to false, of type boolean, that sets the v...
...pe boolean, that sets the value of keyboardevent.altkey. "metakey", optional and defaulting to false, of type boolean, that sets the value of keyboardevent.metakey. "repeat", optional and defaulting to false, of type boolean, that sets the value of keyboardevent.repeat. "iscomposing", optional and defaulting to false, of type boolean, that sets the value of keyboardevent.iscomposing. "charcode", optional and defaulting to 0, of type unsigned long, that sets the value of the deprecated keyboardevent.charcode. "keycode", optional and defaulting to 0, of type unsigned long, that sets the value of the deprecated keyboardevent.keycode. "which", optional and defaulting to 0, of type unsigned long, that sets the value of the deprecated keyboardevent.which. the keyboardeventinit dict...
LocalFileSystemSync - Web APIs
requestfilesystemsync( in unsigned short type, in unsigned long long size ); parameters type the storage type of the file system. the values can be either temporary or persistent. size the storage space—in bytes—that you need for your app. returns filesystemsync an object that represents the file system. exceptions this method can raise an fileexception with the following code: exception description security_error the application does not have permission to access the file system interface. for example, you cannot run from file://. for more details, see the article on basic concepts. resolvelocalfilesystemsyncurl() allows the user to look up the entry for a file or directory referred to by a local url. void resolvelocalfilesystemurl( ...
...ts. resolvelocalfilesystemsyncurl() allows the user to look up the entry for a file or directory referred to by a local url. void resolvelocalfilesystemurl( in domstring url ); parameter url the url of a local file in the file system. returns entrysync an object that represents entries in the file system. exceptions this method can raise a fileexception with the following codes: exception description encoding_err the syntax of the url was invalid. not_found_err the url was structurally correct, but refers to a resource that does not exist. security_err the application does not have permission to access the file system interface. browser compatibility the compatibility table on this page is generated from stru...
MediaCapabilities.decodingInfo() - Web APIs
ration: either an audioconfiguration or a videoconfiguration. return value a promise fulfilling with a mediacapabilitiesinfo interface containing three boolean attributes: supported smooth powerefficient exceptions a typeerror is raised if the mediaconfiguration passed to the decodinginfo() method is invalid, either because the type is not video or audio, the contenttype is not a valid codec mime type, the media decoding configuration is not a valid value for the media decoding type, or any other error in the media configuration passed to the method, including omitting values required in the media decoding configuration. example //create media configuration to be tested const mediaconfig = { type : 'file', // or 'media-source' audio : { contenttype : "au...
...to the method, including omitting values required in the media decoding configuration. example //create media configuration to be tested const mediaconfig = { type : 'file', // or 'media-source' audio : { contenttype : "audio/ogg", // valid content type channels : 2, // audio channels used by the track bitrate : 132700, // number of bits used to encode 1s of audio samplerate : 5200 // number of audio samples making up that 1s. }, }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ? '' : 'not ') + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : ...
MediaCapabilities.encodingInfo() - Web APIs
ither an audioconfiguration or videoconfiguration dictionary. ...
...because the type is not video or audio, the contenttype is not a valid codec mime type, or any other error in the media configuration passed to the method, including omitting any of the media encoding configuration elements. example //create media configuration to be tested const mediaconfig = { type : 'record', // or 'transmission' video : { contenttype : "video/webm;codecs=vp8.0", // valid content type width : 1920, // width of the video height : 1080, // height of the video bitrate : 120000, // number of bits used to encode 1s of video framerate : 48 // number of frames making up that 1s. } }; // check support and performance navigator.mediacapabilities.encodinginfo(mediaconfig).then(result => { console.log('thi...
MediaDevices.getDisplayMedia() - Web APIs
urcoes are supported. check the compatibility table for details for each browser. exceptions rejections of the returned promise are made by passing a domexception error object to the promise's failure handler. possible errors are: aborterror an error or failure that doesn't match any of the other exceptions below occurred. invalidstateerror the call to getdisplaymedia() was not made from code running due to a user action, such as an event handler. another potential cause for this event: the document in whose context getdisplaymedia() was called is not fully active; for example, perhaps it is not the frontmost tab. notallowederror permission to access a screen area was denied by the user, or the current browsing instance is not permitted access to screen sharing. notfounderror no s...
...media(). the specified constraints can't be used to limit the options available to the user. instead, they must be applied after the user chooses a source, in order to generate output that matches the constraints. the go-ahead permission to use getdisplaymedia() cannot be persisted for reuse. the user must be prompted for permission every time. the call to getdisplaymedia() must be made from code which is running in response to a user action, such as in an event handler. browsers are encouraged to provide a warning to users about sharing displays or windows that contain browsers, and to keep a close eye on what other content might be getting captured and shown to other users. example in the example below, a startcapture() method is created which initiates screen capture given a set of...
MediaDevices.getSupportedConstraints() - Web APIs
candidate recommendation initial definition. ...
... candidate recommendation initial definition. ...
MediaRecorder: dataavailable event - Web APIs
umentation for the event handler property: ondataavailable. examples using addeventlistener to listen for dataavailable events: ... var chunks = []; mediarecorder.addeventlistener('stop', (event) => { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); }); mediarecorder.addeventlistener('dataavailable', (event) => { chunks.push(event.data); }); ... the same, but using the ondataavailable event handler property: ... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder...
...eventlistener('dataavailable', (event) => { chunks.push(event.data); }); ... the same, but using the ondataavailable event handler property: ... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ... specifications specification status mediastream recording working draft ...
MediaRecorder.ondataavailable - Web APIs
the dataavailable event is fired when the mediarecorder delivers media data to your application for its use. the data is provided in a blob object that contains the data. this occurs in four situations: when the media stream ends, any media data not already delivered to your ondataavailable handler is passed in a single blob. ...
...recorder.ondataavailable = function(event) { ... } mediarecorder.addeventlistener('dataavailable', function(event) { ... }) example ... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ... specifications specification status comment mediastream recordingthe definition of 'mediarecorder.ondataavailable' in that specification. working draft ...
MediaRecorder.onstop - Web APIs
the stop event is thrown either as a result of the mediarecorder.stop() method being invoked, or when the media stream being captured ends. in each case, the stop event is preceded by a dataavailable event, making the blob captured up to that point available for you to use in your application. syntax mediarecorder.onstop = function(event) { ... } mediarecorder.addeventlistener('stop', function(event) { ... }) example ... ...
...se in your application. syntax mediarecorder.onstop = function(event) { ... } mediarecorder.addeventlistener('stop', function(event) { ... }) example ... mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ... specifications specification status comment mediastream recordingthe definition of 'mediarecorder.onstop' in that specification. working draft initial d...
MediaSource.readyState - Web APIs
attached to a media element but the stream has been ended via a call to mediasource.endofstream(). syntax var myreadystate = mediasource.readystate; value a domstring. ...
...ers (view the full demo live, or download the source for further investigation.) if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); source...
MediaStream Image Capture API - Web APIs
rieve information about device capabilities such as image size, red-eye reduction and whether or not there is a flash and what they are currently set to. conversely, the api allows the capabilities to be configured within the constraints what the device allows. mediastream image capture concepts and usage the process of retrieving an image or video stream happens as described below. the example code is adapted from chrome's image capture examples. first, get a reference to a device by calling mediadevices.getusermedia(). the example below simply says give me whatever video device is available, though the getusermedia() method allows more specific capabilities to be requested. this method returns a promise that resolves with a mediastream object. navigator.mediadevices.getusermedia({ video:...
...allows more specific capabilities to be requested. this method returns a promise that resolves with a mediastream object. navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream. }) next, isolate the visual part of the media stream. do this by calling mediastream.getvideotracks(). this returns an array of mediastreamtrack objects. the code below assumes that the first item in the mediastreamtrack array is the one to use. you can use the properties of the mediastreamtrack objects to select the one you need. const track = mediastream.getvideotracks()[0]; at this point, you might want to configure the device capabilities before capturing an image. you can do this by calling applyconstraints() on the track object before doing anythin...
MediaTrackConstraints.cursor - Web APIs
edia has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's cursor object. ...
...bject's cursor object. for example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertfakecursorflag = false; if (displaystream.getvideotracks()[0].getsettings().cursor === "never") { insertfakecursorflag = true; } following this code, insertfakecursorflag is true if there's no cursor rendered into the stream already. later code can detect this flag's value and if it's true, can manually look at some metadata that might be provided and insert a fake representation of the cursor at the correct position. examples here are some example constraints objects for getdisplaymedia() that make use of the cursor property. in addition, ...
MediaTrackConstraints.displaySurface - Web APIs
r agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's displaysurface object. ...
...eds to know that the surface being shared is a monitor or application—meaning that there's possibly a non-content backdrop—it can use code similar to this: let mayhavebackdropflag = false; let displaysurface = displaystream.getvideotracks()[0].getsettings().displaysurface; if (displaysurface === "monitor" || displaysurface ==="application") { mayhavebackdropflag = true; } following this code, mayhavebackdrop is true if the display surface contained in the stream is of type monitor or application; either of these may have non-content backdrop areas. later code can use this flag to determine whether or not to perform special processing, such as to remove or replace the backdrop, or to "cut" the individual display areas out of the received frames of video. examples here are some exam...
MerchantValidationEvent.complete() - Web APIs
validationdata or merchantsessionpromise an object containing the data needed to complete the merchant validation process, or a promise which resolves to the validation data. return value undefined. exceptions this exception may be passed into the rejection handler for the promise: invalidstateerror the event did not come directly from the user agent, but was instead dispatched by other code. ...
...e passed into the rejection handler for the promise: invalidstateerror the event did not come directly from the user agent, but was instead dispatched by other code. another payment request is currently being processed, the current payment request is not currently being displayed to the user, or payment information is currently being updated. example in this example, we see the client-side code needed to support merchant validation for a payment request called payrequest: payrequest.onmerchantvalidation = event => { const validationdatapromise = getvalidationdata(event.validationurl); event.complete(validationdatapromise); } function getvalidationdata(url) { /* ...retrieve the validation data from the url... */ } this code sets up a handler for the merchantvalidation event. th...
MessagePort: message event - Web APIs
the message event is fired on a messageport object when a message arrives on that channel. ...
...this is only needed when using the addeventlistener() method: if the ...
MessagePort: messageerror event - Web APIs
the messageerror event is fired on a messageport object when it receives a message that can't be deserialized. ...
... const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages and message errors on it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.addeventlistener('messageerror', (event) => { console.error(event.data); }); myport.start(); }); note that the listener must call messageport.start() before any messages ...
MouseEvent.altKey - Web APIs
Web › API › MouseEvent › altKey
to move or resize windows. note: on macintosh keyboards, this key is also known as the option key. syntax var altkeypressed = instanceofmouseevent.altkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the altkey property when you trigger a click event. ...
...esize windows. note: on macintosh keyboards, this key is also known as the option key. syntax var altkeypressed = instanceofmouseevent.altkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the altkey property when you trigger a click event. ...
MouseEvent.ctrlKey - Web APIs
not when a given mouse event occurs. note: on macintosh keyboards, this key is the control key. syntax var ctrlkeypressed = instanceofmouseevent.ctrlkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the ctrlkey property when you trigger a click event. ...
...ven mouse event occurs. note: on macintosh keyboards, this key is the control key. syntax var ctrlkeypressed = instanceofmouseevent.ctrlkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the ctrlkey property when you trigger a click event. ...
MouseEvent.metaKey - Web APIs
oards, this key is the command key (⌘). on windows keyboards, this key is the windows key (⊞). syntax var metakeypressed = instanceofmouseevent.metakey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the metakey property when you trigger a click event. ...
...y is the command key (⌘). on windows keyboards, this key is the windows key (⊞). syntax var metakeypressed = instanceofmouseevent.metakey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the metakey property when you trigger a click event. ...
MouseEvent.shiftKey - Web APIs
boolean that indicates whether the shift key was pressed or not when a given mouse event occurs. syntax var shiftkeypressed = instanceofmouseevent.shiftkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the shiftkey property when you trigger a click event. ...
...dicates whether the shift key was pressed or not when a given mouse event occurs. syntax var shiftkeypressed = instanceofmouseevent.shiftkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the shiftkey property when you trigger a click event. ...
Navigation Timing API - Web APIs
iming api can be used to gather performance data on the client side to be sent to a server via xhr as well as measure data that was very difficult to measure by other means such as time to unload a previous page, domain look up time, window.onload total time, etc. examples calculate the total page load time to compute the total amount of time it took to load the page, you can use the following code: const perfdata = window.performance.timing; const pageloadtime = perfdata.loadeventend - perfdata.navigationstart; this subtracts the time at which navigation began (navigationstart) from the time at which the load event handler returns (loadeventend). this gives you the perceived page load time. calculate request response time you can calculate the time elapsed between the beginning of a r...
...eloadtime = perfdata.loadeventend - perfdata.navigationstart; this subtracts the time at which navigation began (navigationstart) from the time at which the load event handler returns (loadeventend). this gives you the perceived page load time. calculate request response time you can calculate the time elapsed between the beginning of a request and the completion of getting the response using code like this: const connecttime = perfdata.responseend - perfdata.requeststart; here, the time at which the request was initiated (requeststart). from the time at which the response was finished being received (responseend). calculate page render time as another example of an interesting piece of data you can obtain using the navigation timing api that you can't otherwise easily get, you can get...
Navigator.clipboard - Web APIs
e of the asynchronous clipboard read and write methods requires that the user grant the web site or app permission to access the clipboard. this permission must be obtained from the permissions api using the "clipboard-read" and/or "clipboard-write" permissions. syntax theclipboard = navigator.clipboard; value the clipboard object used to access the system clipboard. ...
... if the clipboard is empty or doesn't contain text, the "cliptext" element's contents are cleared. ...
Navigator.sendBeacon() - Web APIs
handler. most user agents will delay the unload to load the image. creating a no-op loop for several seconds in the unload handler. all of these methods block unloading the document, which slows down the next navigation. there is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault. the following example shows theoretical analytics code that attempts to submit data to a server with a synchronous xmlhttprequest in an unload handler. this results in the next page load to be delayed. window.addeventlistener("unload", function logdata() { var xhr = new xmlhttprequest(); xhr.open("post", "/log", false); // third parameter of `false` means synchronous xhr.send(analyticsdata); }); this is what sendbeacon() replaces. with the s...
...a); }); this is what sendbeacon() replaces. with the sendbeacon() method, the data is transmitted asynchronously when the user agent has an opportunity to do so, without delaying unload or the next navigation. this solves all of the problems with submission of analytics data: the data is sent reliably it's sent asynchronously it doesn't impact the loading of the next page in addition, the code is simpler to write than any of the older techniques! the following example shows a theoretical analytics code pattern that submits data to a server using the sendbeacon() method. window.addeventlistener("unload", function logdata() { navigator.sendbeacon("/log", analyticsdata); }); the beacon sends an http request via the post method, with all relevant cookies available when called. spec...
Navigator - Web APIs
Web › API › Navigator
carry on some activities. a navigator object can be retrieved using the read-only window.navigator property. properties doesn't inherit any properties, but implements those defined in navigatorid, navigatorlanguage, navigatoronline, navigatorcontentutils, navigatorstorage, navigatorstorageutils, navigatorconcurrenthardware, navigatorplugins, and navigatorusermedia. standard navigatorid.appcodename read only returns the internal "code" name of the current browser. do not rely on this property to return the correct value. navigatorid.appname read only returns a domstring with the official name of the browser. do not rely on this property to return the correct value. navigatorid.appversion read only returns the version of the browser as a domstring. do not rely on this property...
... the native sharing mechanism of the current platform. navigatorid.taintenabled() deprecated since gecko 1.7.8 obsolete since gecko 9.0 returns false. javascript taint/untaint functions removed in javascript 1.2. navigator.vibrate() causes vibration on devices with support for it. does nothing if vibration support isn't available. non-standard navigator.mozislocallyavailable() lets code check to see if the document at a given uri is available without using the network. specifications specification status comment html living standardthe definition of 'the navigator object' in that specification. living standard ...
NavigatorID.userAgent - Web APIs
ser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable. for example: in firefox, you can change the preference general.useragent.override in about:config. some firefox extensions do that; however, this only changes the http header that gets sent, and doesn't affect browser detection performed by javascript code. opera 6+ allows users to set the browser identification string via a menu. microsoft internet explorer uses the windows registry. safari and icab allow users to change the browser user agent string to predefined internet explorer or netscape strings via a menu. syntax var ua = navigator.useragent; value a domstring specifying the complete user agent string the browser provides both in h...
...r provides both in http headers and in response to this and other related methods on the navigator object. the user agent string is built on a formal structure which can be decomposed into several pieces of info. each of these pieces of info comes from other navigator properties which are also settable by the user. ...
NavigatorID - Web APIs
this property is kept only for compatibility purposes. navigatorid.appname read only always returns "netscape", in any browser. ...
... any methods. navigatorid.taintenabled() always returns false. javascript taint/untaint functions were removed in javascript 1.2. this method is only kept for compatibility purposes. not available in workers. specifications specification status comment html living standardthe definition of 'navigatorid' in that specification. living standard added the appcodename property and the taintenabled() method, for compatibility purpose. html5the definition of 'navigatorid' in that specification. recommendation initial specification. ...
Node.removeChild() - Web APIs
Web › API › Node › removeChild
r oldchild = node.removechild(child); or node.removechild(child); child is the child node to be removed from the dom. node is the parent node of child. oldchild holds a reference to the removed child node, i.e., oldchild === child. the removed child node still exists in memory, but is no longer part of the dom. with the first syntax form shown, you may reuse the removed node later in your code, via the oldchild object reference. in the second syntax form, however, there is no oldchild reference kept, so assuming your code has not kept any other reference to the node elsewhere, it will immediately become unusable and irretrievable, and will usually be automatically deleted from memory after a short time. if child is actually not a child of the element node, the method throws an except...
...ld(d_nested); to remove a specified element without having to specify its parent node: let node = document.getelementbyid("nested"); if (node.parentnode) { node.parentnode.removechild(node); } to remove all children from an element: let element = document.getelementbyid("top"); while (element.firstchild) { element.removechild(element.firstchild); } causing a typeerror <!--sample html code--> <div id="top"> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nested"); // throws uncaught typeerror let garbage = top.removechild(nested); </script> causing a notfounderror <!--sample html code--> <div id="top"> <div id="nested"></div> </div> <script type="text/javascript"> let top = document.getelementb...
NodeList - Web APIs
Web › API › NodeList
ngth. properties nodelist.length the number of nodes in the nodelist. methods nodelist.item() returns an item in the list by its index, or null if the index is out-of-bounds. an alternative to accessing nodelist[i] (which instead returns undefined when i is out-of-bounds). this is mostly useful for non-javascript dom implementations. ...
...ipt dom implementations. nodelist.entries() returns an iterator, allowing code to go through all key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0 and the values are nodes.) nodelist.foreach() executes a provided function once per nodelist element, passing the element as an argument to the function. nodelist.keys() returns an iterator, allowing code to go through all the keys of the key/value pairs contained in the collection. (in this case, the keys are numbers starting from 0.) nodelist.values() returns an iterator allowing code to go through all values (nodes) of the key/value pairs contained in the collection. example it's possible to loop over the items in a nodelist using a for loop: for (let i = 0; i < mynodelist.length; i++) { ...
Notification.Notification() - Web APIs
he direction in which to display the notification. it defaults to auto, which just adopts the browser's language setting behavior, but you can override that behaviour by setting values of ltr and rtl (although most browsers seem to ignore these settings.) lang: the notification's language, as specified using a domstring representing a bcp 47 language tag. see the sitepoint iso 2 letter language codes page for a simple reference. badge: a usvstring containing the url of the image used to represent the notification when there isn't enough space to display the notification itself. body: a domstring representing the body text of the notification, which is displayed below the title. tag: a domstring representing an identifying tag for the notification. icon: a usvstring containing the url...
... the context of the notification itself. the action's name is sent to the service worker notification handler to let it know the action was selected by the user. silent: a boolean specifying whether the notification is silent (no sounds or vibrations issued), regardless of the device settings. the default is false, which means it won't be silent. example in our emogotchi demo (see source code), we run a spawnnotification() function when we want to trigger a notification. the function is passed parameters to specify the body, icon, and title we want, and then it creates the necessary options object and triggers the notification by using the notification() constructor. function spawnnotification(thebody,theicon,thetitle) { var options = { body: thebody, icon: theicon } ...
Notification.requestPermission() - Web APIs
the requestpermission() method of the notification interface requests permission from the user for the current origin to display notifications. ...
...ue. deprecated in favor of the promise return value. returns a promise that resolves to a domstring with the permission picked by the user. possible values for this string are: granted denied default examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support de...
Notification - Web APIs
the notification itself. notification.body read only the body string of the notification as specified in the constructor's options parameter. notification.data read only returns a structured clone of the notification’s data. notification.dir read only the text direction of the notification as specified in the constructor's options parameter. notification.lang read only the language code of the notification as specified in the constructor's options parameter. notification.tag read only the id of the notification (if any) as specified in the constructor's options parameter. notification.icon read only the url of the image used as an icon of the notification as specified in the constructor's options parameter. notification.image read only the url of an image to be displaye...
...n instance of the notification object or through its prototype. the notification object also inherits from the eventtarget interface. notification.close() programmatically closes a notification instance. examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support de...
Using the Notifications API - Web APIs
when a new message is received, even if the user is doing something else with another application. many examples of this now exist, such as slack. we've written a real world example — a to-do list app — to give more of an idea of how web notifications can be used. it stores data locally using indexeddb and notifies users when tasks are due using system notifications. download the to-do list code, or view the app running live. requesting permission before an app can send a notification, the user must grant the application the right to do so. this is a common requirement when an api tries to interact with something outside a web page — at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/si...
... main block first, you'll see that we first check to see if notifications are supported. if they are, we then run a check to see whether the promise-based version of notification.requestpermission() is supported. if it is, we run the promise-based version (supported everywhere except safari), and if not, we run the older callback-based version (which is supported in safari). to avoid duplicating code, we have stored a few bits of housekeeping code inside the handlepermission() function, which is the first main block inside this snippet. inside here we explicitly set the notification.permission value (some old versions of chrome failed to do this automatically), and show or hide the button depending on what the user chose in the permission dialog. we don't want to show it if permission has alr...
OES_standard_derivatives - Web APIs
t and it requires glsl #version 300 es. constants this extension exposes one new constant, which can be used in the hint() and getparameter() methods. ext.fragment_shader_derivative_hint_oes a glenum indicating the accuracy of the derivative calculation for the glsl built-in functions: dfdx, dfdy, and fwidth. ...
...erivative calculation for the glsl built-in functions: dfdx, dfdy, and fwidth. ...
OffscreenCanvas - Web APIs
romimagebitmap() with the previously rendered and saved imagebitmap from the offscreencanvas, will display the imagebitmap on the canvas and transfer its ownership to the canvas. a single offscreencanvas may transfer frames into an arbitrary number of other imagebitmaprenderingcontext objects. given these two <canvas> elements <canvas id="one"></canvas> <canvas id="two"></canvas> the following code will provide the rendering using an offscreencanvas as described above. var one = document.getelementbyid("one").getcontext("bitmaprenderer"); var two = document.getelementbyid("two").getcontext("bitmaprenderer"); var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); // ... some drawing for the first canvas using the gl context ... // commit rendering to the f...
...isplay of frames produced by an offscreencanvas another way to use the offscreencanvas api, is to call transfercontroltooffscreen() on a <canvas> element, either on a worker or the main thread, which will return an offscreencanvas object from an htmlcanvaselement object from the main thread. calling getcontext() will then obtain a renderingcontext from that offscreencanvas. main.js (main thread code): var htmlcanvas = document.getelementbyid("canvas"); var offscreen = htmlcanvas.transfercontroltooffscreen(); var worker = new worker("offscreencanvas.js"); worker.postmessage({canvas: offscreen}, [offscreen]); offscreencanvas.js (worker code): onmessage = function(evt) { var canvas = evt.data.canvas; var gl = canvas.getcontext("webgl"); // ... some drawing using the gl context ... }...
PannerNode.orientationY - Web APIs
d cartesian coordinate space. the complete vector is defined by the position of the audio source, given as (positionx, positiony, positionz), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationx, orientationy, orientationz). depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. s...
...e') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
PannerNode.orientationZ - Web APIs
d cartesian coordinate space. the complete vector is defined by the position of the audio source, given as (positionx, positiony, positionz), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationx, orientationy, orientationz). depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. s...
...e') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
PaymentCurrencyAmount.currency - Web APIs
this is the currency in which the payment's value is given. all currency values must include the currency system in this property. example this example represents the price of $42.95 in us dollars. ...
...this is the currency in which the payment's value is given. all currency values must include the currency system in this property. example this example represents the price of $42.95 in us dollars. ...
PaymentRequest: merchantvalidation event - Web APIs
lidation url, obtained from the event's validationurl property. the merchant server should access the validation url in accordance with the payment method documention. typically, a client should not access the validation url. request.addeventlistener("merchantvalidation", event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }, false); }; const response = await request.show(); how merchant server handles the validation depends on the server implementation and payment method documentation. the content delivered by the validation server is forwarded to t...
...ll's fulfillment handler to the complete() method on the event. this response lets the payment handler know if the merchant is validated. you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. related events payerdetailchange, paymentmethodchange, shippingaddresschange, and shippingoptionchange ...
PaymentRequest: paymentmethodchange event - Web APIs
a given payment handler. for example, if the user switches from one credit card to another on their apple pay account, a paymentmethodchange event is fired to let you know about the change. bubbles no cancelable no interface paymentmethodchangeevent event handler property onpaymentmethodchange examples let's take a look at an example. ...
... bubbles no cancelable no interface paymentmethodchangeevent event handler property onpaymentmethodchange examples let's take a look at an example. this code creates a new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user. the code assumes the existence of a method detailsforshipping(), which returns a paymentdetailsupdate object containing the shipping options for the ground shipping method, in the form found in the paymentshippingoption dictionary. by doing so, the payment form defaults to the ground shipping method. const options = { requestshipping: true }; const paymentrequest = new paymentrequest(paymentmethods, ...
Using Pointer Events - Web APIs
w to use pointer events and the html <canvas> element to build a multi-touch enabled drawing application. this example is based on the one in the touch events overview, except it uses the pointer events input event model. another difference is that because pointer events are pointer device agnostic, the application accepts coordinate-based inputs from a mouse, a pen, or a fingertip using the same code. this application will only work on a browser that supports pointer events. a live version of this application is available on github. the source code is available on github and pull requests and bug reports are welcome. definitions surface a touch-sensitive surface. this may be a trackpad, a touch screen, or even a virtual mapping of a user's desk surface (or mousepad) with the physical s...
... " + evt.pointerid); 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(tou...
PromiseRejectionEvent.promise - Web APIs
ly property indicates the javascript promise which was rejected. you can examine the event's promiserejectionevent.reason property to learn why the promise was rejected. syntax promise = promiserejectionevent.promise value the javascript promise which was rejected, and whose rejection went unhandled. ...
...ent unhandled. examples this example listens for unhandled promises and, if the reason is an object with a code field containing the text "module not ready", it sets up an idle callback that will retry the task that failed to execute correctly. event.preventdefault() is called to indicate that the promise has now been handled. window.onunhandledrejection = function(event) { if (event.reason.code && event.reason.code == "module not ready") { window.requestidlecallback(function(deadline) { loadmodule(event.reason.modulename) .then(performstartup); }); event.preventdefault(); } } specifications specification status comment html living standardthe definition of 'promiserejectionevent.promise' in that specification. living standard ...
RTCDTMFSender - Web APIs
the rtcdtmfsender interface provides a mechanism for transmitting dtmf codes on a webrtc rtcpeerconnection. you gain access to the connection's rtcdtmfsender through the rtcrtpsender.dtmf property on the audio track you wish to send dtmf with. the primary purpose for webrtc's dtmf support is to allow webrtc-based communication clients to be connected to a public-switched telephone network (pstn) or other legacy telephone service, including extant voice over ip (voip) services. for that reason, dtmf can't be used between two webrtc-based devices, because there is no mechanism provided by webrtc for receiving dtmf codes. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"...
... #0095dd; pointer-events: all;} properties rtcdtmfsender.tonebuffer read only a domstring which contains the list of dtmf tones currently in the queue to be transmitted (tones which have already been played are no longer included in the string). see tonebuffer for details on the format of the tone buffer. methods rtcdtmfsender.insertdtmf() given a string describing a set of dtmf codes and, optionally, the duration of and inter-tone gap between the tones, insertdtmf() starts sending the specified tones. calling insertdtmf() replaces any already-pending tones from the tonebuffer. you can abort sending queued tones by specifying an empty string ("") as the set of tones to play. events listen to these events using addeventlistener() or by assigning an event listener to the one...
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
the rtcdatachannel property bufferedamountlowthreshold is used to specify the number of bytes of buffered outgoing data that is considered "low." the default value is 0. when the number of buffered outgoing bytes, as indicated by the bufferedamount property, falls to or below this value, a bufferedamountlow event is fired. this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. listeners may be added with onbufferedamountlow or addeventlistener(). the user agent may implement the process of actually sending data in any way it chooses; this may be done periodically during the event loop or truly asynchronously. as messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired ...
...onously. as messages are actually sent, this value is reduced accordingly. bufferedamountlow events are not fired after the data channel is closed. syntax var threshold = adatachannel.bufferedamountlowthreshold; adatachannel.bufferedamountlowthreshold = threshold; value the number of queued outgoing data bytes below which the buffer is considered to be "low." example in this snippet of code, bufferedamountlowthreshold is set to 64kb, and a handler for the bufferedamountlow event is established by setting the rtcdatachannel.onbufferedamountlow property to a function which should send more data into the buffer by calling send(). var dc = peerconnection.createdatachannel("file transfer"); dc.bufferedamountlowthreshold = 65535; dc.onbufferedamountlow = function() { /* use send() to ...
RTCDataChannel.id - Web APIs
Web › API › RTCDataChannel › id
time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is true). each rtcpeerconnection can therefore have up to a theoretical maximum of 65,534 data channels on it, although the actual maximum may vary from browser to browser. in early versions of the webrtc specification, this property's name was stream. code that uses that property needs to be updated. syntax var id = adatachannel.id; value an unsigned short value (that is, an integer between 0 and 65,535) which uniquely identifies the data channel. while the label property doesn't have to be unique, this id number is guaranteed to be unique among all data channels. additionally, known implementations of webrtc use the same id on both peers. a...
... updated. syntax var id = adatachannel.id; value an unsigned short value (that is, an integer between 0 and 65,535) which uniquely identifies the data channel. while the label property doesn't have to be unique, this id number is guaranteed to be unique among all data channels. additionally, known implementations of webrtc use the same id on both peers. a unique id makes it easier for your code to do its own out-of-band data channel-related signaling. this can be also useful for logging and debugging purposes. example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); console.log("channel id: " + dc.id); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatac...
RTCDtlsTransport - Web APIs
and one for video communications. because transports are established early in the negotiation process, it's likely that it won't be known until after they're created whether or not the remote peer supports bundling or not. for this reason, you'll sometimes see separate transports created at first, one for each track, then see them get bundled up once it's known that bundling is possible. if your code accesses rtcrtpsenders and/or rtcrtpreceivers directly, you may encounter situations where they're initially separate, then half or more of them get closed and the senders and receivers updated to refer to the appropriate remaining rtcdtlstransport objects. data channels rtcdatachannels use sctp to communicate. all of a peer connection's data channels share a single rtcsctptransport, found in ...
... specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport' in that specification. candidate recommendation initial definition. ...
RTCIceCandidate.candidate - Web APIs
043278322 192.168.0.56 44323 typ host". the user agent always prefers candidates with the highest priority, all else being equal. in the example above, the priority is 2043278322. the attributes are all separated by a single space character, and are in a specific order. the complete list of attributes for this example candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" example in this example, we see a function which receives as input an sdp string containing an ice candidate received from the remote peer during the signaling process. function handlenewicecandidate(candidatesdp) { var candidateobj = new rtcicecandidate(candidatesdp...
...es the received candidate's sdp text into rtcicecandidate() to receive an rtcicecanddiate object in return, which represents the candidate. the new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connection being established. this example could be simplified somewhat; you may more often see the code look something like this, taking advantage of more advanced ecmascript 2016 features: let handlenewicecandidate = candidatesdp => mypeerconnection.addicecandidate(new rtcicecandidate(candidatesdp)); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.candidate' in that specification. can...
RTCIceCandidatePairStats - Web APIs
y dividing this value by responsesreceived. transportid optional a domstring that uniquely identifies the rtcicetransport that was inspected to obtain the transport-related statistics (as found in rtctransportstats) used in generating this object. obsolete properties the following properties have been removed from the specification and should no longer be used. you should update any existing code to avoid using them as soon as is practical. check the compatibility table for details on which browsers support them and in which versions. priority optional an integer value indicating the candidate pair's priority. readable optional a boolean value indicating whether or not data can be sent over the connection described by the candidate pair. writable optional a boolean value ind...
...le computes the average time elapsed between connectivity checks if the rtcstats object rtcstats is an rtcicecandidatepairstats object. if (rtcstats && rtcstats.type === "candidate-pair") { let elapsed = (rtcstats.lastrequesttimestamp - rtcstats.firstrequesttimestamp) / rtcstats.requestssent; log("average time between ice connectivity checks: " + elapsed + " ms."); } the code begins by looking at rtcstats to see if its type is candidate-pair. if it is, then we know that rtcstats is in fact an rtcicecandidatepairstats object. if so, we compute the average time elapsed between stun connectivity checks and log that information. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandida...
RTCIceTransport: statechange event - Web APIs
e can be used to determine how far through the process of examining, verifying, and selecting a valid candidate pair is prior to successfully connecting the two peers for webrtc communications. ...
...tatechange examples given an rtcpeerconnection, pc, the following code creates an event handler that calls a function named handlefailure() if the ice transport enters a failure state. ...
RTCInboundRtpStreamStats.sliCount - Web APIs
the slicount property of the rtcinboundrtpstreamstats dictionary indicates how many slice loss indication (sli) packets the rtcrtpreceiver for which this object provdes statistics sent to the remote rtcrtpsender. an sli packet is used by a decoder to let the encoder know that it's detected corruption of one or more consecutive macroblocks (in scan order) in the received media. in general, what's usually of interest is that the higher this number is, the more the stream data is becoming corrupted between the sender and the receiver, requiring resends or dropping frames. syntax var slicount = rtcinboundrtpstreamstats.slicount; value an unsigned integer indicating the number of sli packets this receiver sent to the remote sender due to lost runs of macroblocks. a high value of slicount may ...
...g corrupted between the sender and the receiver, requiring resends or dropping frames. syntax var slicount = rtcinboundrtpstreamstats.slicount; value an unsigned integer indicating the number of sli packets this receiver sent to the remote sender due to lost runs of macroblocks. a high value of slicount may be an indication of an unreliable network. this is a very technical part of how video codecs work. for details, see rfc 4585: 6.3.2. note: this value is only present for video media. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.slicount' in that specification. candidate recommendation initial definition. ...
RTCOutboundRtpStreamStats.pliCount - Web APIs
the plicount property of the rtcoutboundrtpstreamstats dictionary states the number of times the remote peer's rtcrtpreceiver sent a picture loss indication (pli) packet to the rtcrtpsender for which this object provides statistics. a pli packet indicates that some amount of encoded video data has been lost for one or more frames. syntax var plicount = rtcoutboundrtpstreamstats.plicount; value an integer value indicating the number of times a pli packet was sent to this sender by the remote peer's rtcrtpreceiver. these are sent by the receiver's decoder to notify the sender's encoder that an undefined amount of coded video data, which may span frame boundaries, has been lost. note: this property is only used for video streams. usage notes upon receiving a pli packet, the sender may h...
...nize with the media. however, the primary purpose of a pli packet is to allow the rtcrtpsender for which this rtcoutboundrtpstreamstats object provides statistics to consider techniques to mitigate network performance issues. this is often achieved by methods such as increasing the compression or lowering resolution, although the mechanisms available to reduce the bit rate of the stream vary from codec to codec. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.plicount' in that specification. candidate recommendation initial definition. ...
RTCOutboundRtpStreamStats.sliCount - Web APIs
the slicount property of the rtcoutboundrtpstreamstats dictionary indicates how many slice loss indication (sli) packets the rtcrtpsender received from the remote rtcrtpreceiver for the rtp stream described by this object. an sli packet is used by a decoder to let the encoder (the sender) know that it's detected corruption of one or more consecutive macroblocks, in scan order, in the received media.in general, what's usually of interest is that the higher this number is, the more the stream data is becoming corrupted between the sender and the receiver, causing the receiver to request retransmits or to drop frames entirely. syntax var slicount = rtcoutboundrtpstreamstats.slicount; value an unsigned integer indicating the number of sli packets the sender received from the receiver due to ...
...d the receiver, causing the receiver to request retransmits or to drop frames entirely. syntax var slicount = rtcoutboundrtpstreamstats.slicount; value an unsigned integer indicating the number of sli packets the sender received from the receiver due to lost runs of macroblocks. a high value of slicount may be an indication of an unreliable network. this is a very technical part of how video codecs work. for details, see rfc 4585: 6.3.2. note: this value is only present for video media. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.slicount' in that specification. candidate recommendation initial definition. ...
RTCPeerConnection.addIceCandidate() - Web APIs
be constructed from a message received over the signaling channel, describing a newly received ice candidate that's ready to be delivered to the local ice agent. if no candidate object is specified, or its value is null, an end-of-candidates signal is sent to the remote peer using the end-of-candidates a-line, formatted simply like this: a=end-of-candidates deprecated parameters in older code and documentation, you may see a callback-based version of this function. this has been deprecated and its use is strongly discouraged. you should update any existing code to use the promise-based version of addicecandidate() instead. the parameters for this form of addicecandidate() are described below, to aid in updating existing code. successcallback a function to be called when the ice ...
...specified value of sdpmlineindex is greater than or equal to the number of media descriptions included in the remote description. the specified ufrag doesn't match the ufrag field in any of the remote descriptions being considered. one or more of the values in the candidate string are invalid or could not be parsed. attempting to add the candidate fails for any reason. examples this code snippet shows how to signal ice candidates across an arbitrary signaling channel. // this example assumes that the other peer is using a signaling channel as follows: // // pc.onicecandidate = event => { // if (event.candidate) { // signalingchannel.send(json.stringify({ice: event.candidate})); // "ice" is arbitrary // } else { // // all ice candidates have been sent // } // } sig...
RTCPeerConnection.addTrack() - Web APIs
ecified as a parameter when calling addtrack()). this track's kind is set to match the kind of the track provided as an input parameter. a new rtcrtptransceiver is created and associated with the new sender and receiver. the new transceiver's direction is set to "sendrecv". the new transceiver is added to the rtcpeerconnection's set of transceivers. example this example is drawn from the code presented in the article signaling and video calling and its corresponding sample code. it comes from the handlevideooffermsg() method there, which is called when an offer message is received from the remote peer. var mediaconstraints = { audio: true, // we want an audio track video: true // ...and we want a video track }; var desc = new rtcsessiondescription(sdp); p...
...once that succeeds, it uses mediadevices.getusermedia() to obtain access to the local webcam and microphone. if that succeeds, the resulting stream is assigned as the source for a <video> element which is referenced by the variable previewelement. the final step...
RTCPeerConnection.getStreamById() - Web APIs
the rtcpeerconnection.getstreambyid() method returns the mediastream with the given id that is associated with local or remote end of the connection. if no stream matches, it returns null. this property has been replaced with the rtcpeerconnection.getlocalstreams and rtcpeerconnection.getremotestreams properties. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. ...
...eams properties. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to return. example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not natively available. // from: https://bugs.chromium.org/p/chromium/issues/detail?id=698163&desc=5#c10 rtcpeerconnection.prototype.getstreambyid = function(id) { try { var localstreams = this.getlocalstreams(); var remotestreams = this.getremotestreams(); var i; for (i = 0; i < localstreams.
RTCPeerConnection: icecandidateerror event - Web APIs
ice negotiations through a stun or turn server. the event object is of type rtcpeerconnectioniceerrorevent, and contains information describing the error in some amount of detail. bubbles no cancelable no interface rtcpeerconnectioniceerrorevent event handler property rtcpeerconnection.onicecandidateerror description the error object's errorcode property is one of the numeric stun error codes. there is one additional, webrtc-specific, error which lies outside the valid stun error code range: 701. error 701 indicates that none of the ice candidates were able to successfully make contact with the stun or turn server. the 701 error is fired only once per server url from the list of available stun or turn servers provided when creating the ...
...r icecandidateerrors that occur on the rtcpeerconnection pc. this handler looks specifically for 701 errors that indicate that candidates couldn't reach the stun or turn server. when this happens, the server url and the error message are passed to a function called reportconnectfail() to log or output the connection failure. pc.addeventlistener("icecandidateerror", (event) => { if (event.errorcode === 701) { reportconnectfail(event.url, event.errortext); } }); note that if multiple stun and/or turn servers are provided when creating the connection, this error may happen more than once, if more than one of those servers fails. each provided server is tried until a connection is established. specifications specification status comment webrtc 1.0: real-time c...
RTCPeerConnection.onaddstream - Web APIs
the rtcpeerconnection.onaddstream event handler is a property containing the code to execute when the addstream event, of type mediastreamevent, is received by this rtcpeerconnection. such an event is sent when a mediastream is added to this connection by the remote peer. the event is sent immediately after the call setremotedescription() and doesn't wait for the result of the sdp negotiation. important: this property has been removed from the specification; you should now use rtcpeerconnection.ontrack to watch for track events instead. it is included here in order to help you adapt existing code and understand existing samples, which may not be up-to-date yet. syntax rtcpeerconnection.onaddstream = eventhandler; value a function which handles addstream events. these events, of type...
...n which handles addstream events. these events, of type mediastreamevent, are sent when streams are added to the connection by the remote peer. the first time an event occurs may be nearly immediately after the remote end of the connection is set using rtcpeerconnection.setremotedescription(); it doesn't wait for a particular stream to be accepted or rejected using sdp negotiation. example this code, based on an older version of our signaling and video calling sample, responds to addstream events by setting the video source for a <video> element to the stream specified in the event, and then enabling a "hang up" button in the app's user interface. pc.onaddstream = function(event) { document.getelementbyid("received_video").srcobject = event.stream; document.getelementbyid("hangup-button...
RTCPeerConnection.ontrack - Web APIs
ue set ontrack to be a function you provide that accepts as input a rtctrackevent object describing the new track and how it's being used. this information includes the mediastreamtrack object representing the new track, the rtcrtpreceiver and rtcrtptransceiver, and a list of mediastream objects which indicates which stream or streams the track is part of.. example this example, taken from the code for the article signaling and video calling, connects the incoming track to the <video> element which will be used to display the incoming video. pc.ontrack = function(event) { document.getelementbyid("received_video").srcobject = event.streams[0]; document.getelementbyid("hangup-button").disabled = false; }; the first line of our ontrack event handler takes the first stream in the incomin...
...ion(event) { document.getelementbyid("received_video").srcobject = event.streams[0]; document.getelementbyid("hangup-button").disabled = false; }; the first line of our ontrack event handler takes the first stream in the incoming track and sets the srcobject attribute to that. this connects that stream of video to the element so that it begins to be presented to the user. the second line of code simply enables a "hang up" button, which the user can use to disconnect from the call. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.ontrack' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.setLocalDescription() - Web APIs
se's fulfillment handler receives no input parameters. the process of changing descriptions actually involves intermediary steps handled by the webrtc layer to ensure that an active connection can be changed without losing the connection if the change does not succeed. see pending and current descriptions in webrtc connectivity for more details on this process. deprecated parameters in older code and documentation, you may see a callback-based version of this function used. this has been deprecated and its use is strongly discouraged, as it will be removed in the future. you should update any existing code to use the promise-based version of setlocaldescription() instead. the parameters for the older form of setlocaldescription() are described below, to aid in updating existing code. s...
...nection's signalingstate is "closed", indicating that the connection is not currently open, so negotiation cannot take place. invalidsessiondescriptionerror the rtcsessiondescription specified by the sessiondescription parameter is invalid. examples implicit descriptions one of the advantages of the parameter-free form of setlocaldescription() is that it lets you simplify your negotiation code substantially. this is all your negotiationneeded event handler needs to look like, for the most part. just add the signaling server code, which here is represented by the call to signalremotepeer(). pc.addeventlistener("negotiationneeded", async (event) => { await pc.setlocaldescription(); signalremotepeer({ description: pc.localdescription }); }); other than error handling, that's about ...
RTCPeerConnection.signalingState - Web APIs
interface returns one of the string values specified by the rtcsignalingstate enum; these values describe the state of the signaling process on the local end of the connection while connecting or reconnecting to another peer. see signaling in lifetime of a webrtc session for more details about the signaling process. ...
... this value may also be useful during debugging, for example. in addition, when the value of this property changes, a signalingstatechange event is sent to the rtcpeerconnection instance. ...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
ndinboundstats = findreportentry(endreport, "remoteid", endremoteoutbound.id); let elapsedtime = (endremoteoutbound.timestamp - startremoteoutbound.timestamp) / 1000; /* in seconds */ let packetssent = endremoteoutbound.packetssent - startremoteoutbound.packetssent; let bytessent = endremoteoutbound.bytessent - startremoteoutbound.bytessent; let framesdecoded = endinboundstats.framesdecoded - startinboundstats.framesdecoded; let framerate = framesdecoded / elapsedtime; let timestring = ""; if (!isnan(elapsedtime)) { timestring = ` representing ${elapsedtime}s`; } let framestring = ""; if (!isnan(framesdecoded)) { framestring = `decoded ${framesdecoded} frames for a ...
... the result from milliseconds to seconds. we compute the number of packets sent during this interval—packetssent—by subtracting the two reports' values for the packetssent property. similarly, the number of bytes sent during this interval—bytessent—is calculated by subtracting the starting statistics object's bytessent property from that of the ending statistics. the number of frames decoded during this interval—framesdecoded—is determined by subtracting startrecord's framesdecoded from endrecord.framesdecoded. finally, the frame rate over the elapsed time span is calculated by dividing framesdecoded by elapsedtime. the remainder of the networkteststop() function constructs the html used to display the output of the collected and computed results to the user, then append it t...
RTCRtpEncodingParameters.maxBitrate - Web APIs
other parameters may further reduce the bandwidth used by the track; for example, maxframerate will, if set low enough, constrain the bandwidth as well. ...
...other parameters may further reduce the bandwidth used by the track; for example, maxframerate will, if set low enough, constrain the bandwidth as well. in addition, there's no guarantee that the network interface can support the specified bandwidth, in which case the actual bandwidth will be lower. ...
RTCRtpEncodingParameters - Web APIs
an instance of the webrtc api's rtcrtpencodingparameters dictionary describes a single configuration of a codec for an rtcrtpsender. it's used in the rtcrtpsendparameters describing the configuration of an rtp sender's encodings; rtcrtpdecodingparameters is used to describe the configuration of an rtp receiver's encodings. properties active if true, the described encoding is currently actively being used. that is, for rtp senders, the encoding is currently being used to send data, while for receivers, the encoding is being used to decode received data. the default value is true. ...
...uration of an rtp sender's encodings; rtcrtpdecodingparameters is used to describe the configuration of an rtp receiver's encodings. properties active if true, the described encoding is currently actively being used. that is, for rtp senders, the encoding is currently being used to send data, while for receivers, the encoding is being used to decode received data. the default value is true. codecpayloadtype when describing a codec for an rtcrtpsender, codecpayloadtype is a single 8-bit byte (or octet) specifying the codec to use for sending the stream; the value matches one from the owning rtcrtpparameters object's codecs parameter. this value can only be set when creating the transceiver; after that, this value is read only. dtx only used for an rtcrtpsender whose kind is audio, this...
RTCRtpSendParameters.encodings - Web APIs
the rtcrtpsendparameters dictionary's encodings property is an rtcrtpencodingparameters object providing configuration settings for the encoder being used for the rtcrtpsender's track. syntax sendparameters.encodings = encodingparameterlist; encodingparameterlist = sendparameters.encodings; value an array of objects conforming to the rtcrtpencodingparameters dictionary, each of which contains properties which provide settings and parameters that describe and configure a single codec that could be used to encode the track. each object's properties are: active if true, the described encoding is currently actively being used. that is, for rtp senders, the encoding is currently being used to send data, while for receivers, the encoding is being used to decode received data. the default ...
...provide settings and parameters that describe and configure a single codec that could be used to encode the track. each object's properties are: active if true, the described encoding is currently actively being used. that is, for rtp senders, the encoding is currently being used to send data, while for receivers, the encoding is being used to decode received data. the default value is true. codecpayloadtype when describing a codec for an rtcrtpsender, codecpayloadtype is a single 8-bit byte (or octet) specifying the codec to use for sending the stream; the value matches one from the owning rtcrtpparameters object's codecs parameter. this value can only be set when creating the transceiver; after that, this value is read only. dtx only used for an rtcrtpsender whose kind is audio, this...
ReadableStream.pipeThrough() - Web APIs
readablestream.pipethrough(transformstream[, options]); parameters transformstream a transformstream (or an object with the structure {writable, readable}) consisting of a readable stream and a writable stream working together to transform some data from one form to another. data writen to the writable stream can be read in some transformed state by the readable stream. for example, a textdecoder, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. options optional the options that should be used when piping to the writable stream. available options are: preventclose: if this is set to true, the source readablestream closing will no longer cause the destination writablestream to be close...
...occurs during canceling the source. signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. return value the readable side of the transformstream. exceptions typeerror the writable and/or readable property of transformstream are undefined. examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream. next, we log the contents of the readable stream, use pipethrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. // fetch the original image fetch('png-logo.png') // retrieve its body as readablestre...
Reporting API - Web APIs
n useful to web developers when they are trying to fix bugs or improve their websites in other ways. such information can include: content security policy violations. feature-policy violations. deprecated feature usage (when you are using something that will stop working soon in browsers). occurrence of crashes. occurrence of user-agent interventions (when the browser blocks something your code is trying to do because it is deemed a security risk for example, or just plain annoying, like auto-playing audio). the reporting api's purpose is to provide a consistent reporting mechanism that can be used to make such information available to developers in the form of reports represented by javascript objects. there are a few ways to use it, which are detailed in the sections below. origins...
...edia) { navigator.mozgetusermedia( constraints, success, failure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details. note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia() method twice. after the first time we call reportingobserver.takerecords(), which returns the first generated report and empties the queue. because of this, when the button is pressed only the second report is listed. specifications specification status comment reporting api spec ...
Resize Observer API - Web APIs
concepts and usage there are a whole raft of use cases for responsive design techniques (and others besides) that respond to changes in an element's size, but previously their implementations have often been hacky and/or brittle. ...
...bove solution gives you nice square corners that scale with the box size. resize-observer-text.html (see source): here we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width. this shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport. ...
SVGAnimationElement - Web APIs
specifies an unknown element) the value returned is null. methods this interface also inherits methods from its parent, svgelement. svganimationelement.getstarttime() returns a float representing the begin time, in seconds, for this animation element's current interval, if it exists, regardless of whether the interval has begun yet. if there is no current interval, then a domexception with code invalid_state_err is thrown. svganimationelement.getcurrenttime() returns a float representing the current time in seconds relative to time zero for the given time container. svganimationelement.getsimpleduration() returns a float representing the number of seconds for the simple duration for this animation. if the simple duration is undefined (e.g., the end time is indefinite), then a domexc...
...te_err is thrown. svganimationelement.getcurrenttime() returns a float representing the current time in seconds relative to time zero for the given time container. svganimationelement.getsimpleduration() returns a float representing the number of seconds for the simple duration for this animation. if the simple duration is undefined (e.g., the end time is indefinite), then a domexception with code not_supported_err is raised. svganimationelement.beginelement() creates a begin instance time for the current time. the new instance time is added to the begin instance times list. the behavior of this method is equivalent to beginelementat(0). svganimationelement.beginelementat() creates a begin instance time for the current time plus the specified offset. the new instance time is adde...
SVGImageElement - Web APIs
t</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggraphicselement. svgimageelement.crossorigin a domstring corresponding to the crossorigin attribute of the given <image> element. svgimageelement.decoding returns a domstring representing a hint given to the browser on how it should decode the image. svgimageelement.height read only an svganimatedlength corresponding to the height attribute of the given <image> element. svgimageelement.preserveaspectratio read only an svganimatedpreserveaspectratio corresponding to the preserveaspectratio attribute of the given <image> element. svgimageelement.width read only an svganimatedlength corresponding to the width attribute of the...
... to the width attribute of the given <image> element. svgimageelement.x read only an svganimatedlength corresponding to the x attribute of the given <image> element. svgimageelement.y read only an svganimatedlength corresponding to the y attribute of the given <image> element. methods this interface also inherits methods from its parent interface, svggraphicselement. svgimageelement.decode() initiates asynchronous decoding of the image data. returns a promise which resolves once the image data is ready to be used. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgimageelement' in that specification. candidate recommendation changed the inheritance from svgelement to svggraphicselement, removed the imp...
SVGStyleElement - Web APIs
t-baseline="middle">svgstyleelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent interface, svgelement and implements properties from linkstyle. svgstyleelement.type a domstring corresponding to the type attribute of the given element. svg 1.1 defined that a domexception is raised with code no_modification_allowed_err on an attempt to change the value of a read-only attribute. this restriction was removed in svg 2. svgstyleelement.media a domstring corresponding to the media attribute of the given element. svg 1.1 defined that a domexception is raised with code no_modification_allowed_err on an attempt to change the value of a read-only attribute. this restriction was removed i...
...this restriction was removed in svg 2. ...
Screen.availHeight - Web APIs
ue of availheight is approximately the value of height (the total height of the screen in css pixels) minus the heights of the dock and menu bar, as seen in the diagram below. example if your web application needs to open a new window, such as a tool palette which can contain multiple panels, and wants to position it so that it occupies the entire vertical space available, you can do so using code similar to what's seen here. in the main window, when it's time to open the panels, code like the following is used. let palettewindow = window.open("panels.html", "panels", "left=0, top=0, width=200"); the panels window's html, in panels.html, has javascript code of its own, which is executed as soon as the window is created. it doesn't even need to wait for any particular event (or any event...
...note the panels window filling all available vertical space at the left of the screen. ...
ServiceWorkerContainer - Web APIs
current page is actively controlled. properties serviceworkercontainer.controller read only returns a serviceworker object if its state is activated (the same object returned by serviceworkerregistration.active). this property returns null during a force-refresh request (shift + refresh) or if there is no active worker. serviceworkercontainer.ready read only provides a way of delaying code execution until a service worker is active. it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an serviceworkerregistration.active worker. once that condition is met, it resolves with the serviceworkerregistration. events controllerchange occurs when the document's associated serviceworkerregistr...
... serviceworkercontainer.startmessages() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. examples the example below first checks to see if the browser supports service workers. if supported, the code registers the service worker and determines if the page is actively controlled by the service worker. if it isn't, it prompts the user to reload the page so the service worker can take control. the code also reports any registration failures. if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope. navigator.serviceworker.r...
ServiceWorkerGlobalScope.onfetch - Web APIs
the onfetch property of the serviceworkerglobalscope interface is an event handler fired whenever a fetch event occurs (usually when the windoworworkerglobalscope.fetch() method is called.) syntax serviceworkerglobalscope.onfetch = function(fetchevent) { ... }; example this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, the code returns a promise that resolves to the first matching request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an exception. it will return a normal response object th...
... self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache. ...
ServiceWorkerGlobalScope - Web APIs
alscope — which implements windoworworkerglobalscope. therefore it also has the following property available to it: globalfetch.fetch() starts the process of fetching a resource. this returns a promise that resolves to the response object representing the response to your request. this algorithm is the entry point for the fetch handling handed to the service worker context. ...
...ce. this returns a promise that resolves to the response object representing the response to your request. this algorithm is the entry point for the fetch handling handed to the service worker context. examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, the code returns a promise that resolves to the first matching request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an exception. it will return a normal response object that has the appropriate error code set. self.addeventlistener...
SharedWorkerGlobalScope - Web APIs
orker, which is a regular performance object, but with a subset of its properties and methods available. event handlers this interface inherits event handlers from the workerglobalscope interface, and its parent eventtarget, and therefore implements event handlers from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.onconnect is an eventhandler representing the code to be called when the connect event is raised — that is, when a messageport connection is opened between the associated sharedworker and the main thread. methods this interface inherits methods from the workerglobalscope interface, and its parent eventtarget, and therefore implements methods from windowtimers, windowbase64, and windoweventhandlers. sharedworkerglobalscope.close() discard...
...alscope.dump() allows you to write a message to stdout — i.e. in your terminal. this is the same as firefox's window.dump, but for workers. workerglobalscope.importscripts() imports one or more scripts into the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding. 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 ex...
SourceBuffer.changeType() - Web APIs
syntax sourcebuffer.changetype(type); parameters type a domstring specifying the mime type that future buffers will conform to. return value undefined. ...
... syntax sourcebuffer.changetype(type); parameters type a domstring specifying the mime type that future buffers will conform to. return value undefined. ...
Using the Storage Access API - Web APIs
ds to add the allow-storage-access-by-user-activation sandbox token to allow storage access requests to be successful, along with allow-scripts and allow-same-origin to allow it to call the api, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"> ... </iframe> now on to the code executed inside the embedded document. since it does not know whether it currently has access to storage, it should first call document.hasstorageaccess(). if that call returns false, we can then call document.requeststorageaccess(), returning the result so that then we can chain it onto the previous promise call. in the final then, we'll have first-party storage access. document.hasstorageacces...
...t's access some items from the first-party cookie jar document.cookie = "foo=bar"; // set a cookie localstorage.setitem("username", "john"); // access a localstorage entry }).catch(_ => { // error obtaining storage access. }); note that access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click — so this code needs to be run inside some kind of user gesture-based event handler, for example: btn.addeventlistener('click', () => { // run code here }); ...
Touch.force - Web APIs
Web › API › Touch › force
n, the absolute pressure represented by the force attribute, and the sensitivity in levels of pressure, may vary. example this example illustrates using the touch interface's touch.force property. this property is a relative value of pressure applied, in the range 0.0 to 1.0, where 0.0 is no pressure, and 1.0 is the highest level of pressure the touch device is capable of sensing. in following code snippet, the touchstart event handler iterrates through the targettouches list and logs the force value of each touch point but the code could invoke different processing depending on the value. someelement.addeventlistener('touchstart', function(e) { // iterate through the list of touch points and log each touch // point's force. for (var i=0; i < e.targettouches.length; i++) { //...
...for example // minimum pressure vs. maximum pressure could result in // different handling of the user's input. ...
Multi-touch interaction - Web APIs
er, the interfaces can be a bit tricky for programmers to use because touch events are very different from other dom input events, such as mouse events. the application described in this guide shows how to use touch events for simple single and multi-touch interactions, the basics needed to build application-specific gestures. a live version of this application is available on github. the source code is available on github and pull requests and bug reports are welcome. example this example demonstrates using the touchstart, touchmove, touchcancel, and touchend) touch events for the following gestures: single touch, two (simultaneous) touches, more than two simultaneous touches, 1-finger swipe, and 2-finger move/pinch/swipe. define touch targets the application uses <div> elements to repre...
...dler; el.ontouchmove = move_handler; // use same handler for touchcancel and touchend el.ontouchcancel = end_handler; el.ontouchend = end_handler; } function init() { set_handlers("target1"); set_handlers("target2"); set_handlers("target3"); set_handlers("target4"); } move/pinch/zoom handler this function provides very basic support for 2-touch horizontal move/pinch/zoom handling. the code does not include error handling, or vertical moving. note that the threshold for pinch and zoom movement detection is application specific (and device dependent). // this is a very basic 2-touch move/pinch/zoom handler that does not include // error handling, only handles horizontal moves, etc. function handle_pinch_zoom(ev) { if (ev.targettouches.length == 2 && ev.changedtouches.length == 2) ...
URLUtilsReadOnly - Web APIs
this has been fixed to match the spec.ie no support noopera no support nosafari no support nowebview android no support nochrome android no support nofirefox android ...
...this has been fixed to match the spec.opera android no support nosafari ios no support nosamsung internet android no support nohost experimentalchrome no support noedge no support ...
VideoConfiguration - Web APIs
eo file being tested when calling the mediacapabilities methods encodinginfo() and decodinginfo() to determine whether or not the described video configuration is supported, and how smoothly and how smoooth and power-efficient it can be handled. properties the videoconfiguration dictionary is made up of five video properties, including: contenttype: a valid video mime type. see our web video codec guide for types which may be supported. width: the width of the video. height: the height of the video. bitrate: the number of bits used to encode one second of the video file. framerate: the number of frames making up one second of video playback. examples // create media configuration to be tested const mediaconfig = { type : 'file', // see mediadecodingconfiguration and mediaencod...
...e video. height: the height of the video. bitrate: the number of bits used to encode one second of the video file. framerate: the number of frames making up one second of video playback. examples // create media configuration to be tested const mediaconfig = { type : 'file', // see mediadecodingconfiguration and mediaencodingconfiguration video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames making up that 1s. } }; specifications specification status comment media capabilitiesthe definition of 'videoconfiguration...
WebGLRenderingContext.makeXRCompatible() - Web APIs
estored events are used: the first gives you the opportunity to discard anything you won't need anymore, while the second gives you the opportunity to load resources and prepare to render the scene in its new context. while this method is available through the webglrenderingcontext interface, it's actually defined by the webxr device api rather than by webgl. examples this example demonstrates code logic you might find in a game that starts up using webgl to display menus and other ui, and uses webgl to render gameplay, but has a button on its main menu that offers an option to start the game in webxr mode. html the html for the buttons looks lke this: <button class="green button" type="button">start game</button> <button class="blue button use-webxr" type="button">start game (vr mode)</...
...ype="button">start game</button> <button class="blue button use-webxr" type="button">start game (vr mode)</button> the first button starts the game, continuing to present the game onscreen as usual. the second button will be used to start the game in immersive-vr mode. note the inclusion of a use-webxr class on the vr mode button. this is important, which we'll explore shortly. ...
WebGLRenderingContext - Web APIs
webglrenderingcontext.getshaderparameter() returns information about the shader. webglrenderingcontext.getshaderprecisionformat() returns a webglshaderprecisionformat object describing the precision for the numeric format of the shader. webglrenderingcontext.getshaderinfolog() returns the information log for a webglshader object. webglrenderingcontext.getshadersource() returns the source code of a webglshader as a string. webglrenderingcontext.isprogram() returns a boolean indicating if the passed webglprogram is valid. webglrenderingcontext.isshader() returns a boolean indicating if the passed webglshader is valid. webglrenderingcontext.linkprogram() links the passed webglprogram object. webglrenderingcontext.shadersource() sets the source code in a webglshader. webglrenderi...
...ument.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. specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext' in that specification. recommendation initial definition ...
Hello GLSL - Web APIs
xt » this webgl example demonstrates a very basic glsl shader program that draws a solid color square. note: this example will most likely work in all modern desktop browsers. but it may not work in some mobile or older browsers. if the canvas remains blank, you can check the output of the next example, which draws exactly the same thing. but remember to read through the explanations and code on this page, before moving on to the next. hello world program in glsl a very simple first shader program. <p>hello world! hello glsl!</p> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { displa...
... « previousnext » ...
Raining rectangles - Web APIs
tion, 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 demonstrates how to integrate the webgl function calls within a game loop. the game loop is responsible for drawing the ...
... « previousnext » ...
WebGL best practices - Web APIs
cit webgl.flush() isn't really needed with raf. avoid blocking api calls in production (e.g. geterror, getparameter) certain webgl entry points cause synchronous stalls on the calling thread. even basic requests can take as long as 1ms, but they can take even longer if they need to wait for all graphics work to be completed (with an effect similar to glfinish() in native opengl). in production code, avoid such entry points, especially on the browser main thread where they can cause the entire page to jank (often including scrolling or even the whole browser). geterror(): causes a flush + round-trip to fetch errors from the gpu process). for example, within firefox, the only time glgeterror is checked is after allocations (bufferdata, *teximage*, texstorage*) to pick up any gl_out_o...
...^8, 2^8] [0, 2^9] prefer builtins like dot, mix, and normalize instead of buiding your own at best, custom implementations of builtins might run as fast as the builtins they replace, but don't expect them to. hardware often has hyper-optimized or even specialized instructions for builtins, and the compiler can't reliably replace your custom builtin-replacements with the special builtin codepaths. textures use mipmaps for any texture you'll see in 3d! when in doubt, call generatemipmaps() after texture uploads. mipmaps are cheap on memory (only 30% overhead) while providing often-large performance advantages when textures are "zoomed out" or generally downscaled in the distance in 3d, or even for cube-maps! it's quicker to sample from smaller texture images due to better inherent...
Web Video Text Tracks Format (WebVTT) - Web APIs
where you can use spaces you can also use tabs. there is also a small api available to represent and manage these tracks and the data needed to perform the playback of the text at the correct times. webvtt files the mime type of webvtt is text/vtt. ...
...on interface this is the second interface in webvtt api. the new keyword can be used for defining a new vttregion object which can then be used for containing the multiple cues. there are several properties of vttregion which are width, lines, regionanchorx, regionanchory, viewportanchorx, viewportanchory and scroll that can be used to specify the look and feel of this vtt region. ...
WebXR application life cycle - Web APIs
this serves as preparation for the next few articles in these webxr guides, which cover starting up and shutting down a webxr session, geometry, simulating cameras, spatial tracking, and more. life cycle outline most applications using webxr will follow a similar overall design pattern: check to see if the user's device and browser are both capable of presenting the xr experience you want to provide. ...
...to render the next frame. when the time comes (such as when the user exits your app or navigates away from your site), end the xr session; otherwise, continue the loop until the user chooses to exit xr mode. to end the xr session yourself, call xrsession.end(). include a handler for the xrsession event end event to be informed when the session is ending, regardless of whether your code, the user, or the browser initiated the termination of the session. ...
Lighting a WebXR setting - Web APIs
because the webxr device api relies on other technologies—namely, webgl and frameworks based upon it—to perform all rendering, texturing, and lighting of a scene, the same general lighting concepts apply to webxr settings or scenes as to any other webgl-generated display. however, there are issues and details to keep in mind while creating your lighting code, especially for augmented reality (ar) applications. this guide discusses these topics. and while this article provides brief reminders as to how lighting works in general, it is not by any means a tutorial in lighting or a guide to how to create a properly-lit 3d scene. flashback: simulating lighting in 3d although this article isn't a comprehensive guide to lighting a 3d scene, it's useful to provide a brief reminder as to how li...
...ur objects, since your virtual objects need to exist within a physical world that has its own light sources. as such, you should try to match your lighting to the real world's light sources as much as possible. this is done using a technique known as lighting estimation. conversely, you should try to avoid having virtual objects that are themselves light sources, unless you're prepared to create code that can cast that lighting onto the real world setting. casting light onto real-world objects is essentially the opposite of casting shadows. it can be done, but is not as widely implemented. lighting estimation lighting estimation is a technique used by augmented reality platforms to attempt to match the lighting of the virtual objects in the scene to the lighting of the real world surroundin...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
e, vector, or matrix in the original space, converts it to the target space. thus a pose can be used to not only convert and determine positions, but also rotational information. there is only one way to create an xrpose, and that's using the getpose() method on an animation frame as given using an xrframe object. this means that most frequently, you'll be using poses within your frame rendering code, which is executed as a callback from the xrframe method requestanimationframe(). getpose() computes the position of an xrreferencespace relative to the origin of a specified xrspace and then creates a pose representing the resulting position and orientation. for example, if you wish to draw a hand controller's representation using the controller's gripspace, you can get the pose needed like th...
... in order to place the virtual camera and render the scene. the only way to obtain a pose that adapts positional information from one space to another is through the xrframe object received by your frame rendering callback function specified when you called the xrsession method requestanimationframe(). ...
Basic concepts behind Web Audio API - Web APIs
output is composed of one or more audio channels, which together represent a specific audio layout. any discrete channel structure is supported, including mono, stereo, quad, 5.1, and so on. audio sources can be obtained in a number of ways: sound can be generated directly in javascript by an audio node (such as an oscillator). created from raw pcm data (the audio context has methods to decode supported audio formats). taken from html media elements (such as <video> or <audio>). taken directly from a webrtc mediastream (such as a webcam or microphone). audio data: what's in a sample when an audio signal is processed, sampling means the conversion of a continuous signal to a discrete signal; or put another way, a continuous sound wave, such as a band playing live, is converted to a...
...tored like this: llllllllllllllllrrrrrrrrrrrrrrrr (for a buffer of 16 frames) this is very common in audio processing: it makes it easy to process each channel independently. the alternative is to use an interleaved buffer format: lrlrlrlrlrlrlrlrlrlrlrlrlrlrlrlr (for a buffer of 16 frames) this format is very common for storing and playing back audio without much processing, for example a decoded mp3 stream. the web audio api exposes only planar buffers, because it's made for processing. it works with planar, but converts the audio to interleaved when it is sent to the sound card for playback. conversely, when an mp3 is decoded, it starts off in interleaved format, but is converted to planar for processing. audio channels different audio buffers contain different numbers of channels...
Web Audio API best practices - Web APIs
there's no strict right or wrong way when writing creative code. as long as you consider security, performance, and accessibility, you can adapt to your own style. in this article, we'll share a number of best practices — guidelines, tips, and tricks for working with the web audio api. loading sounds/files there are four main ways to load sound with the web audio api and it can be a little confusing as to which one you should use. when working with files, you are looking at either the grabbing the file from an htmlmediaelement (i.e. an <audio> or <video> element), or you're looking to fetch the file and decode it into a buffer. both are legitimate ways of working, however, it's more common to use the former when you are working with full-length tracks, and the latter when working with sh...
... half. however, if you're using any of the audioparam's defined methods to set these values, they will take precedence over the above property setting. if for example, you want the gain value to be raised to 1 in 2 seconds time, you can do this: gainnode.gain.setvalueattime(1, audioctx.currenttime + 2); it will override the previous example (as it should), even if it were to come later in your code. bearing this in mind, if your website or application requires timing and scheduling, it's best to stick with the audioparam methods for setting values. if you're sure it doesn't, setting it with the value property is fine. ...
Example and tutorial: Simple synth keyboard - Web APIs
the keyboard allows you to switch among the standard waveforms as well as one custom waveform, and you can control the master gain using a volume slider beneath the keyboard. this example makes use of the following web api interfaces: audiocontext, oscillatornode, periodicwave, and gainnode. because oscillatornode is based on audioscheduledsourcenode, this is to some extent an example for that as well. the video keyboard html there are three primary components to the display for our virtual keyboard. the first is the musical keyboard itself. ...
... let audiocontext = new (window.audiocontext || window.webkitaudiocontext)(); let osclist = []; let mastergainnode = null; audiocontext is set to reference the global audiocontext object (or webkitaudiocontext if necessary). osclist is set up to be ready to contain a list of all currently-playing oscillators. it starts off empty, since there are ...
Using IIR filters - Web APIs
ment one, and use it in a simple example. demo our simple example for this guide provides a play/pause button that starts and pauses audio play, and a toggle that turns an iir filter on and off, altering the tone of the sound. it also provides a canvas on which is drawn the frequency response of the audio, so you can see what effect the iir filter has. you can check out the full demo here on codepen. also see the source code on github. it includes some different coefficient values for different lowpass frequencies — you can change the value of the filternumber constant to a value between 0 and 3 to check out the different available effects. browser support iir filters are supported well across modern browsers, although they have been implemented more recently than some of the more lon...
...ter node and need some values to help along the way, there's a table of already calculated values here; on pages 4 & 5 of the linked pdf the an values refer to the feedforward values and the bn values refer to the feedback. musicdsp.org is also a great resource if you want to read more about different filters and how they are implemented digitally. with that all in mind, let's take a look at the code to create an iir filter with the web audio api. setting our iirfilter co-efficients when creating an iir filter, we pass in the feedforward and feedback coefficients as options (coefficients is how we describe the values). both of these parameters are arrays, neither of which can be larger than 20 items. when setting our coefficients, the feedforward values can't all be set to zero, otherwise ...
Web audio spatialization basics - Web APIs
t a 2d plane, so if you were planning a 2d game, this would still be the node you were looking for. note: there's also a stereopannernode designed to deal with the common use case of creating simple left and right stereo panning effects. this is much simpler to use, but obviously nowhere near as versatile. if you just want a simple stereo panning effect, our stereopannernode example (see source code) should give you everything you need. 3d boombox demo to demonstrate 3d spatialization we've created a modified version of the boombox demo we created in our basic using the web audio api guide. see the 3d spatialization demo live (and see the source code also). the boombox sits inside a room (defined by the edges of the browser viewport), and in this demo, we can move and rotate it with th...
... some time to get them right. note: there are slight differences in the way the audio spatialization sounds across different browsers. the panner node does some very involved maths under the hood; there are a number of tests here so you can keep track of the status of the inner workings of this node across different platforms. again, you can check out the final demo here, and the final source code is here. there is also a codepen demo too. if you are working with 3d games and/or webxr it's a good idea to harness a 3d library to create such functionality, rather than trying to do this all yourself from first principles. we rolled our own in this article to give you an idea of how it works, but you'll save a lot of time by taking advantage of work others have done before you. ...
Web Locks API - Web APIs
when the lock is granted. the lock is automatically released when the callback returns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished. the request() method itself returns a promise which resolves once the lock has been released; within an async function, a script can await the call to make the asynchronous code flow linear. for example: await do_something_without_lock(); // request the lock. await navigator.locks.request('my_resource', async lock => { // the lock has been acquired. await do_something_with_lock(); await do_something_else_with_lock(); // now the lock will be released. }); // the lock has been released. await do_something_else_without_lock(); options several options can be pa...
...uested out-of-order. if tab 1 holds lock a and tab 2 holds lock b, then tab 1 attempts to also acquire lock b and tab 2 attempts to also acquire lock a, neither request can be granted. web applications can avoid this through several strategies, such as ensuring lock requests are not nested, or are always well ordered, or have timeouts. note that such deadlocks only affect the locks themselves and code depending on them; the browser, other tabs, and other script in the page is not affected. interfaces lock provides the name and mode of a previously requested lock, which is received in the callback to lockmanager.request(). lockmanager provides methods for requesting a new lock object and querying for an existing lock object. to get an instance of lockmanager, call navigator.locks. spec...
Using the Web Storage API - Web APIs
at detects whether localstorage is both supported and available: function storageavailable(type) { var storage; try { storage = window[type]; var x = '__storage_test__'; storage.setitem(x, x); storage.removeitem(x); return true; } catch(e) { return e instanceof domexception && ( // everything except firefox e.code === 22 || // firefox e.code === 1014 || // test name field too, because code might not be present // everything except firefox e.name === 'quotaexceedederror' || // firefox e.name === 'ns_error_dom_quota_reached') && // acknowledge quotaexceedederror only if there's something already stored ...
...e the page and load it again, later on, your choices are remembered. we have also provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a storageevent is fired. note: as well as viewing the example pages live using the above links, you can also check out the source code. testing whether your storage has been populated to start with, in main.js, we test whether the storage object has already been populated (i.e., the page was previously accessed): if(!localstorage.getitem('bgcolor')) { populatestorage(); } else { setstyles(); } the storage.getitem() method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor it...
Functions and classes available to Web Workers - Web APIs
erver to push data to a web page at any point, after a connection has been opened to it. 53 (53) (currently only available in dedicated and shared workers; not service workers.) ? (yes) ? serviceworkerregistration you can register a service worker from inside a standard worker, and use associated functionality. 40 (40) no support (yes) no support textencoder and textdecoder create and return a new textencoder, or respectively textdecoder, allowing to encode or decode strings into specific encodings. 20 (20) no support no support no support url workers can use the static methods url.createobjecturl and url.revokeobjecturl with blob objects accesible to the worker. workers can also create a new url using the url() constr...
...pport workerglobalscope the global scope of workers. this objects defines worker-specific functions. (yes) 10.0 (yes) (yes) workerlocation the subset of the location interface available to workers. 3.6 (1.9.2) 10.0 (yes) (yes) workernavigator the subset of the navigator interface available to workers. basic implementation (yes) appcodename, product, taintenabled(): 28 (28) online: 29 (29) navigatorlanguage: (yes) appname, appversion, online, platform, useragent: 10.0 other: no support (yes) (yes) xmlhttprequest creates and returns a new xmlhttprequest object; this mimics the behavior of the standard xmlhttprequest() constructor. note that the responsexml and channel attributes on xmlhttprequest...
Window.devicePixelRatio - Web APIs
; ctx.textbaseline = 'middle'; var x = size / 2; var y = size / 2; var textstring = "i love mdn"; ctx.filltext(textstring, x, y); monitoring screen resolution or zoom level changes in this example, we'll set up a media query and watch it to see when the device resolution changes, so that we can check the value of devicepixelratio to handle any updates we need to. javascript the javascript code creates the media query that monitors the device resolution and checks the value of devicepixelratio any time it changes. let pixelratiobox = document.queryselector(".pixel-ratio"); let mqstring = `(resolution: ${window.devicepixelratio}dppx)`; const updatepixelratio = () => { let pr = window.devicepixelratio; let prstring = (pr * 100).tofixed(0); pixelratiobox.innertext = `${prstring}% (...
...r for the change event. html the html creates the boxes containing the instructions and the pixel-ratio box that will display the current pixel ratio information. <div class="container"> <div class="inner-container"> <p>this example demonstrates the effect of zooming the page in and out (or moving it to a screen with a different scaling factor) on the value of the property <code>window.devicepixelratio</code>. try it and watch what happens!</p> </div> <div class="pixel-ratio"></div> </div> css body { font: 22px arial, sans-serif; } .container { top: 2em; width: 22em; height: 14em; border: 2px solid #22d; margin: 0 auto; padding: 0; background-color: #a9f; } .inner-container { padding: 1em 2em; text-align: justify; text-justify: au...
Window.matchMedia() - Web APIs
Web › API › Window › matchMedia
x-width: 600px) and displays the value of the resulting mediaquerylist's matches property in a <span>; as a result, the output will say "true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that. javascript let mql = window.matchmedia('(max-width: 600px)'); document.queryselector(".mq-value").innertext = mql.matches; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the results' matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded. html <span class="mq-value"></span> a simple <span> to receive the output. css .mq-value { font: 18px arial, sans-serif; font-wei...
...property, so that it indicates whether or not the document matches the media query at the moment the page was loaded. html <span class="mq-value"></span> a simple <span> to receive the output. css .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } result see testing media queries programmatically for additional code examples. specifications specification status comment css object model (cssom) view modulethe definition of 'window.matchmedia()' in that specification. working draft initial definition ...
Window: message event - Web APIs
ssage event is fired on a window object when the window receives a message, for example from a call to window.postmessage() from another browsing context. ...
...text, such as another <iframe>, using code like this: const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const windowmessagebutton = document.queryselector('#window-message'); windowmessagebutton.addeventlistener('click', () => { targetframe.postmessage('hello there', targetorigin); }); the receiver can listen for the message using addeventlistener() with code like this: window.addeventlistener('message', (event) => { console.log(`received message: ${event.data}`); }); alternatively the listener could use the onmessage event handler property: window.onmessage = (event) => { console.log(`received message: ${event.data}`); }; specifications specification status html living standard living standard ...
window.postMessage() - Web APIs
postmessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the messageevent is dispatched. the value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window. for idn host names only, the value of the origin property is not consistently unicode or punycode; for greatest compatibility check for both the idn and punycode values when using this property if you expect messages from idn sites. this value will eventually be consistently idn, but for now you should handle both idn and punycode forms. the value of the origin property when the sending window contains a javascript: or data: url is the origin of the script that loaded the url. u...
...rty if you expect messages from idn sites. this value will eventually be consistently idn, but for now you should handle both idn and punycode forms. the value of the origin property when the sending window contains a javascript: or data: url is the origin of the script that loaded the url. using window.postmessage in extensions window.postmessage is available to javascript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction. (the other properties have their expected values.) it is not possible for content or web context scripts to specify a targetorigin to communicate directly with an extension (either the background script or a content script). web or content scripts can use window.po...
Window: resize event - Web APIs
esize changes. see resize observer to read the draft document, and github issues to read the on-going discussions. examples window size logger the following example reports the window size each time it is resized. bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. ...
.... see resize observer to read the draft document, and github issues to read the on-going discussions. examples window size logger the following example reports the window size each time it is resized. bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. ...
Window.screenX - Web APIs
Web › API › Window › screenX
screenx was implemented across modern browsers in more recent times — window.screenleft. this was originally supported only in ie but was introduced everywhere due to popularity. syntax leftwindowpos = window.screenx returns a number equal to the number of css pixels from the left edge of the browser viewport to the left edge of the screen. examples in our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle. in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. initialleft = window.screenleft + canvaselem.offsetleft; initialtop = window.screentop + canvaselem.offsettop; funct...
...inpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); these work in exactly the same way as screenx/screeny. also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using screenx/screeny. if(!window.screenleft) { window.screenleft = window.screenx; window.screentop = window.screeny; } specifications specification status comment css object model (cssom) view modulethe definition of 'window.screenx' in that specifi...
WindowOrWorkerGlobalScope.atob() - Web APIs
the windoworworkerglobalscope.atob() function decodes a string of data which has been encoded using base64 encoding. you can use the btoa() method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the atob() method to decode the data again. for example, you can encode, transmit, and decode control characters such as ascii values 0 through 31. for use with unicode or utf-8 strings, see the note on "unicode strings" in the page for btoa(). syntax var decodeddata = scope.atob(encodeddata); parameters encodeddata a binary string contains an base64 encoded data. return value an ascii string containing decoded data from encodeddata. exceptions domexception (name: invalidcharactererror) throws if encodeddata is not valid base64. ...
...or utf-8 strings, see the note on "unicode strings" in the page for btoa(). syntax var decodeddata = scope.atob(encodeddata); parameters encodeddata a binary string contains an base64 encoded data. return value an ascii string containing decoded data from encodeddata. exceptions domexception (name: invalidcharactererror) throws if encodeddata is not valid base64. example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.a...
WindowOrWorkerGlobalScope - Web APIs
scope.issecurecontext read only returns a boolean indicating whether the current context is secure (true) or not (false). windoworworkerglobalscope.origin read only returns the origin of the global 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 windoworworkerglobals...
...and returns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after execution of the javascript code completes and control isn't being returned to a javascript caller, but before handling callbacks and other tasks. this lets your code run without interfering with other, possibly higher priority, code, but before the browser runtime regains control, potentially depending upon the work you need to complete. windoworworkerglobalscope.setinterval() schedules a function to execute every time a give...
Worker - Web APIs
Web › API › Worker
through to the worker. this is inherited from abstractworker. worker.onmessage an eventlistener called whenever a messageevent of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via dedicatedworkerglobalscope.postmessage. the message is stored in the event's data property. worker.onmessageerror is an eventhandler representing the code to be called when the messageerror event is raised. methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. worker.postmessage() sends a message — consisting of any javascript object — to the worker's inner scope. worker.terminate() immediately terminates the worker. this does not let worker finish its operations; it is halted at once. se...
... property. rejectionhandled fires every time a promise rejects, regardless of whether or not there is a handler to catch the rejection. also available through the onrejectionhandled event handler property. unhandledrejection fires when a promise rejects with no handler to catch the rejection. also available using the onunhandledrejection event handler property. ...
WorkerGlobalScope.performance - Web APIs
note: firefox has a bug with using console.log inside shared/service workers (see bug 1058644), which may return strange results, but this should be fixed soon. specifications specification status ...
... note: firefox has a bug with using console.log inside shared/service workers (see bug 1058644), which may return strange results, but this should be fixed soon. specifications specification status comment high resolution tim...
Worklet - Web APIs
Web › API › Worklet
worklet types worklets are restricted to specific use cases; they cannot be used for arbitrary computations like web workers. the worklet interface abstracts properties and methods common to all kind of worklets, and cannot be created directly. ...
... api animationworklet for creating scroll-linked and other high performance procedural animations. compositor thread css animation worklet api layoutworklet for defining the positioning and dimensions of custom elements. css layout api for 3d rendering with webgl, you don't use worklets. instead, you write vertex shaders and fragment shaders using glsl code, and those shaders will then run on the graphics card. properties the worklet interface does not define any properties. methods worklet.addmodule() adds the script module at the given url to the current worklet. specifications specification status comment worklets level 1the definition of 'worklet' in that specification. working draft ...
Sending and Receiving Binary Data - Web APIs
(default), "arraybuffer", "blob", "document", "json", and "text". the response property will contain the entity body according to responsetype, as an arraybuffer, blob, document, json, or string. this is null if the request is not complete or was not successful. this example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes. note that this will not decode the image and read the pixels. you will need a png decoding library for that. var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png", true); oreq.responsetype = "arraybuffer"; oreq.onload = function (oevent) { var arraybuffer = oreq.response; // note: not oreq.responsetext if (arraybuffer) { var bytearray = new uint8array(arraybuffer); for (var i = 0; i < bytearray.byteleng...
...r-defined'); req.send(null); if (req.status != 200) return ''; return req.responsetext; } the magic happens in line 5, which overrides the mime type, forcing the browser to treat it as plain text, using a user-defined character set. this tells the browser not to parse it, and to let the bytes pass through unprocessed. var filestream = load_binary_resource(url); var abyte = filestream.charcodeat(x) & 0xff; // throw away high-order byte (f7) the example above fetches the byte at offset x within the loaded binary data. the valid range for x is from 0 to filestream.length-1. see downloading binary streams with xmlhttprequest for a detailed explanation. see also downloading files. sending binary data the send method of the xmlhttprequest has been extended to enable easy transmission o...
Using XMLHttpRequest in IE6 - Web APIs
xmlhttprequest was first introduced by microsoft in internet explorer 5.0 as an activex control. however, in ie7 and other browsers xmlhttprequest is a native javascript object. ...
... xmlhttprequest was first introduced by microsoft in internet explorer 5.0 as an activex control. however, in ie7 and other browsers xmlhttprequest is a native javascript object. ...
XRInputSource.targetRayMode - Web APIs
eted direction. the direction is determined using platform-specific rules, though if no such rules exist, the direction is chosen by assuming the user is pointing their index finger straight out from their hand. usage notes the input source's targetrayspace indicates the position and orientation of the target ray, and can be used to determine where to render the ray. example this fragment of code shows part of a function to be called once every frame. it looks for inputs which have a non-null targetrayspace. inputs which have a value for this property represent inputs that project a target ray outward from the user. for each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rathe...
...r each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click. for tracked pointers, a function myrendertargetrayasbeam() is called to render a beam from the input controller's virtual position outward in the direction it's pointing. the code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateinputsources(session, frame, refspace) { for (let source of session.getinputsources()) { let targetraypose = frame.getpose(inputsource.targetrayspace, refspace); if (targetraypose) { ...
XRInputSource.targetRaySpace - Web APIs
tracked pointer inputs (targetraymode of tracked-pointer) is actually based upon the true spatial position and orientation of the input device. to determine the position and orientation of the target ray while rendering a frame, pass it into the xrframe method getpose() method, then use the returned xrpose object's transform to gather the spatial information you need. example this fragment of code shows part of a function to be called once every frame. it looks for inputs which have a non-null targetrayspace. inputs which have a value for this property represent inputs that project a target ray outward from the user. for each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rathe...
...r each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click. for tracked pointers, a function myrendertargetrayasbeam() is called to render a beam from the input controller's virtual position outward in the direction it's pointing. the code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateinputsources(session, frame, refspace) { for (let source of session.getinputsources()) { let targetraypose = frame.getpose(inputsource.targetrayspace, refspace); if (targetraypose) { ...
XRSession.onsqueeze - Web APIs
nput device. these actions represent the user squeezing or gripping an object or controller. to learn more about how to use and handle webxr controller inputs, see inputs and input sources. syntax xrsession.onsqueeze = squeezehandlerfunction; value a function to be invoked whenever the xrsession receives a squeeze event. examples handling squeeze events for a specific hand this snippet of code adds a simple handler for the squeeze event, which responds only to events on the user's off-hand (that is, the hand that isn't their dominant hand). this is determined by comparing the input source's handedness against the value of a handedness property on a user object we've established previously. xrsession.onsqueeze = event => { if (event.inputsource.handedness != user.handedness) { ha...
.... xrsession.onsqueeze = event => { if (event.inputsource.handedness != user.handedness) { handleoffhandsqueeze(event.inputsource, event.frame); } }; finishing an ongoing squeeze action this example exapnds somewhat on the previous example by demonstrating a way to implement the ability for the user to drop an object that was previously picked up by the user.. this is just a snippet of code, but should establish the general idea. after checking that the event occurred on the user's dominant hand, the pose's target ray is obtained. then we pass the currently held object and the target ray's transform matrix into a function we call dropobjectusingray() to drop the object, using the target ray to determine the surface upon which the object should be placed. this also clears the value ...
XRSession.onsqueezeend - Web APIs
action whether it was successfully completed or not. to learn more about how the sequence of squeeze events works, see primary squeeze actions in inputs and input sources. syntax xrsession.onsqueezeend = squeezeendhandlerfunction; value a function to be invoked whenever the xrsession receives a squeezestart event, indicating the ending of a primary squeeze action. examples this snippet of code adds a simple handler for the squeezeend event, which responds only to events on the user's dominant hand. in response to the end of the squeeze operation, this code looks to see if there is an object currently being held by the user by checking to see if the variable user.heldobject contains a reference to an object representing the held item. if heldobject has an object reference, that object ...
...ten to return the object to its original position. this takes care of the situation in which the drag is aborted or canceled. xrsession.onsqueezeend = event => { if (event.inputsource.handedness == user.handedness) { let targetraypose = event.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 ...
XRSession: selectend event - Web APIs
primary actions in inputs and input sources. examples the following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select. this snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose w...
...f which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pi...
XRSession: selectstart event - Web APIs
primary actions in inputs and input sources. examples the following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select. this snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose w...
...f which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to pi...
XRSession: squeezeend event - Web APIs
eze actions in inputs and input sources. examples the following example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. this snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was...
... of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to p...
XRSession: squeezestart event - Web APIs
eze actions in inputs and input sources. examples the following example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. this snippet is the core of an event handler to allow the user to grab objects in the scene and move them around. in this case, a single function is used to handle all three events, allowing them to share certain code that's the same regardless of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was...
... of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, determining which object to p...
XRSystem - Web APIs
Web › API › XRSystem
isn't supported. requestsession() returns a promise that resolves to a new xrsession with the specified xrsessionmode. events devicechange sent when the set of available xr devices has changed. also available using the ondevicechange event handler. usage notes thsi interface was previously known as simply xr in earlier versions of the specification; if you see references to xr in code or documentation, simply replace that with xrsystem. examples the following example shows how to use both issessionsupported() and requestsession(). if (navigator.xr) { immersivebutton.addeventlistener("click", onbuttonclicked); navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.disabled = false; } else { immers...
... immersivebutton.disabled = true; }); } function onbuttonclicked() { if (!xrsession) { navigator.xr.requestsession('immersive-vr') .then(() => { // onsessionstarted() not shown for reasons of brevity and clarity. onsessionstarted(xrsession); }); } else { // shut down the already running xrsession xrsession.end() .then(() => xrsession = null); } } this code starts by checking to see if webxr is available by looking for the navigator.xr property. if it's found, we know webxr is present, so we proceed by establishing a handler for the button which the user can click to toggle immersive vr mode on and off. however, we don't yet know if the desired immersive mode is available. to determine this, we call issessionsupported(), passing it the desired sess...
XRTargetRayMode - Web APIs
vice or hand-tracking system which the user points in the direction of the target. the target ray extends from the hand (or the object in the hand) in the targeted direction. the direction is determined using platform-specific rules, though if no such rules exist, the direction is chosen by assuming the user is pointing their index finger straight out from their hand. examples this fragment of code shows part of a function to be called once every frame. it looks for inputs which have a non-null targetrayspace. inputs which have a value for this property represent inputs that project a target ray outward from the user. for each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rathe...
...r each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click. for tracked pointers, a function myrendertargetrayasbeam() is called to render a beam from the input controller's virtual position outward in the direction it's pointing. the code should continue to perform tasks such as drawing controllers or any objects representative of the user's hands' positions in the virtual space, as well as any other input-related tasks. function updateinputsources(session, frame, refspace) { for (let source of session.getinputsources()) { let targetraypose = frame.getpose(inputsource.targetrayspace, refspace); if (targetraypose) { ...
XRViewerPose.views - Web APIs
e right eye's view a value of right. syntax let viewlist = xrviewerpose.views; value an array of xrview objects, one for each view available as part of the scene for the current viewer pose. this array's 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. 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. let pose = frame.getviewerpose(xrreferencespace); if (pose)...
...you can see more context and see much more on that page. specifications specification status comment webxr device apithe definition of 'xrviewerpose.views' in that specification. working draft initial definition. ...
XRViewerPose - Web APIs
rrect facing. the viewer's pose for the animation frame represented by xrframe can be obtained by calling the frame's getviewerpose() method, specifying the reference space in which the origin's position should be computed. the returned xrviewerpose tells you where the 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. 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. let pose = frame.getviewerpose(xrreferencespace); if (pose)...
...you can see more context and see much more on that page. specifications specification status comment webxr device apithe definition of 'xrviewerpose' in that specification. working draft initial definition. ...
Using the group role - Accessibility
s the focused control may be announced. screen magnifiers may enlarge the group. note: opinons may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: using the group role with a html tree view the snippet below shows how the group role is added directly into the html source code. <div id="tree1" role="tree" tabindex="-1"> <div id="animals" class="groupheader" role="presentation" aria-owns="animalgroup" aria-expanded="true"> <img role="presentation" tabindex="-1" src="images/treeexpanded.gif" /> <span role="treeitem" tabindex="0">animals</span> </div> <div id="animalgroup" role="group"> <div id="birds" role="treeitem"> <span tabindex="-1">birds</...
...v> <div id="catgroup" role="group"> <div id="siamese" role="treeitem"> <span tabindex="-1">siamese</span> </div> <div id="tabby" role="treeitem"> <span tabindex="-1">tabby</span> </div> </div> </div> </div> example 2: using the group role with a html drop-down menu the snippet below shows how the group role is added directly into the html source code. <div role="menu"> <ul role="group"> <li role="menuitem">inbox</li> <li role="menuitem">archive</li> <li role="menuitem">trash</li> </ul> <ul role="group"> <li role="menuitem">custom folder 1</li> <li role="menuitem">custom folder 2</li> <li role="menuitem">custom folder 3</li> </ul> <ul role="group"> <li role="menuitem">new folder</li> </ul> </div> work...
Using the slider role - Accessibility
100. the current volume is 50. the application will programmatically update the value of aria-valuenow in response to user input. <label for="fader">volume</label> <input type="range" id="fader" min="1" max="100" value="50" step="1" aria-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputupdate(value)"> <output for="fader" id="volume">50</output> the following code snippet allows you to return the output as it is updated by user input: function outputupdate(vol) { document.queryselector('#volume').value = vol; } example 2: text values sometimes, a slider is used to choose a value that is not, semantically, a number. in these cases, the aria-valuetext attribute is used to provide the appropriate text name for the currently selected value. in the exampl...
...e appropriate text name for the currently selected value. in the example below, the slider is used to select a day of the week. ...
ARIA: Region role - Accessibility
g aria. associated wai-aria roles, states, and properties aria-labelledby use this attribute to label the region. often, the value of the aria-labelledby attribute will be the id of the element used to title the section. keyboard interactions none. required javascript features none. examples <div role="region" aria-labelledby="region-heading"> <h2 id="region-heading">this heading's <code>id</code> attribute helps this region have an accessible name</h2> <!-- region content --> </div> accessibility concerns use sparingly! landmark roles are intended to be used sparingly, to identify larger overall sections of the document. using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. only use the region ...
...gion if it is given an accessible name. if at all possible, prefer using it instead. labeling landmarks if there is more than one region landmark role in a document, provide a label for each one. this label will allow an assitive technology user to be able to quickly understand the purpose of each landmark. <div role="region" aria-labelledby="heading"> <h3 id="use-discretion">please use the <code>region</code> role with discretion</h3> <!-- content --> </div> ... <div role="region" aria-labelledby="please-reconsider"> <h3 id="please-reconsider">please reconsider your document structure</h3> <!-- content --> </div> in this example, the region's label is being generated by the aria-labelledby attribute. scrolling content areas with overflow text if there is a content area with t...
ARIA: img role - Accessibility
the aria img role can be used to identify multiple elements inside page content that should be considered as a single image. these elements could be images, code snippets, text, emojis, or other content that can be combined to deliver information in a visual manner. <div role="img" aria-label="description of the overall image"> <img src="graphic1.png" alt=""> <img src="graphic2.png"> </div> description any set of content that should be consumed as a single image (which could include images, video, audio, code snippets, emojis, or other content) can be identified using role="img". you shouldn't count on the alt text of individual elements images for conveying context to assistive technologies; most screenreaders will consider the element with role="img" set on it to be to be like a bl...
...ontent it is not so obvious, and role="img" can come into play. for example, if you use emojis in your text, the meaning might be obvious to a sighted user, but someone using a screenreader might get confused because the emojis might have either no text representation at all, or the alternative text might be confusing and not match the context it is being used in. for example, take the following code: <div role="img" aria-label="that cat is so funny"> <p> &#x1f408; &#x1f602; </p> </div> &#x1f408; &#x1f602; are entity references for emojis read out as "cat" and "face with tears of joy", but this doesn't necessarily make sense — the implied meaning is possibly more like "that cat is so funny", so we include that in an aria-label along with role="img". this seems to work ok across s...
ARIA: tab role - Accessibility
x: 2; } [role="tabpanel"]:focus { border-color: orange; outline: 1px solid orange; } there are two things we need to do with javascript: we need to change focus and tab index of our tab elements with the right and left arrows, and we need to change the active tab and tabpanel when we click on a tab. to accomplish the first, we listen for the keydown event on the tablist. if the event's keycode is 39 for right arrow or 37 for the left arrow, we react to the event. we start by setting the tabindex of the current tab element to -1, making it no longer tabbable. then, if the right arrow is being pressed, we increase our tab focus counter by one. if the counter is greater than the number of tab elements we have, we circle back to the first tab by setting that counter to 0. if the left arrow...
... { const tabs = document.queryselectorall('[role="tab"]'); const tablist = document.queryselector('[role="tablist"]'); // add a click event handler to each tab tabs.foreach(tab => { tab.addeventlistener("click", changetabs); }); // enable arrow navigation between tabs in the tab list let tabfocus = 0; tablist.addeventlistener("keydown", e => { // move right if (e.keycode === 39 || e.keycode === 37) { tabs[tabfocus].setattribute("tabindex", -1); if (e.keycode === 39) { tabfocus++; // if we're at the end, go to the start if (tabfocus >= tabs.length) { tabfocus = 0; } // move left } else if (e.keycode === 37) { tabfocus--; // if we're at the start, move to the end if (tabfocu...
WAI-ARIA Roles - Accessibility
enables screen readers to use the browse mode reading cursor to both read and scroll through a stream of rich content that may continue scrolling infinitely by loading more content as the user reads.aria: figure rolethe aria figure role can be used to identify a figure inside page content where appropriate semantics do not already exist. a figure is generally considered to be one or more images, code snippets, or other content that puts across information in a different way to a regular flow of text.aria: form rolethe form landmark role can be used to identify a group of elements on a page that provide equivalent functionality to an html form.aria: grid rolethe grid role is for a widget that contains one or more rows of cells. the position of each cell is significant and can be focused using ...
...style grouping of information.aria: heading rolethe heading role defines this element as a heading to a page or section. to give the page more structure, a level should also be provided to indicate relationships between sections.aria: img rolethe aria img role can be used to identify multiple elements inside page content that should be considered as a single image. these elements could be images, code snippets, text, emojis, or other content that can be combined to deliver information in a visual manner.aria: list rolethe aria list role can be used to identify a list of items. it is normally used in conjunction with the listitem role, which is used to identify a list item contained inside the list.aria: listbox rolethe listbox role is used for lists from which a user may select one or more ite...
Web applications and ARIA FAQ - Accessibility
ttribute informs the browser that this element is actually a javascript-powered progress bar widget. the aria-valuemin and aria-valuemax attributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it. along with placing them directly in the markup, aria attributes can be added to the element and updated dynamically using javascript code like this: // find the progress bar <div> in the dom. var progressbar = document.getelementbyid("percent-loaded"); // set its aria roles and states, so that assistive technologies know what kind of widget it is. progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be called a...
...ogressbar" in cases where the <progressbar> tag isn't supported. here is an example of the markup used for an html5 progress bar: <!doctype html> <html> <head><title>gracefully degrading progress bar</title></head> <body> <progress id="progress-bar" value="0" max="100">0% complete</progress> <button id="update-button">update</button> </body> </html> ... and here is the javascript code that will ensure the progress bar still works in older browsers: var progressbar = document.getelementbyid("progress-bar"); // check to see if the browser supports the html5 <progress> tag. var supportshtml5progress = (typeof (htmlprogresselement) !== "undefined"); function setupprogress() { if (!supportshtml5progress) { // html5 <progress> isn't supported in this browser, so we need to ...
Accessibility documentation index - Accessibility
stream of rich content that may continue scrolling infinitely by loading more content as the user reads. 62 aria: figure role aria, aria role, aria figure, accessibility, reference, rôle, figure the aria figure role can be used to identify a figure inside page content where appropriate semantics do not already exist. a figure is generally considered to be one or more images, code snippets, or other content that puts across information in a different way to a regular flow of text. 63 aria: form role aria, aria role, aria figure, accessibility, reference, rôle, form the form landmark role can be used to identify a group of elements on a page that provide equivalent functionality to an html form. 64 aria: grid role aria, html the gr...
...ading to a page or section. to give the page more structure, a level should also be provided to indicate relationships between sections. 67 aria: img role aria, aria img, aria role, accessibility, reference, rôle, figure the aria img role can be used to identify multiple elements inside page content that should be considered as a single image. these elements could be images, code snippets, text, emojis, or other content that can be combined to deliver information in a visual manner. 68 aria: listbox role aria, accessibility, needscontent the listbox role is used for lists from which a user may select one or more items which are static and, unlike html <select> elements, may contain images. 69 aria: row role aria, aria role, aria row, ar...
Text labels and names - Accessibility
t accessibility, include a <figcaption> within a <figure> element, even though doing so is technically optional. the caption is in addition to any alternative text on images within the figure. the caption describes the purpose of the figure in the document, which may be different from a simple description of a visual item, as provided by the alternative text. example the following example shows code for a figure with a caption. the alt attribute of the <img> describes the appearance of the image; the <figcaption> describes it from a functional perspective (in this case, the latin name of the flower in the image). <figure> <img src="milkweed.jgp" alt="black and white close-up photo of milkweed flowers"> <figcaption>asclepias verticillata</figcaption> </figure> fieldset elements mu...
...e the same title in both places. example <iframe title="mdn web docs" width="300" height="200" src="https://developer.mozilla.org"> </iframe> use alt attribute to label mglyph elements when writing equations with mathml, give each <mglyph> element an alt attribute containing a name that describes the symbol. since mglyph elements are used for non-standard symbols without unicode definitions, screen readers won't automatically be able to name them. alternative text helps users of screen readers understand the symbol. headings must be labeled make sure that your headings have non-empty text content, and are not hidden, such as with css display:none or aria-hidden=true. users of screen readers rely on headings to understand the structure and content of a document. also, ...
:disabled - CSS: Cascading Style Sheets
Web › CSS › :disabled
background: #ccc; } syntax :disabled examples this example shows a basic shipping form. it uses the javascript change event to let the user enable/disable the billing fields. ...
...pe="text" placeholder="zip code"> </fieldset> <br> <fieldset id="billing"> <legend>billing address</legend> <label for="billing-checkbox">same as shipping address:</label> <input type="checkbox" id="billing-checkbox" checked> <br> <input type="text" placeholder="name" disabled> <input type="text" placeholder="address" disabled> <input type="text" placeholder="zip code" disabled> </fieldset> </form> css input[type="text"]:disabled { background: #ccc; } javascript // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').onchange = togglebilling; }, false); function togglebilling() { // select the billing text fields...
:lang() - CSS: Cascading Style Sheets
Web › CSS › :lang
selects any <p> in english (en) */ p:lang(en) { quotes: '\201c' '\201d' '\2018' '\2019'; } note: in html, the language is determined by a combination of the lang attribute, the <meta> element, and possibly by information from the protocol (such as http headers). for other document types there may be other document methods for determining the language. syntax formal syntax :lang( <language-code> ) parameter <language-code> a <string> representing the language you want to target. acceptable values are specified in the html spec. examples in this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. note that this doesn't illustrate the only way to do this, and that the best method to use depends on the type of document. al...
... <language-code> a <string> representing the language you want to target. acceptable values are specified in the html spec. examples in this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators. note that this doesn't illustrate the only way to do this, and that the best method to use depends on the type of document. also note that unicode values are used to specify some of the special quote characters. html <div lang="en"><q>this english quote has a <q>nested</q> quote inside.</q></div> <div lang="fr"><q>this french quote has a <q>nested</q> quote inside.</q></div> <div lang="de"><q>this german quote has a <q>nested</q> quote inside.</q></div> css :lang(en) > q { quotes: '\201c' '\201d' '\2018' '\2019'; } :lang(fr) > q { quot...
@charset - CSS: Cascading Style Sheets
Web › CSS › @charset
e the <style> element where the character set of the html page is relevant. @charset "utf-8"; this at-rule is useful when using non-ascii characters in some css properties, like content. as there are several ways to define the character encoding of a style sheet, the browser will try the following methods in the following order (and stop as soon as one yields a result) : the value of the unicode byte-order character placed at the beginning of the file. the value given by the charset attribute of the content-type: http header or the equivalent in the protocol used to serve the style sheet. the @charset css at-rule. use the character encoding defined by the referring document: the charset attribute of the <link> element. this method is obsoleted in html5 and must not be used. assume th...
...n the iana-registry, and must be double-quoted, following exactly one space character (u+0020), and immediately terminated with a semicolon. if several names are associated with an encoding, only the one marked with preferred must be used. ...
@media - CSS: Cascading Style Sheets
Web › CSS › @media
ed on the result of one or more media queries. with it, you specify a media query and a block of css to apply to the document if and only if the media query matches the device on which the content is being used. note: in javascript, the rules created using @media can be accessed with the cssmediarule css object model interface. ...
...block of css to apply to the document if and only if the media query matches the device on which the content is being used. note: in javascript, the rules created using @media can be accessed with the cssmediarule css object model interface. syntax the @media at-rule may be placed at the top level of your code or nested inside any other conditional group at-rule. /* at the top level of your code */ @media screen and (min-width: 900px) { article { padding: 1rem 3rem; } } /* nested within another conditional at-rule */ @supports (display: flex) { @media screen and (min-width: 900px) { article { display: flex; } } } for a discussion of media query syntax, please see using media queries. description media types media types describe the general category of a de...
Coordinate systems - CSS: Cascading Style Sheets
e a look at an example. this simple example creates a set of nested boxes. whenever the mouse enters, moves around inside, or exits the inner box, the corresponding event is handled by updating a set of informational messages within the box, listing out the current mouse coordinates in each of the four available coordinate systems. javascript let's look at the script in two sections. first, the code that logs the coordinates to the screen. this code will be called by the event handler for the various mouse events we watch. displaying the coordinates as we'll see in the html, the inner box (the one we're watching for events on) contains several paragraphs; one for each of the four coordinate systems we'll be reporting on. let inner = document.queryselector(".inner"); let log = document.que...
...offset"); setcoords(e, "client"); setcoords(e, "page"); setcoords(e, "screen"); } inner.addeventlistener("mouseenter", update, false); inner.addeventlistener("mousemove", update, false); inner.addeventlistener("mouseleave", update, false); the event handler is in the update() method. it simply calls setcoords() once for each coordinate system, passing in the event that occurred. our main code sets up the event handlers on the inner box by calling addeventlistener() for each of the types mouseenter, mousemove, and mouseleave. html the html for our example is below. note that within the <div> with the id "log", we have a paragraph for each coordinate system, with span used for each of the elements to receive and display the coordinates in each model. <div class="outer"> <div class=...
Box-shadow generator - CSS: Cascading Style Sheets
<div class="ui-slider-btn-set" data-topic="height" data-type="add"></div> <div class="ui-slider-input" data-topic="height" data-unit="px"></div> </div> </div> </div> <div id="output" class="category"> <div id="menu" class="menu"></div> <div class="title"> css code </div> <div class="group" style="border-top-left-radius: 0;"> <div class="output" data-topic="element" data-name="element" data-prop="width height background-color position=[relative] box-shadow"> </div> <div class="output" data-topic="before" data-name="element:before" data...
... #colorpicker [data-topic="hexa"] > input { width: 85px; padding: 2px 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* * ui components */ /* property */ .property { height: 20px; margin: 10px 0; } .property * { float: left; height: 100%; line-height: 100%; } /* slider */ #controls .ui-slider-name { margin: 0 10px 0 0; } /* * output code styling */ #output { position: relative; } #output .menu { max-width: 70%; height: 20px; position: absolute; top: 2px; } #output .button { width: 90px; height: 22px; margin: 0 5px 0 0; text-align: center; line-height: 20px; font-size: 14px; color: #fff; background-color: #999; border-top-left-radius: 3px; border-top-right-radius: 3px; bottom: -5px; float:left; } #output .but...
Using feature queries - CSS: Cascading Style Sheets
inside the feature query. let's walk through a very simple example where feature queries come in handy, which uses them in the way described above. let's say we want to create a layout of three boxes in a row, and ideally we would like to use css grid layout. however, we would like to have a layout for older browsers using floats. we can start by creating that floated layout with the following code, which gives us three columns. when browsers don't understand a css property or value, they ignore it. so we could start enhancing our layout by using css grid. browsers that do not support grid will ignore the grid value of the display property. once a floated item becomes a grid item, the float is removed — something you can read more about in supporting older browsers. therefore the grid ...
...to remove the width if display: grid is supported. this is exactly the situation feature queries solve. we can set the width back to auto if grid is supported. in the above scenario, it doesn't matter that ie11 doesn't support feature queries or css grid — it would get the floated version anyway, which is then overwritten by browsers that do support grid. an alternate way to write the above code is to wrap all of the grid code in a feature query as follows. this may mean you have a little more code but comes with the benefit of being able to test the fallback by misspelling the property or value name. you can try this in the live example above by changing display: grid in the @supports rule to display: grip or similar. summary feature queries can help you start to use newer features...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
t this feature of grid and other modern layout methods, learning a little about writing modes and logical vs. physical properties as we do so. logical and physical properties and values css is full of physical positioning keywords – left and right, top and bottom. if we position an item using absolute positioning, we use these physical keywords as offset values to push the item around. in the code snippet below, the item is placed 20 pixels from the top, and 30 pixels from the left of the container: .container { position: relative; } .item { position: absolute; top: 20px; left: 30px; } <div class="container"> <div class="item">item</div> </div> another place you might see physical keywords in use, is when using text-align: right to align text to the right. there are also phy...
...ight, however the direction of the text is vertical - inline text now runs down the page, from top to bottom. .wrapper > p { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; margin: 1em; color: #d9480f; max-width: 300px; } <div class="wrapper"> <p style="writing-mode: horizontal-tb">i have writing mode set to the default <code>horizontal-tb</code></p> <p style="writing-mode: vertical-rl">i have writing mode set to <code>vertical-rl</code></p> </div> writing modes in grid layouts if we now take a look at a grid layout example, we can see how changing the writing mode means changing our idea of where the block and inline axis are. the grid in my next example has three columns and two row tracks. this means there...
Grid template areas - CSS: Cascading Style Sheets
div> <div class="content">content</div> <div class="footer">footer</div> </div> using grid-template-areas for ui elements many of the grid examples you will find online make the assumption that you will use grid for main page layout, however grid can be just as useful for small elements as those larger ones. using grid-template-areas can be especially nice as it is easy to see in the code what your element looks like. as a very simple example we can create a “media object”. this is a component with space for an image or other media on one side and content on the other. the image might be displayed on the right or left of the box. our grid is a two-column track grid, with the column for the image sized at 1fr and the text 3fr. if you wanted a fixed width image area, then yo...
...orthand grid. grid-template the grid-template property sets the following properties: grid-template-rows grid-template-columns grid-template-areas the property is referred to as the explicit grid shorthand because it is setting those things that you control when you define an explicit grid, and not those which impact any implicit row or column tracks that might be created. the following code creates a layout using grid-template that is the same as the layout created earlier in this guide. .wrapper { display: grid; grid-template: "hd hd hd hd hd hd hd hd hd" minmax(100px, auto) "sd sd sd main main main main main main" minmax(100px, auto) "ft ft ft ft ft ft ft ft ft" minmax(100px, auto) / 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr ; ...
Layout using named grid lines - CSS: Cascading Style Sheets
e 1 to col-start 5</div> <div class="item2">i am placed from col-start line 7 spanning 3 lines</div> </div> if you take a look at this layout in the firefox grid highlighter you can see how the column lines are shown, and how our items are placed against these lines. the repeat syntax can also take a track list, it doesn’t just need to be a single track size that is being repeated. the code below would create an eight track grid, with a narrower 1fr width column named col1-start followed by a wider 3fr column named col2-start. .wrapper { grid-template-columns: repeat(4, [col1-start] 1fr [col2-start] 3fr); } if your repeating syntax puts two lines next to each other then they will be merged, and create the same result as giving a line multiple names in a non-repeating track defi...
...presentation of what your layout looks like, and it is then easy to move things around on the grid. if working with a strict multiple column layout for example the named lines demonstration in the last part of this guide works very well. if you consider grid systems such as those found in frameworks like foundation or bootstrap, these are based on a 12 column grid. the framework then imports the code to do all of the calculations to make sure that the columns add up to 100%. with grid layout the only code we need for our grid “framework” is: .wrapper { display: grid; grid-gap: 10px; grid-template-columns: repeat(12, [col-start] 1fr); } we can then use that framework to layout our page. for example, to create a three column layout with a header and footer, i might have the follow...
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
it should come as no surprise to know there is a shorthand. the grid-column-start and grid-column-end properties can be combined into grid-column, grid-row-start and grid-row-end into grid-row. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: rep...
... * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 100px); } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; backgrou...
Stacking context example 3 - CSS: Cascading Style Sheets
... level #3 level #2 (z-index: 1) ... level #2 (z-index: 1) level #1 ... level #1 this problem can be avoided by removing overlapping between different level menus, or by using individual (and different) z-index values assigned through the id selector instead of class selector, or by flattening the html hierarchy. ...
...ifferent level menus, or by using individual (and different) z-index values assigned through the id selector instead of class selector, or by flattening the html hierarchy. note: in the source code you will see that second-level and third level menus are made of several divs contained in an absolutely positioned container. this is useful to group and position all of them at once. ...
The stacking context - CSS: Cascading Style Sheets
which results in a rendering order of 4.1 div #6 - z-index is 3, stacked under an element with a z-index of 4, which results in a rendering order of 4.3 div #4 - z-index is 6, stacked under an element with a z-index of 4, which results in a rendering order of 4.6 div #1 - z-index is 5 example html <div id="div1"> <h1>division element #1</h1> <code>position: relative;<br/> z-index: 5;</code> </div> <div id="div2"> <h1>division element #2</h1> <code>position: relative;<br/> z-index: 2;</code> </div> <div id="div3"> <div id="div4"> <h1>division element #4</h1> <code>position: relative;<br/> z-index: 6;</code> </div> <h1>division element #3</h1> <code>position: absolute;<br/> z-index: 4;</code> <div id="div5...
...code> </div> <div id="div2"> <h1>division element #2</h1> <code>position: relative;<br/> z-index: 2;</code> </div> <div id="div3"> <div id="div4"> <h1>division element #4</h1> <code>position: relative;<br/> z-index: 6;</code> </div> <h1>division element #3</h1> <code>position: absolute;<br/> z-index: 4;</code> <div id="div5"> <h1>division element #5</h1> <code>position: relative;<br/> z-index: 1;</code> </div> <div id="div6"> <h1>division element #6</h1> <code>position: absolute;<br/> z-index: 3;</code> </div> </div> css * { margin: 0; } html { padding: 20px; font: 12px/20px arial, sans-serif; } div { opacity: 0.7; position: relative; } h1 { font: inherit; font-weight: bold; } #div1, #div2 { border: 1px dashed ...
all - CSS: Cascading Style Sheets
Web › CSS › all
the all shorthand css property resets all of an element's properties except unicode-bidi, direction, and css custom properties. it can set properties to their initial or inherited values, or to the values specified in another stylesheet origin. the source for this interactive example is stored in a github repository. if 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 /* global values */ all: initial; all: inherit; all: unset; /* css cascading and inheritance level 4 */ all: revert; the all property is specified as one of the css global keyword values. note that none of these values affect the unicode-bidi and direction properties. values initial specifies that all the element...
... were specified for the element. for purposes of revert, the author origin includes the override and animation origins. formal definition initial valuethere is no practical initial value for it.applies toall elementsinheritednocomputed valueas the specified value applies to each property this is a shorthand for.animation typeas each of the properties of the shorthand (all properties but unicode-bidi and direction) formal syntax initial | inherit | unset | revert examples html <blockquote id="quote"> lorem ipsum dolor sit amet, consectetur adipiscing elit. </blockquote> phasellus eget velit sagittis. css body { font-size: small; background-color: #f0f0f0; color: blue; } blockquote { background-color: skyblue; color: red; } result no all property <blockquote id="q...
<custom-ident> - CSS: Cascading Style Sheets
nt ambiguity. syntax the syntax of <custom-ident> is similar to css identifiers (such as property names), except that it is case-sensitive. it consists of one or more characters, where characters can be any of the following: any alphabetical character (a to z, or a to z), any decimal digit (0 to 9), a hyphen (-), an underscore (_), an escaped character (preceded by a backslash, \), a unicode character (in the format of a backslash, \, followed by one to six hexadecimal digits, representing its unicode code point) note that id1, id1, id1 and id1 are all different identifiers as they are case-sensitive. on the other hand, as there are several ways to escape a character, toto\? and toto\3f are the same identifiers. forbidden values a <custom-ident> must not be placed between single ...
...tial, and inherit), as well as the values will-change, auto, scroll-position, and contents. examples valid identifiers nono79 a mix of alphanumeric characters and numbers ground-level a mix of alphanumeric characters and a dash -test a dash followed by alphanumeric characters _internal an underscore followed by alphanumeric characters \22 toto a unicode character followed by a sequence of alphanumeric characters bili\.bob a correctly escaped period invalid identifiers 34rem it must not start with a decimal digit. -12rad it must not start with a dash followed by a decimal digit. bili.bob only alphanumeric characters, _, and - needn't be escaped. --toto it must not start with two dashes. this w...
<filter-function> - CSS: Cascading Style Sheets
<option>brightness</option> <option>contrast</option> <option>drop-shadow</option> <option>grayscale</option> <option>hue-rotate</option> <option>invert</option> <option>opacity</option> <option>saturate</option> <option>sepia</option> </select> </li> <li> <input type="range"><output></output> </li> <li> <p>current value: <code></code></p> </li> </ul> css div { width: 300px; height: 300px; background: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png) no-repeat center; } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } input { width: 60% } output { width: 5%; text-align: center; } select { ...
...ter; margin-bottom: 20px; } input { width: 60% } output { width: 5%; text-align: center; } select { width: 40%; margin-left: 2px; } javascript const selectelem = document.queryselector('select'); const divelem = document.queryselector('div'); const slider = document.queryselector('input'); const output = document.queryselector('output'); const curvalue = document.queryselector('p code'); selectelem.addeventlistener('change', () => { setslider(selectelem.value); setdiv(selectelem.value); }); slider.addeventlistener('input', () => { setdiv(selectelem.value); }); function setslider(filter) { if(filter === 'blur') { slider.value = 0; slider.min = 0; slider.max = 30; slider.step = 1; slider.setattribute('data-unit', 'px'); } else if(filter === 'brig...
gap (grid-gap) - CSS: Cascading Style Sheets
Web › CSS › gap
don't you think that's fun and exciting? i sure do! </p> css .content-box { column-count: 3; gap: 40px; } result specifications specification status comment css box alignment module level 3the definition of 'gap' in that specification. working draft initial definition ...
... don't you think that's fun and exciting? i sure do! </p> css .content-box { column-count: 3; gap: 40px; } result specifications specification status comment css box alignment module level 3the definition of 'gap' in that specification. working draft initial definition ...
ident - CSS: Cascading Style Sheets
Web › CSS › ident
n identifier. syntax the syntax of <custom-ident> is similar to css identifiers (such as property names), except that it is case-sensitive. it consists of one or more characters, where characters can be any of the following: any alphabetical character (a to z, or a to z), any decimal digit (0 to 9), a hyphen (-), an underscore (_), an escaped character (preceded by a backslash, \), a unicode character (in the format of a backslash, \, followed by one to six hexadecimal digits, representing its unicode code point) note that id1, id1, id1 and id1 are all different identifiers as they are case-sensitive. on the other hand, as there are several ways to escape a character, toto\? and toto\3f are the same identifiers. examples valid identifiers nono79 a mix of alphanumeric chara...
...ys to escape a character, toto\? and toto\3f are the same identifiers. examples valid identifiers nono79 a mix of alphanumeric characters and numbers ground-level a mix of alphanumeric characters and a dash -test a dash followed by alphanumeric characters --toto a custom-property like identifier _internal an underscore followed by alphanumeric characters \22 toto a unicode character followed by a sequence of alphanumeric characters bili\.bob a correctly escaped period invalid identifiers 34rem it must not start with a decimal digit. -12rad it must not start with a dash followed by a decimal digit. bili.bob only alphanumeric characters, _, and - needn't be escaped. 'bilibob' this would be a <string>. "bilibob" this would be a <string>. specifications ...
max-block-size - CSS: Cascading Style Sheets
es. everything else about the two boxes is identical, including the values used for max-block-size. html the html simply establishes the two <div> blocks that will be presented with their writing-mode set using the classes horizontal or vertical. both boxes share the standard-box class, which simply establishes coloring, padding, and their respective values of max-block-size. <p>writing mode <code>horizontal-tb</code> (the default):</p> <div class="standard-box horizontal"> call me ishmael. some years ago—never mind how long precisely—having little or no money in my purse, and nothing particular to interest me on shore, i thought i would sail about a little and see the watery part of the world. it is a way i have of driving off the spleen and regulating the circulation. <...
...he default):</p> <div class="standard-box horizontal"> call me ishmael. some years ago—never mind how long precisely—having little or no money in my purse, and nothing particular to interest me on shore, i thought i would sail about a little and see the watery part of the world. it is a way i have of driving off the spleen and regulating the circulation. </div> <p>writing mode <code>vertical-rl</code>:</p> <div class="standard-box vertical"> call me ishmael. some years ago—never mind how long precisely—having little or no money in my purse, and nothing particular to interest me on shore, i thought i would sail about a little and see the watery part of the world. it is a way i have of driving off the spleen and regulating the circulation. </div> css the cs...
offset-path - CSS: Cascading Style Sheets
svg the top and bottom halves of the scissors would appear in the top left of the canvas were they not positioned along the starting point of the motion path defined by offset-path. <svg xmlns="http://www.w3.or...
...ter | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]<box> = border-box | padding-box | content-box examples animating an element with offset-path the offset-path properties in the css code sample defines a motion path that is identical to the <path> element in the svg. the path, as can be seen in the rendering of the svg code, is a line drawing of a house with a chimney. svg the top and bottom halves of the scissors would appear in the top left of the canvas were they not positioned along the starting point of the motion path defined by offset-path. <svg xmlns="http://www.w3.org/2000/svg" width="700" height="450" viewbox="350 0 1400 900"> <title>house and scissors</title> <rect x="595" y...
overflow-inline - CSS: Cascading Style Sheets
definition initial valueautoapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto examples setting inline overflow behavior html <ul> <li><code>overflow-inline:hidden</code> — hides the text outside the box <div id="div1"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-inline:scroll</code> — always adds a scrollbar <div id="div2"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-inline:visible</code> — displays the text outsi...
...ijklmopqrstuvwxyz </div> </li> <li><code>overflow-inline:scroll</code> — always adds a scrollbar <div id="div2"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-inline:visible</code> — displays the text outside the box if needed <div id="div3"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-inline:auto</code> — on most browsers, equivalent to <code>scroll</code> <div id="div4"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> </ul> css #div1, #div2, #div3, #div4 { border: 1px solid black; width: 250px; margin-bottom: 12px; } #div1 { overflow-inline: hidden;} #div2 { overflow-inline: scroll;} #div3 { overflow-inline: visible;} #div...
overscroll-behavior-block - CSS: Cascading Style Sheets
inside the viewport, but its content is given a large height so it will also scroll vertically. by default, when the inner box is scrolled and a scroll boundary is reached, the whole page will begin to scroll, which is probably not what we want. to avoid this happening in the block direction, we've set overscroll-behavior-block: contain on the inner box. ...
...tent is given a large height so it will also scroll vertically. by default, when the inner box is scrolled and a scroll boundary is reached, the whole page will begin to scroll, which is probably not what we want. to avoid this happening in the block direction, we've set overscroll-behavior-block: contain on the inner box. ...
overscroll-behavior-inline - CSS: Cascading Style Sheets
ide the viewport, but its content is given a large width so it will also scroll horizontally. by default, when the inner box is scrolled and a scroll boundary is reached, the whole page will begin to scroll, which is probably not what we want. to avoid this happening in the inline direction, we've set overscroll-behavior-inline: contain on the inner box. ...
... is given a large width so it will also scroll horizontally. by default, when the inner box is scrolled and a scroll boundary is reached, the whole page will begin to scroll, which is probably not what we want. to avoid this happening in the inline direction, we've set overscroll-behavior-inline: contain on the inner box. ...
transform-style - CSS: Cascading Style Sheets
their parent, and you might not be able to see them at all, depending on the browser you are using. ...
... you might not be able to see them at all, depending on the browser you are using. ...
Adding captions and subtitles to HTML5 video - Developer guides
it are stable so we can use it today. video providers (such as the blender foundation) provide captions and subtitles in a text format with their videos, but they're usually in the subrip text (srt) format. these can be easily converted to webvtt using an online converter such as srt2vtt. modifications to the html and css this section summarises the modifications made to the previous article's code in order to facilitate the addition of subtitles to the video. if you are not interested in this, and just want to get straight into the javascript and more relevant css, skip to the subtitle implementation section. in this example we are using a different video, sintel, as it actually has some speech in it and therefore is better for illustrating how subtitles work! html markup as mentioned...
...first of all an option is added to allow the user to switch all subtitles off, and then buttons are added for each text track, reading the language and label from each one. the creation of each list item and button is done by the createmenuitem() function, which is defined as follows: var subtitle...
Rich-Text Editing in Mozilla - Developer guides
table region. most commands affect the document's selection (bold, italics, etc), while others insert new elements (adding a link) or affect an entire line (indenting). when using contenteditable, calling execcommand will affect the currently active editable element. internet explorer differences one major difference between mozilla and internet explorer that affects designmode is the generated code in the editable document: while internet explorer uses html tags (em, i, etc), mozilla 1.3 will generate by default spans with inline style rules. the stylewithcss command can be used to toggle between css and html markup creation. figure 1 : generated html differences mozilla: <span style="font-weight: bold;">i love geckos.</span> <span style="font-weight: bold; font-style: italic; text-d...
...the function executed the requested command using execcommand() and then sets focus back to the editable document, as clicking on a button will set focus on the button itself, which breaks the editing flow. figure 4 : executing rich editing commands html: <button onclick="doricheditcommand('bold')" style="font-weight:bold;">b</button> javascript: function doricheditcommand(aname, aarg){...
Using HTML sections and outlines - Developer guides
e javascript disabled that your page relies on javascript: <noscript> <p><strong>this web page requires javascript to be enabled.</strong></p> <p>javascript is an object-oriented computer programming language commonly used to create interactive effects within web browsers.</p> <p><a href="https://goo.gl/koeeaj">how to enable javascript?</a></p> </noscript> this leads to the following code to allow the support of the html5 sections and headings elements in non-html5 browsers, even for internet explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting: <!--[if lt ie 9]> <script> document.createelement("article"); document.createelement("aside"); document.createelement("footer"); document.createelement(...
...this isn't a really bad thing neccessarily — sites will often have a few validation errors — but it's something to be aware of still. conclusion the new semantic elements introduced in html5 bring the ability to describe the structure of a web document in a standard way. they bring a big advantage for people having html5 browsers and nee...
A hybrid approach - Developer guides
ion. but even if it does not work, it is no worse with respect to performance than only using fluid images. by combining the techniques listed above, we can get a mobile web development strategy that is both more flexible than pure separate sites and has better performance than pure responsive design. the bad one downside of mixing approaches is that it can lead to an increase in the number of code paths, both on the client and server side. this can make it more time-consuming to develop than other approaches. with proper planning, though, the code can still be organized in a maintainable way. another downside is that because this approach relies on responsive design, it typically works best on a new project or one that has an existing flexible layout, not as a retrofit. similarly, because ...
...xtend comfortably to tablets as well. examples for mozilla's web o’ wonder demo site, we tried out a basic version of the hybrid approach, with positive results. we used some elements of responsive web design to give the site a mobile layout, along with user-agent detection to provide mobile-friendly videos and to re-order the demos if the user is on a phone. feel free to check out the source code on github. we could also be doing more development involving this approach very soon! in fact, one potential path for the main mozilla site is roughly outlined in the “the good” section above: using user-agent detection, route visitors to a landing page for the firefox version for their device. every page on the site should look great at a wide variety of resolutions, being built with re...
Mobile Web Development - Developer guides
Web › Guide › Mobile
ce screen size and resolution. you do this in css by querying for screen height, width, and pixel ratio. you can also make use of css properties to implement visual effects like gradients and shadows without images. mobile apis finally, you can take advantage of the new possibilities offered by mobile devices, such as orientation and geolocation. cross-browser development write cross-browser code to create web sites that will work acceptably across different mobile browsers: try to avoid using browser-specific features, such as vendor-prefixed css properties. if you do need to use these features, check whether other browsers implement their own versions of these features, and target them too. for browsers that don't support these features, provide an acceptable fallback. for examp...
...do that, at least make sure that the default background contrasts with the text: that way, the page will at least be usable in a browser which is not targeted by your linear-gradient rule. see this list of gecko-specific properties, and this list of webkit-specific properties, and peter beverloo's table of vendor-specific properties. using tools like css lint can help find problems like this in code, and preprocessors like sass and less can help you to produce cross-browser code. take care with user agent sniffing it's preferable for web sites to detect specific device features such as screen size and touch screens using the techniques listed above, and adapt themselves accordingly. but sometimes this is impractical, and web sites resort to parsing the browser's user agent string to try to...
Printing - Developer guides
.onbeforeprint and window.onafterprint to assign handlers for these events, but using eventtarget.addeventlistener() is preferred. examples here are some common examples. ...
...open('', 'mywindow', 'status=1,width=350,height=150'); my_window.document.write('<html><head><title>print me</title></head>'); my_window.document.write('<body onafterprint="self.close()">'); my_window.document.write('<p>when you print this window, it will close afterward.</p>'); my_window.document.write('</body></html>'); } </script> </head> <body> <p>to try out the <code>afterprint</code> event, click the link below to open the window to print. you can also try changing the code to use <code>beforeprint</code> to see the difference.</p> <p><a href="javascript: popuponclick()">open popup window</a></p> </body> </html> view live examples print an external page without opening it if you want to be able to print an external page without opening it, you can ...
User input and controls - Developer guides
er, pointerout, etc. note: pointer events are not widely supported yet, but a pointer.js polyfill is available on mozilla github. implement controls pointer lock in some cases, typically game development, you might need to access mouse events even when the cursor goes past the boundary of the browser or screen: the pointer_lock_api gives you full control of the pointing device. this is the code to request pointer lock on an element: element.requestpointerlock(); note: for a full tutorial and reference, read our pointer_lock_api page. screen orientation when screen orientation matters for your application, you can read the screen orientation state, be informed when this state changes, and able to lock the screen orientation to a specific state (usually portrait or landscape) throug...
...mation about the screen orientation api can be found in managing screen orientation. fullscreen you might need to present an element of your application (such as a <video>, for example) in fullscreen mode. you can achieve this by calling element.requestfullscreen() on that element. ...
Developer guides
application faster and more responsive to user actions. graphics on the web modern web sites and applications often need to present graphics of varying sophistication. guide to web apis a list of all web apis and what they do. javascript javascript is the powerful scripting language used to create applications for the web. localizations and character encodings browsers process text as unicode internally. however, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. the html specification recommends the use of the utf-8 encoding (which can represent all of unicode), and regardless of the encoding used requires web content to declare that encoding. mobile web development this article provides an overview...
...content work quickly and efficiently. this lets it perform effectively for both powerful desktop systems and weaker handheld devices. parsing and serializing xml the web platform provides different methods of parsing and serializing xml, each with its pros and cons. the web open font format (woff) woff (web open font format) is a font file format that is free for anyone to use on the web. unicode bidirectional text algorithm (bidi) the unicode® bidi algorithm is part of the unicode text standard. it describes how the browser should order characters while rendering unicode text. this guide covers the algorithm in general and how it applies to content you create—especially when you build properly localized and internationalized content. using formdata objects the formdata object lets ...
HTML attribute: maxlength - HTML: Hypertext Markup Language
constraint validation is only applied when the value is changed by the user. ...
...o an <input> or <textarea>. this must be an integer value 0 or higher. if no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length. any maxlength value must be greater than or equal to the value of minlength, if present and valid. the input will fail constraint validation if the length of the text value of the field is greater than maxlength utf-16 code units long. constraint validation is only applied when the value is changed by the user. constraint validation while the browser will generally prevent user from entering more text than the maxlength attribute allows, should the length be longer than the maxlength allows, the read-only toolong property of a validitystate object will be true. examples <input type="password" maxlength="4"/> ...
HTML attribute: minlength - HTML: Hypertext Markup Language
constraint validation is only applied when the value is changed by the user. ...
...st be an integer value 0 or higher. if no minlength is specified, or an invalid value is specified, the input has no minimum length. this value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria. the input will fail constraint validation if the length of the text value of the field is less than minlength utf-16 code units long, with validitystate.tooshort returning true. constraint validation is only applied when the value is changed by the user. once submission fails, some browsers will display an error message indicating the minimum length required and the current length. examples by adding minlength="5", the value must either be empty or five characters or longer to be valid. <label for="fruit">enter a...
HTML attribute: pattern - HTML: Hypertext Markup Language
he pattern attribute, when specified, is a regular expression which the input's value must match in order for the value to pass constraint validation. it must be a valid javascript regular expression, as used by the regexp type, and as documented in our guide on regular expressions; the 'u' flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of unicode code points, instead of as ascii. no forward slashes should be specified around the pattern text. if the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored. tip: use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. you should also include othe...
...rom javascript regular expressions: in the case of pattern attribute, we are matching against the entire value, not just any subset, as if a ^(?: were implied at the start of the pattern and )$ at the end. ...
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
esult in an error, but using only one is seen as a best practice. it makes logical sense — <h1> is the most important heading, and tells you what the purpose of the overall page is. you wouldn't have a book with more than one title, or a movie with more than one name! having a single top-level title is also arguably better for screenreader users, and seo. examples all headings the following code shows all the heading levels, in use. <h1>heading level 1</h1> <h2>heading level 2</h2> <h3>heading level 3</h3> <h4>heading level 4</h4> <h5>heading level 5</h5> <h6>heading level 6</h6> here is the result of this code: example page the following code shows a few headings with some content under them. <h1>heading elements</h1> <h2>summary</h2> <p>some text here...</p> <h2>examples</h2> ...
...because of this, it is important to not skip one or more heading levels. ...
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
Web › HTML › Element › applet
ttop. alt this attribute causes a descriptive text alternate to be displayed on browsers that do not support java. page designers should also remember that content enclosed within the <applet> element may also be rendered as alternative text. archive this attribute refers to an archived or compressed version of the applet and its associated class files, which might help reduce download time. code this attribute specifies the url of the applet's class file to be loaded and executed. applet filenames are identified by a .class filename extension. the url specified by code might be relative to the codebase attribute. codebase this attribute gives the absolute or relative url of the directory where applets' .class files referenced by the code attribute are stored. datafld this attribute,...
... as defined for internet explorer 4 and higher, this attribute specifies a url for an associated file for the applet. the meaning and use is unclear and not part of the html standard. vspace this attribute specifies additional vertical space, in pixels, to be reserved above and below the applet. width this attribute specifies in pixels the width that the applet needs. example html <applet code="game.class" align="left" archive="game.zip" height="250" width="350"> <param name="difficulty" value="easy"> <b>sorry, you need java to play this game.</b> </applet> specifications specification status comment html 5.2the definition of '<applet>' in that specification. recommendation html 5.1the definition of '<applet>' in that specification. ...
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
Web › HTML › Element › bdi
to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. bidirectional text is text that may contain both sequences of characters that are arranged left-to-right (ltr) and sequences of characters that are arranged right-to-left (rtl), such as an arabic quotation embedded in an english string. browsers implement the unicode bidirectional algorithm to handle this. in this algorithm, characters are given an implicit directionality: for example, latin characters are treated as ltr while arabic characters are treated as rtl. some other characters (such as spaces and some punctuation) are treated as neutral and are assigned directionality based on that of their surrounding characters. usually, the bidirectional algorith...
...em by wrapping embedded-text in a <span> with the dir attribute set to the known directionality. but if you don't know the directionality - for example, because embedded-text is being read from a database or entered by the user - you should use <bdi> to prevent the directionality of embedded-text from affecting its surroundings. though the same visual effect can be achieved using the css rule unicode-bidi: isolate on a <span> or another text-formatting element, html authors should not use this approach because it is not semantic and browsers are allowed to ignore css styling. embedding the characters in <span dir="auto"> has the same effect as using <bdi>, but its semantics are less clear. content categories flow content, phrasing content, palpable content. permitted co...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
Web › HTML › Element › canvas
6,384 x 16,384) firefox 32,767 pixels 32,767 pixels 472,907,776 pixels (i.e., 22,528 x 20,992) safari 32,767 pixels 32,767 pixels 268,435,456 pixels (i.e., 16,384 x 16,384) ie 8,192 pixels 8,192 pixels ? note: exceeding the maximum dimensions or area renders the canvas unusable — drawing commands will not work. ...
...ions or area renders the canvas unusable — drawing commands will not work. examples html this code snippet adds a canvas element to your html document. a fallback text is provided if a browser is unable to render the canvas, or if can't read a canvas. <canvas width="300" height="300"> an alternative text describing what your canvas displays. ...
<col> - HTML: Hypertext Markup Language
Web › HTML › Element › col
htmltablecolelement attributes this element includes the global attributes. span this attribute contains a positive integer indicating the number of consecutive columns the <col> element spans. if not present, its default value is 1. deprecated attributes the following attributes are deprecated and should not be used. they are documented below for reference when updating existing code and for historical interest only. align this enumerated attribute specifies how horizontal alignment of each column cell content will be handled. possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting spaces into the textual content so that the content...
...t a to zero and b to the position of the column in the table, e.g. td:nth-child(2) { text-align: right; } to right-align the second column. if the table does use a colspan attribute, the effect can be achieved by combining adequate css attribute selectors like [colspan=n], though this is not trivial. bgcolor the background color of the table. it is a 6-digit hexadecimal rgb code, prefixed by a '#'. one of the predefined color kewords can also be used. to achieve a similar effect, use the css background-color property. char this attribute is used to set the character to align the cells in a column on. typical values for this include a period (.) when attempting to align numbers or monetary values. if align is not set to char, this attribute is ignored. charoff ...
<colgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › colgroup
lumn group, it has no effect on the css styling rules associated with it or, even more, to the cells of the column's members of the group. the span attribute is not permitted if there are one or more <col> elements within the <colgroup>. deprecated attributes the following attributes are deprecated and should not be used. they are documented below for reference when updating existing code and for historical interest only. align this enumerated attribute specifies how horizontal alignment of each column cell content will be handled. possible values are: left, aligning the content to the left of the cell center, centering the content in the cell right, aligning the content to the right of the cell justify, inserting spaces into the textual content so that the content...
...of the columns in the table and b is the ordinal position of this column in the table. only after this selector the text-align property can be used. if the table does use a colspan attribute, the effect can be achieved by combining adequate css attribute selectors like [colspan=n], though this is not trivial. bgcolor the background color of the table. it is a 6-digit hexadecimal rgb code, prefixed by a '#'. one of the predefined color kewords can also be used. to achieve a similar effect, use the css background-color property. char this attribute specifies the alignment of the content in a column group to a character. typical values for this include a period (.) when attempting to align numbers or monetary values. if align is not set to char, this attribute is ignored, th...
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › content
point, and wasn't meant to be used in ordinary html. it has now been replaced by the <slot> element, which creates a point in the dom at which a shadow dom can be inserted. note: though present in early draft of the specifications and implemented in several browsers, this element has been removed in later versions of the spec, and should not be used. it is documented here to assist in adapting code written during the time it was included in the spec to work with newer versions of the specification. content categories transparent content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parent elements any element that accepts flow content. dom interface htmlcontentelemen...
... dom interface htmlcontentelement attributes this element includes the global attributes. select a comma-separated list of selectors. these have the same syntax as css selectors. they select the content to insert in place of the <content> element. example here is a simple example of using the <content> element. it is an html file with everything needed in it. note: for this code to work, the browser you display it in must support web components. see enabling web components in firefox. <html> <head></head> <body> <!-- the original content accessed by <content> --> <div> <h4>my content heading</h4> <p>my content text</p> </div> <script> // get the <div> above. var mycontent = document.queryselector('div'); // create a shadow dom on the <div> ...
<dfn>: The Definition element - HTML: Hypertext Markup Language
Web › HTML › Element › dfn
</p> <p>negare non possum. dat enim intervalla et relaxat. quonam modo? equidem e cn. quid de pythagora? in schola desinis. </p> <p>ubi ut eam caperet aut quando? cur iustitia laudatur? aperiendum est igitur, quid sit voluptas; quid enim? non est igitur voluptas bonum. urgent tamen et nihil remittunt. quid enim possumus hoc agere divinius? </p> <p>because of all of that, we decided to use the <code><a href="#definition-dfn">&lt;dfn&gt;</a></code> element for this project.</p> here we see the definition — now with an id attribute, "definition-dfn", which can be used as the target of a link. later on, a link is created using <a> with the href attribute set to "#definition-dfn" to set up the link back to the definition. result the resulting content looks like this: using abbreviations ...
...lescope">hst</abbr> has arguably done more to advance science than any device ever built.</p> note the <abbr> element nested inside the <dfn>. the former establishes that the term is an abbreviation ("hst") and specifies the full term ("hubble space telescope") in its title attribute. the latter indicates that the abbreviated term represents a term being defined. result the output of the above code looks like this: specifications specification status comment html living standardthe definition of '<dfn>' in that specification. living standard html5the definition of '<dfn>' in that specification. recommendation html 4.01 specificationthe definition of '<dfn>' in that specification. recommendation ...
<input type="hidden"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › hidden
type hidden let web developers include data that cannot be seen or modified by users when a form is submitted. for example, the id of the content that is currently being ordered or edited, or a unique security token. hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page's content. note: there is a live example below the following line of code — if it is working correctly, you should see nothing! <input id="prodid" name="prodid" type="hidden" value="xm234jq"> value a domstring representing the value of the hidden data you want to pass back to the server. events none. supported common attributes autocomplete idl attributes value methods none. note: the input an...
...e of the hidden input with the id "postid" to the id of the post in its database before sending the form to the user's browser and would use that information when the form is returned to know which database record to update with modified information. no scripting is needed in the content to handle this. the output looks like this: note: you can also find the example on github (see the source code, and also see it running live). when submitted, the form data sent to the server will look something like this: title=my+excellent+blog+post&content=this+is+the+content+of+my+excellent+blog+post.+i+hope+you+enjoy+it!&postid=34657 even though the hidden input cannot be seen at all, its data is still submitted. specifications specification status comment html livin...
<input type="radio"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › radio
any radio groups on a page as you like, as long as each has its own unique name. for example, if your form needs to ask the user for their preferred contact method, you might create three radio buttons, each with the name property set to contact but one with the value email, one with the value phone, and one with the value mail. the user never sees the value or the name (unless you expressly add code to display it). the resulting html looks like this: <form> <p>please select your preferred contact method:</p> <div> <input type="radio" id="contactchoice1" name="contact" value="email"> <label for="contactchoice1">email</label> <input type="radio" id="contactchoice2" name="contact" value="phone"> <label for="contactchoice2">phone</label> <input type="radio" ...
...ted when the form is submitted, the radio group is not included in the submitted form data at all, since there is no value to report. it's fairly uncommon to actually want to allow the form to be submitted without any of the radio buttons in a group selected, so it is usually wise to have one default to the checked state. see selecting a radio button by default below. let's add a little bit of code to our example so we can examine the data generated by this form. the html is revised to add a <pre> block to output the form data into: <form> <p>please select your preferred contact method:</p> <div> <input type="radio" id="contactchoice1" name="contact" value="email"> <label for="contactchoice1">email</label> <input type="radio" id="contactchoice2" name="...
<keygen> - HTML: Hypertext Markup Language
Web › HTML › Element › keygen
or rsa keys, the keyparams parameter is not used (ignored if present). the user may be given a choice of rsa key strengths. currently, the user is given a choice between "high" strength (2048 bits) and "medium" strength (1024 bits). for dsa keys, the keyparams parameter specifies the dsa pqg parameters which are to be used in the keygen process. the value of the pqg parameter is the the base64 encoded, der encoded dss-parms as specified in ietf rfc 3279. the user may be given a choice of dsa key sizes, allowing the user to choose one of the sizes defined in the dsa standard. for ec keys, the keyparams parameter specifies the name of the elliptic curve on which the key will be generated. it is normally a string from the table in nskeygenhandler.cpp. (note that only a subset of the curves name...
...selected size is generated. the private key is encrypted and stored in the local key database. publickeyandchallenge ::= sequence { spki subjectpublickeyinfo, challenge ia5string } signedpublickeyandchallenge ::= sequence { publickeyandchallenge publickeyandchallenge, signaturealgorithm algorithmidentifier, signature bit string } the public key and challenge string are der encoded as publickeyandchallenge, and then digitally signed with the private key to produce a signedpublickeyandchallenge. the signedpublickeyandchallenge is base64 encoded, and the ascii data is finally submitted to the server as the value of a form name/value pair, where the name is name as specified by the name attribute of the keygen element. if no challenge string is provided, then it will be encod...
<listing> - HTML: Hypertext Markup Language
Web › HTML › Element › listing
ouldn't be broken when not greater than 132 characters. note: do not use this element. it is deprecated since html 3.2 and was neither implemented by all browsers, nor in a consistent way. even more it is obsoleted in html5 and may be rendered by conforming user-agents as the <pre> element, which will interpret the internal html! instead use the <pre> element or if semantically adequate the <code> element, eventually escaping the html '<' and '>' so that they don't get interpreted. a monospaced font can also be obtained on a simple <div> element, by applying an adequate css style using monospace as the generic-font value in a font-family property. attributes this element has no other attributes than the global attributes, common to all elements. dom interface this element implement...
... the <plaintext> and <xmp> elements, similar to <listing> but also obsolete. ...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
e text within is rendered in a different direction. <br> the html <br> element produces a line break in text (carriage-return). it is useful for writing a poem or an address, where the division of lines is significant. <cite> the html citation element (<cite>) is used to describe a reference to a cited creative work, and must include the title of that work. <code> the html <code> element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code. <data> the html <data> element links a given piece of content with a machine-readable translation. if the content is time- or date-related, the <time> element must be used. <dfn> the html definition element (<dfn>) is used to in...
...<canvas> use the html <canvas> element with either the canvas scripting api or the webgl api to draw graphics and animations. <noscript> the html <noscript> element defines a section of html to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. <script> the html <script> element is used to embed executable code or data; this is typically used to embed or refer to javascript code. demarcating edits these elements let you provide indications that specific parts of the text have been altered. element description <del> the html <del> element represents a range of text that has been deleted from a document. <ins> the html <ins> element represents a range...
Evolution of HTTP - HTTP
he url as both the protocol, server, and port are unnecessary once connected to the server). get /mypage.html the response is extremely simple too: it only consisted of the file itself. <html> a very simple html page </html> unlike subsequent evolutions, there were no http headers, meaning that only html files could be transmitted, but no other type of documents. ...
... status or error codes: in case of a problem, a specific html file was send back with the description of the problem contained in it, for human consumption. ...
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
nd all its subdomains (it doesn't have to be the same domain that the csp is set on.) content-security-policy: default-src 'self' *.trusted.com example 3 a web site administrator wants to allow users of a web application to include images from any origin in their own content, but to restrict audio or video media to trusted providers, and all scripts only to a specific server that hosts trusted code. content-security-policy: default-src 'self'; img-src *; media-src media1.com media2.com; script-src userscripts.example.com here, by default, content is only permitted from the document's origin, with the following exceptions: images may load from anywhere (note the "*" wildcard). media is only allowed from media1.com and media2.com (and not from subdomains of those sites). executable scr...
...t in which the violation occurred. effective-directive the directive whose enforcement caused the violation. original-policy the original policy as specified by the content-security-policy http header. referrer the referrer of the document in which the violation occurred. script-sample the first 40 characters of the inline script, event handler, or style that caused the violation. status-code the http status code of the resource on which the global object was instantiated. violated-directive the name of the policy section that was violated. sample violation report let's consider a page located at http://example.com/signup.html. it uses the following policy, disallowing everything but stylesheets from cdn.example.com. content-security-policy: default-src 'none'; style-src cdn.e...
Configuring servers for Ogg media - HTTP
e browser will treat it as a video file. most servers don't by default serve ogg media with the correct mime types, so you'll likely need to add the appropriate configuration for this. for apache, you can add the following to your configuration: addtype audio/ogg .oga addtype video/ogg .ogv addtype application/ogg .ogg you can find specific information about possible media file types and the codecs used within them in our comprehensive guide to media types and formats on the web. in particular, the article on media container formats will be especially helpful when configuring serers to host media properly. handle http 1.1 byte range requests correctly in order to support seeking and playing back regions of the media that aren't yet downloaded, gecko uses http 1.1 byte-range requests to ...
... return 206: partial content to all byte range requests; otherwise, browsers can't be sure you actually support byte range requests. your server must also return 206: partial content for the request range: bytes=0- as well. include regular key frames when the browser seeks through ogg media to a specified time, it has to seek to the nearest key frame before the seek target, then download and decode the video from there until the requested target time. the farther apart your key frames are, the longer this takes, so it's helpful to include key frames at regular intervals. by default, ffmpeg2theora uses one key frame every 64 frames (or about every 2 seconds at 30 frames per second), which works pretty well. note: of course, the more key frames you use, the larger your video file is, so you...
Cache-Control - HTTP
cache-control directives are not part of the core http caching standards document. check the compatibility table for their support; user-agents that don't recognize them should ignore them. cache-control: immutable cache-control: stale-while-revalidate=<seconds> cache-control: stale-if-error=<seconds> directives cacheability a response is normally cached by the browser if: it has a status code of 301, 302, 307, 308, or 410 and cache-control does not have no-store, or if proxy, does not have private and authorization is unset either has a status code of 301, 302, 307, 308, or 410 or has public, max-age or s-maxage in cache-control or has expires set public the response may be stored by any cache, even if the response is normally non-cacheable. private the resp...
...e response body, content-encoding, content-range, or content-type. it therefore forbids a proxy or browser feature, such as google’s web light, from converting images to minimize data for a cache store or slow connection. only-if-cached set by the client to indicate "do not use the network" for the response. the cache should either respond using a stored response, or respond with a 504 status code. conditional headers such as if-none-match should not be set. there is no effect if only-if-cached is set by a server as part of a response. examples preventing caching to disable caching of a resource, you can send the following response header: good: cache-control: no-store bad: cache-control: private,no-cache,no-store,max-age=0,must-revalidate,pre-check=0,post-check=0 cachi...
CSP: child-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inl...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header:...
CSP: connect-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header...
CSP: font-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inl...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header:...
CSP: frame-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inl...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header:...
CSP: manifest-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inl...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header:...
CSP: media-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inl...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header:...
CSP: object-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inl...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header:...
CSP: report-uri - HTTP
g_file = dirname(__file__) . '/csp-violations.log'; $log_file_size_limit = 1000000; // bytes - once exceeded no further entries are added $email_address = 'admin@example.com'; $email_subject = 'content-security-policy violation'; // end configuration $current_domain = preg_replace('/www\./i', '', $_server['server_name']); $email_subject = $email_subject . ' on ' . ...
...e.com'; $email_subject = 'content-security-policy violation'; // end configuration $current_domain = preg_replace('/www\./i', '', $_server['server_name']); $email_subject = $email_subject . ' on ' . $current_domain; http_response_code(204); // http 204 no content $json_data = file_get_contents('php://input'); // we pretty print the json before adding it to the log file if ($json_data = json_decode($json_data)) { $json_data = json_encode($json_data, json_pretty_print | json_unescaped_slashes); if (!file_exists($log_file)) { // send an email $message = "the following content-security-policy violation occurred on " . $current_domain . ":\n\n" . $json_data . "\n\nfurther cps violations will be logged to the following log file, but no further email notifications w...
CSP: require-sri-for - HTTP
script requires sri for scripts. style requires sri for style sheets. script style requires sri for both, scripts and style sheets. ...
...content-security-policy: require-sri-for script style <script> elements like the following will be loaded as they use a valid integrity attribute. ...
CSP: style-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows enabling specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method than using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inline even...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header...
CSP: worker-src - HTTP
elf' refers to the origin from which the protected document is being served, including the same url scheme and port number. you must include the single quotes. some browsers specifically exclude blob and filesystem from source directives. sites needing to allow these content types can specify them using the data attribute. 'unsafe-eval' allows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' allows to enable specific inline event handlers. if you only need to allow inline event handlers and not inline <script> elements or javascript: urls, this is a safer method compared to using the unsafe-inline expression. 'unsafe-inline' allows the use of inline resources, such as inline <script> elements, javascript: urls, inl...
...al. see unsafe inline script for an example. specifying nonce makes a modern browser ignore 'unsafe-inline' which could still be set for older browsers without nonce support. '<hash-algorithm>-<base64-value>' a sha256, sha384 or sha512 hash of scripts or styles. the use of this source consists of two portions separated by a dash: the encryption algorithm used to create the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0 this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. examples violation cases given this csp header:...
Firefox user agent string reference - HTTP
vant. avoid inferring materials based on these. the preferred way to target content to a device form factor is to use css media queries. however, if you use ua sniffing to target content to a device form factor, please look for mobi (to include opera mobile, which uses "mobi") for the phone form factor and do not assume any correlation between "android" and the device form factor. this way, your code will work if/when firefox ships on other phone/tablet operating systems or android is used for laptops. also, please use touch detection to find touch devices rather than looking for "mobi" or "tablet", since there may be touch devices which are not tablets. firefox os devices identify themselves without any operating system indication; for example: "mozilla/5.0 (mobile; rv:15.0) gecko/15.0 fire...
... (mobile; nnnn; rv:26.0) gecko/26.0 firefox/26.0 device-specific user agent strings although it is strongly discouraged by mozilla, some handset manufacturers unfortunately include a token in their device's ua string that represents their device id. if this is the case, the firefox os ua string will look like the device-specific string in the table above, where nnnn; is the manufacturer's code for the device (see guidelines). some of them we have noticed are of the form "nexusone;", "zteopen;", or "open c;" (note that putting space is also discouraged). we provide this information to assist with your ua detection logic, but mozilla discourages the detection of a device id in ua strings. here is a javascript regular expression that will detect all mobile devices, including devices with...
PATCH - HTTP
Web › HTTP › Methods › PATCH
a 200 response could have contained a payload body. http/1.1 204 no content content-location: /file.txt etag: "e0023aa4f" specifications specification title rfc 5789: patch patch method for http ...
...a 200 response could have contained a payload body. http/1.1 204 no content content-location: /file.txt etag: "e0023aa4f" specifications specification title rfc 5789: patch patch method for http ...
Protocol upgrade mechanism - HTTP
to a websocket connection for more details. if the server decides to upgrade the connection, it sends back a 101 switching protocols response status with an upgrade header that specifies the protocol(s) being switched to. if it does not (or cannot) upgrade the connection, it ignores the upgrade header and sends back a regular response (for example, a 200 ok). right after sending the 101 status code, the server can begin speaking the new protocol, performing any additional protocol-specific handshakes as necessary. effectively, the connection becomes a two-way pipe as soon as the upgraded response is complete, and the request that initiated the upgrade can be completed over the new protocol. common uses for this mechanism here we look at the most common use cases for the upgrade header. u...
...connection. it will appear no more than once in the response headers. sec-websocket-accept: hash hash if a sec-websocket-key header was provided, the value of this header is computed by taking the value of the key, concatenating the string "258eafa5-e914-47da-95ca-c5ab0dc85b11" to it, taking the sha-1 hash of that concatenated string, resulting in a 20-byte value. that value is then base64 encoded to obtain the value of this property. references websocket api http specifications and rfcs: rfc 7230 rfc 6455 rfc 7540 ...
300 Multiple Choices - HTTP
Web › HTTP › Status › 300
if the server has a preferred choice, it should generate a location header. ...
... if the server has a preferred choice, it should generate a location header. ...
303 See Other - HTTP
Web › HTTP › Status › 303
the method used to display this redirected page is always get. ...
...the method used to display this redirected page is always get. ...
308 Permanent Redirect - HTTP
Web › HTTP › Status › 308
a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the new url). the request method and the body will not be altered, whereas 301 may incorrectly sometimes be changed to a get method. note: some web applications may use the 308 permanent redirect in a non-standard way and for other purposes. ...
... applications may use the 308 permanent redirect in a non-standard way and for other purposes. for example, google drive uses a 308 resume incomplete response to indicate to the client when an incomplete upload stalled.[1] status 308 permanent redirect specifications specification title rfc 7538, section 3: 308 permanent redirect the hypertext transfer protocol status code 308 (permanent redirect) ...
410 Gone - HTTP
Web › HTTP › Status › 410
note: a 410 response is cacheable by default. ...
... note: a 410 response is cacheable by default. ...
418 I'm a teapot - HTTP
Web › HTTP › Status › 418
the http 418 i'm a teapot client error response code indicates that the server refuses to brew coffee because it is, permanently, a teapot. a combined coffee/tea pot that is temporarily out of coffee should instead return 503. this error is a reference to hyper text coffee pot control protocol defined in april fools' jokes in 1998 and 2014. ...
...fined in april fools' jokes in 1998 and 2014. status 418 i'm a teapot specifications specification title rfc 2324, section 2.3.2: 418 i'm a teapot hyper text coffee pot control protocol (htcpcp/1.0): semantics and content rfc 7168, section 2.3.3: 418 i'm a teapot the hyper text coffee pot control protocol for tea efflux appliances (htcpcp-tea): response codes ...
428 Precondition Required - HTTP
Web › HTTP › Status › 428
the http 428 precondition required response status code indicates that the server requires the request to be conditional. typically, this means that a required precondition header, such as if-match, is missing. when a precondition header is not matching the server side state, the response should be 412 precondition failed. ...
...e request to be conditional. typically, this means that a required precondition header, such as if-match, is missing. when a precondition header is not matching the server side state, the response should be 412 precondition failed. status 428 precondition required specifications specification title rfc 6585, section 3: 428 precondition required additional http status codes ...
429 Too Many Requests - HTTP
Web › HTTP › Status › 429
the http 429 too many requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting"). a retry-after header might be included to this response indicating how long to wait before making a new request. ...
... given amount of time ("rate limiting"). a retry-after header might be included to this response indicating how long to wait before making a new request. status 429 too many requests example http/1.1 429 too many requests content-type: text/html retry-after: 3600 specifications specification title rfc 6585, section 4: 429 too many requests additional http status codes ...
431 Request Header Fields Too Large - HTTP
Web › HTTP › Status › 431
the 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. ...
...large. ...
451 Unavailable For Legal Reasons - HTTP
Web › HTTP › Status › 451
status 451 unavailable for legal reasons example this example response is taken from the ietf rfc (see below) and contains a reference to monty python's life of brian. note: the link header might also contain a rel="blocked-by" relation identifying the entity and implementing blockage, not any other entity mandating it. ...
... <p>this request may not be serviced in the roman province of judea due to the lex julia majestatis, which disallows access to resources hosted on servers deemed to be operated by the people's front of judea.</p> </body> </html> specifications specification title rfc 7725: 451 unavailable for legal reasons an http status code to report legal obstacles ...
511 Network Authentication Required - HTTP
Web › HTTP › Status › 511
the http 511 network authentication required response status code indicates that the client needs to authenticate to gain network access. this status is not generated by origin servers, but by intercepting proxies that control access to the network. network operators sometimes require some authentication, acceptance of terms, or other user interaction before granting access (for example in an internet café or at an airport). they often identify clients who have not done so using their media access control (mac) addresses. ...
...ce of terms, or other user interaction before granting access (for example in an internet café or at an airport). they often identify clients who have not done so using their media access control (mac) addresses. status 511 network authentication required specifications specification title rfc 6585, section 6: 511 network authentication required additional http status codes ...
CSS Houdini
houdini is a set of low-level apis that exposes parts of the css engine, giving developers the power to extend css by hooking into the styling and layout process of a browser’s rendering engine. houdini is a group of apis that give developers direct access to the css object model (cssom), enabling developers to write code the browser can parse as css, thereby creating new css features without waiting for them to be implemented natively in browsers. advantages of houdini houdini enables faster parse times than using javascript .style for style changes. browsers parse the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts. in addition, layout, paint, and composite processes are repeated for javascript style updates. houd...
...aiting for them to be implemented natively in browsers. advantages of houdini houdini enables faster parse times than using javascript .style for style changes. browsers parse the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts. in addition, layout, paint, and composite processes are repeated for javascript style updates. houdini code doesn't wait for that first rendering cycle to be complete. rather, it is included in that first cycle — creating renderable, understandable styles. houdini provides an object-based api for working with css values in javascript. houdini's css typed om is a css object model with types and methods, exposing values as javascript objects making for more intuitive css manipulation than previous str...
About JavaScript - JavaScript
d to the syntactic class definitions common in compiled languages like c++ and java. once an object has been constructed it can be used as a blueprint (or prototype) for creating similar objects. javascript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval), object introspection (via for ... in), and source code recovery (javascript programs can decompile function bodies back into their source text). for a more in depth discussion of javascript programming follow the javascript resources links below. what javascript implementations are available? the mozilla project provides two javascript implementations. the first ever javascript was created by brendan eich at netscape, and has since been updated to...
...k into their source text). for a more in depth discussion of javascript programming follow the javascript resources links below. what javascript implementations are available? the mozilla project provides two javascript implementations. the first ever javascript was created by brendan eich at netscape, and has since been updated to conform to ecma-262 edition 5 and later versions. this engine, code named spidermonkey, is implemented in c/c++. the rhino engine, created primarily by norris boyd (also at netscape) is a javascript implementation written in java. like spidermonkey, rhino is ecma-262 edition 5 compliant. several major runtime optimizations such as tracemonkey (firefox 3.5), jägermonkey (firefox 4) and ionmonkey were added to the spidermonkey javascript engine over time. work is...
JavaScript data types and data structures - JavaScript
ipt provides binary (bitwise) operators. caution: although bitwise operators can be used to represent several boolean values within a single number using bit masking, this is usually considered a bad practice. javascript offers other means to represent a set of booleans (like an array of booleans, or an object with boolean values assigned to named properties). bit masking also tends to make the code more difficult to read, understand, and maintain. it may be necessary to use such techniques in very constrained environments, like when trying to cope with the limitations of local storage, or in extreme cases (such as when each bit over the network counts). this technique should only be considered when it is the last measure that can be taken to optimize size. bigint type the bigint type is...
...his means that once a string is created, it is not possible to modify it. however, it is still possible to create another string based on an operation on the original string. for example: a substring of the original by picking individual letters or using string.substr(). a concatenation of two strings using the concatenation operator (+) or string.concat(). beware of "stringly-typing" your code! it can be tempting to use strings to represent complex data. doing this comes with short-term benefits: it is easy to build complex strings with concatenation. strings are easy to debug (what you see printed is always what is in the string). strings are the common denominator of a lot of apis (input fields, local storage values, xmlhttprequest responses when using responsetext, etc.) and i...
Iterators and generators - JavaScript
tool, their creation requires careful programming due to the need to explicitly maintain their internal state. generator functions provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function whose execution is not continuous. generator functions are written using the function* syntax. when called, generator functions do not initially execute their code. instead, they return a special type of iterator, called a generator. when a value is consumed by calling the generator's next method, the generator function executes until it encounters the yield keyword. the function can be called as many times as desired, and returns a new generator each time. each generator may only be iterated once. we can now adapt the example from above. the behavior of ...
...tead, they return a special type of iterator, called a generator. when a value is consumed by calling the generator's next method, the generator function executes until it encounters the yield keyword. the function can be called as many times as desired, and returns a new generator each time. each generator may only be iterated once. we can now adapt the example from above. the behavior of this code is identical, but the implementation is much easier to write and read. function* makerangeiterator(start = 0, end = 100, step = 1) { let iterationcount = 0; for (let i = start; i < end; i += step) { iterationcount++; yield i; } return iterationcount; } iterables an object is iterable if it defines its iteration behavior, such as what values are looped over in a ...
Numbers and dates - JavaScript
r) year: years since 1900 for example, suppose you define the following date: var xmas95 = new date('december 25, 1995'); then xmas95.getmonth() returns 11, and xmas95.getfullyear() returns 1995. the gettime and settime methods are useful for comparing dates. the gettime method returns the number of milliseconds since january 1, 1970, 00:00:00 for a date object. ...
...ed today that contains today's date. it then creates a date object named endyear and sets the year to the current year. then, using the number of milliseconds per day, it computes the number of days between today and endyear, using gettime and rounding to a whole number of days. the parse method is useful for assigning values from date strings to existing date objects. for example, the following code uses parse and settime to assign a date value to the ipodate object: var ipodate = new date(); ipodate.settime(date.parse('aug 9, 1995')); example in the following example, the function jsclock() returns the time in the format of a digital clock. function jsclock() { var time = new date(); var hour = time.gethours(); var minute = time.getminutes(); var second = time.getseconds(); v...
SyntaxError: invalid regular expression flag "x" - JavaScript
lag" occurs when the flags, defined after the second slash in regular expression literal, are not one of g, i, m, s, u, or y. message syntaxerror: syntax error in regular expression (edge) syntaxerror: invalid regular expression flag "x" (firefox) syntaxerror: invalid regular expression flags (chrome) error type syntaxerror what went wrong? there are invalid regular expression flags in the code. in a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. they can also be defined in the constructor function of the regexp object (second parameter). regular expression flags can be used separately or together in any order, but there are only six of them in ecmascript. to include a flag with the regular expression, use...
...m in ecmascript. to include a flag with the regular expression, use this syntax: var re = /pattern/flags; or var re = new regexp('pattern', 'flags'); regular expression flags flag description g global search. i case-insensitive search. m multi-line search. s allow . to match newlines (added in ecmascript 2018) u unicode; treat pattern as a sequence of unicode code points y perform a "sticky" search that matches starting at the current position in the target string. see sticky examples there are only six valid regular expression flags. /foo/bar; // syntaxerror: invalid regular expression flag "b" did you intend to create a regular expression? an expression containing two slashes is interpr...
SyntaxError: missing } after function body - JavaScript
omewhere. check if any closing curly brackets or parenthesis are in the correct order. message syntaxerror: expected '}' (edge) syntaxerror: missing } after function body (firefox) error type syntaxerror what went wrong? there is a syntax mistake when creating a function somewhere. also check if any closing curly brackets or parenthesis are in the correct order. ...
...dy (firefox) error type syntaxerror what went wrong? there is a syntax mistake when creating a function somewhere. also check if any closing curly brackets or parenthesis are in the correct order. indenting or formatting the code a bit nicer might also help you to see through the jungle. examples forgotten closing curly bracket oftentimes, there is a missing curly bracket in your function code: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); }; correct would be: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); } }; it can be more obscure when using iife, closures, or other constructs that use a lot of different parenthesis and curly brackets, for example. (function() { if (true) { retur...
SyntaxError: missing } after property list - JavaScript
sage syntaxerror: expected '}' (edge) syntaxerror: missing } after property list (firefox) error type syntaxerror what went wrong? there is a mistake in the object initializer syntax somewhere. ...
...in the object initializer syntax somewhere. might be in fact a missing curly bracket, but could also be a missing comma, for example. also check if any closing curly brackets or parenthesis are in the correct order. ...
SyntaxError: missing ) after condition - JavaScript
the javascript exception "missing ) after condition" occurs when there is an error with how an if condition is written. it must appear in parenthesis after the if keyword. message syntaxerror: expected ')' (edge) syntaxerror: missing ) after condition (firefox) error type syntaxerror what went wrong? there is an error with how an if condition is written. in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. the if statement executes a statement if a specified condition is truthy. in javascript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is true } examples missing parenthesis it might just be an oversight, carefully check all you pa...
... and carry out actions accordingly depending on different inputs. the if statement executes a statement if a specified condition is truthy. in javascript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is true } examples missing parenthesis it might just be an oversight, carefully check all you parenthesis in your code. if (3 > math.pi { console.log("wait what?"); } // syntaxerror: missing ) after condition to fix this code, you would need to add a parenthesis that closes the condition. if (3 > math.pi) { console.log("wait what?"); } misused is keyword if you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in javascript.
TypeError: "x" is not a function - JavaScript
the javascript exception "is not a function" occurs when there was an attempt to call a value from a function, but the value is not actually a function. message typeerror: object doesn't support property or method {x} (edge) typeerror: "x" is not a function error type typeerror what went wrong? it attempted to call a value from a function, but the value is not actually a function. some code expects you to provide a function, but that didn't happen. maybe there is a typo in the function name? maybe the object you are calling the method on does not have this function? for example, javascript objects have no map function, but the javascript array object does. there are many built-in functions in need of a (callback) function. you will have to provide a function in order to have these me...
...return this; } var mynewdog = new dog(); mynewdog.name("cassidy"); //dog { age: 11, color: 'black', dogname: 'cassidy' } using brackets for multiplication in math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5). using the latter will throw an error: const sixteen = 2(3 + 5); alert('2 x (3 + 5) is ' + string(sixteen)); //uncaught typeerror: 2 is not a function you can correct the code by adding a * operator: const sixteen = 2 * (3 + 5); alert('2 x (3 + 5) is ' + string(sixteen)); //2 x (3 + 5) is 16 import the exported module correctly ensure you are importing the module correctly. an example helpers library (helpers.js) let helpers = function () { }; helpers.groupby = function (objectarray, property) { return objectarray.reduce(function (acc, obj) { var key = obj...
ReferenceError: assignment to undeclared variable "x" - JavaScript
are some differences between declared and undeclared variables, which might lead to unexpected results and that's why javascript presents an error in strict mode. three things to note about declared and undeclared variables: declared variables are constrained in the execution context in which they are declared. undeclared variables are always global. declared variables are created before any code is executed. undeclared variables do not exist until the code assigning to them is executed. declared variables are a non-configurable property of their execution context (function or global). undeclared variables are configurable (e.g. can be deleted). for more details and examples, see the var reference page. errors about undeclared variable assignments occur in strict mode code only. in no...
... examples invalid cases in this case, the variable "bar" is an undeclared variable. function foo() { 'use strict'; bar = true; } foo(); // referenceerror: assignment to undeclared variable bar valid cases to make "bar" a declared variable, you can add the var keyword in front of it. ...
The arguments object - JavaScript
is an array-like object accessible inside functions that contains the values of the arguments passed to that function. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. description note: if you're writing es6 compatible code, then rest parameters should be preferred. note: “array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have array's built-in methods like foreach() or map(). see §description for details. the arguments object is a local variable available within all non-arrow functions. you can refer to a function's arguments inside that function by usi...
... "<ul><li>one</li><li>two</li><li>three</li></ul>" */ rest, default, and destructured parameters the arguments object can be used in conjunction with rest, default, and destructured parameters. function foo(...args) { return args; } foo(1, 2, 3); // [1, 2, 3] while the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there are subtle differences for non-strict code. in strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. that is, assigning new values to variables in the body of the function will not affect the arguments object. nor will assigning new variables to the arguments object affect the value of variables. note: you ...
Array.prototype.reduce() - JavaScript
first call 0 1 1 [0, 1, 2, 3, 4] 1 second call 1 2 2 [0, 1, 2, 3, 4] 3 third call 3 3 3 [0, 1, 2, 3, 4] 6 fourth call 6 4 4 [0, 1, 2, 3, 4] 10 the value returned by reduce() would be that of the last callback invocation (10). you can also provide an arrow function instead of a full function. ...
...3, 4] 1 second call 1 2 2 [0, 1, 2, 3, 4] 3 third call 3 3 3 [0, 1, 2, 3, 4] 6 fourth call 6 4 4 [0, 1, 2, 3, 4] 10 the value returned by reduce() would be that of the last callback invocation (10). you can also provide an arrow function instead of a full function. ...
Array.from() - JavaScript
of both built-in and user-defined classes. as a result, static methods such as array.from() are "inherited" by subclasses of array, and create new instances of the subclass, not array. polyfill array.from() was added to the ecma-262 standard in the 6th edition (es2015). as such, it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of array.from() in implementations that don't natively support it. polyfill notes: this algorithm is exactly as specified in ecma-262 6th edition (assuming object and typeerror have their original values and that callback.call() evaluates to the original value of function.prototype.call()). in addition, since true iterables cannot be polyfilled, t...
...ange", e.g. clojure, php etc) const range = (start, stop, step) => array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)); // generate numbers range 0..4 range(0, 4, 1); // [0, 1, 2, 3, 4] // generate numbers range 1..10 with step of 2 range(1, 10, 2); // [1, 3, 5, 7, 9] // generate the alphabet using array.from making use of it being ordered as a sequence range('a'.charcodeat(0), 'z'.charcodeat(0), 1).map(x => string.fromcharcode(x)); // ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] specifications specification initial publication ecmascript (ecma-262)the definition of 'array.from' in that specification. ecmascript 2015 ...
Array.prototype.lastIndexOf() - JavaScript
lement in the array; -1 if not found. description lastindexof compares searchelement to elements of the array using strict equality (the same method used by the ===, or triple-equals, operator). polyfill lastindexof was added to the ecma-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of lastindexof in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object, typeerror, number, math.floor, math.abs, and math.min have their original values. // production steps of ecma-262, edition 5, 15.4.4.15 // reference: http://es5.github.io/#x15.4.4.15 if (!array.pr...
...f (k in t && t[k] === searchelement) { return k; } } return -1; }; } again, note that this implementation aims for absolute compatibility with lastindexof in firefox and the spidermonkey javascript engine, including in several cases which are arguably edge cases. if you intend to use this in real-world applications, you may be able to calculate from with less complicated code if you ignore those cases. examples using lastindexof the following example uses lastindexof to locate values in an array. var numbers = [2, 5, 9, 2]; numbers.lastindexof(2); // 3 numbers.lastindexof(7); // -1 numbers.lastindexof(2, 3); // 3 numbers.lastindexof(2, 2); // 0 numbers.lastindexof(2, -2); // 0 numbers.lastindexof(2, -1); // 3 finding all the occurrences of an element ...
Array.prototype.pop() - JavaScript
arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. if you call pop() on an empty array, it returns undefined. array.prototype.shift() has similar behavior to pop, but applied to the first element in an array. ...
...ray. examples removing the last element of an array the following code creates the myfish array containing four elements, then removes its last element. var myfish = ['angel', 'clown', 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the following code creates the myfish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter. var myfish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4}; var popped = array.prototype.pop.call(myfish); //same syntax for using apply( ) console.log(myfish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3} console.log(po...
Array.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the array. syntax arr.tosource() return value a string representing the source code of the array. description the tosource method returns the following values: for the built-in array object, tosource returns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource returns a string representing the source code. this method is usually called internally by javascript and not explicitly in code. you can call tosource while debugging to examine the contents of an array. ...
...ce returns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource returns a string representing the source code. this method is usually called internally by javascript and not explicitly in code. you can call tosource while debugging to examine the contents of an array. examples examining the source code of an array to examine the source code of an array: var alpha = new array('a', 'b', 'c'); alpha.tosource(); //returns ['a', 'b', 'c'] specifications not part of any standard. implemented in javascript 1.3. ...
Error.prototype.stack - JavaScript
function calls are indicated with "> function" and eval calls with "> eval". try { new function('throw new error()')(); } catch (e) { console.log(e.stack); } // anonymous@file:///c:/example.html line 7 > f...
...function calls are indicated with "> function" and eval calls with "> eval". try { new function('throw new error()')(); } catch (e) { console.log(e.stack); } // anonymous@file:///c:/example.html line 7 > function:1:1 // @file:///c:/example.html:7:6 try {...
Error.prototype.toSource() - JavaScript
this string can be evaluated to create an (approximately) equal object. naturally, the string containing the source follows the structure of the error constructor. for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the error instance. ...
...this string can be evaluated to create an (approximately) equal object. naturally, the string containing the source follows the structure of the error constructor. for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the error instance. ...
Error - JavaScript
r is outside of its valid range. referenceerror creates an instance representing an error that occurs when de-referencing an invalid reference. syntaxerror creates an instance representing a syntax error. typeerror creates an instance representing an error that occurs when a variable or parameter is not of a valid type. urierror creates an instance representing an error that occurs when encodeuri() or decodeuri() are passed invalid parameters. constructor error() creates a new error object. static methods error.capturestacktrace() a non-standard v8 function that creates the stack property on an error instance. instance properties error.prototype.message error message. error.prototype.name error name. error.prototype.description a non-standard microsoft property fo...
....error(e.name + ': ' + e.message) } else if (e instanceof rangeerror) { console.error(e.name + ': ' + e.message) } // ... etc } custom error types you might want to define your own error types deriving from error to be able to throw new myerror() and use instanceof myerror to check the kind of error in the exception handler. this results in cleaner and more consistent error handling code. see "what's a good way to extend error in javascript?" on stackoverflow for an in-depth discussion. es6 custom error class versions of babel prior to 7 can handle customerror class methods, but only when they are declared with object.defineproperty(). otherwise, old versions of babel and other transpilers will not correctly handle the following code without additional configuration. some...
Function() constructor - JavaScript
ated with a comma. for example: "x", "thevalue"—or "x,thevalue". functionbody a string containing the javascript statements comprising the function definition. description function objects created with the function constructor are parsed when the function is created. this is less efficient than declaring a function with a function expression or function statement and calling it within your code because such functions are parsed with the rest of the code. all arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed. omitting an argument will result in the value of that parameter being undefined. invoking the function constructor as a function (without using the new operator) has t...
...of the identifiers of the parameters in the function to be created, in the order in which they are passed. omitting an argument will result in the value of that parameter being undefined. invoking the function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor. examples specifying arguments with the function constructor the following code creates a function object that takes two arguments. // example can be run directly in your javascript console // create a function that takes two arguments, and returns the sum of those arguments const adder = new function('a', 'b', 'return a + b'); // call the function adder(2, 6); // 8 the arguments "a" and "b" are formal argument names that are used in the function body, "return a + b". ...
Function.prototype.apply() - JavaScript
github repository. if 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 func.apply(thisarg, [ argsarray]) parameters thisarg the value of this provided for the call to func. note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed. this argument is required. argsarray optional an array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function. starting with ecmascript 5 these arguments can be a generic array-like object instead of an ar...
... { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } } but beware: by using apply this way, you run the risk of exceeding the javascript engine's argument length limit. the consequences of applying a function with too many arguments (that is, more than tens of thousands of arguments) varies across engines. (the javascriptcore engine has hard-coded argument limit of 65536. this is because the limit (and indeed, even the nature of any excessively-large-stack behavior) is unspecified. some engines will throw an exception. more perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. to illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course...
Function.caller - JavaScript
it's also null for strict, async function and generator function callers. this property replaces the obsolete arguments.caller property of the arguments object. ...
... function myfunc() { if (myfunc.caller == null) { return 'the function was called from the top!'; } else { return 'this function\'s caller was ' + myfunc.caller; } } specifications not part of any standard. ...
Function.name - JavaScript
end us a pull request. property attributes of function.name writable no enumerable no configurable yes note that in non-standard, pre-es2015 implementations the configurable attribute was false as well. ...
...pt compressors and minifiers warning: be careful when using function.name and source code transformations, such as those carried out by javascript compressors (minifiers) or obfuscators. these tools are often used as part of a javascript build pipeline to reduce the size of a program prior to deploying it to production. such transformations often change a function's name at build-time. ...
Intl.DisplayNames() constructor - JavaScript
'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new intl.displaynames([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. for the general form and interpretation of the locales argument, see the intl page. the following unicode extension key is allowed: nu the numbering system to be used. possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt". options optional an object with some or all of the following properties: localematcher the locale mat...
... use. possible values are "lookup" and "best fit"; the default is "best fit". for information about this option, see the intl page. style the formatting style to use, the default is "long". "narrow" "short" "long" type the type to use, the default is "language". "language" "region" "script" "currency" fallback the fallback to use, the default is "code". "code" "none" examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned. console.log((new intl.displaynames()).of('us')); // expected output: 'us' specifications specification intl.displaynamesthe definition of 'the intl.displaynames constructor' in that specification.
Intl.DisplayNames.prototype.of() - JavaScript
the of() method receives a code and returns a string based on the locale and options provided when instantiating intl.displaynames. the source for this interactive example is stored in a github repository. if 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 displaynames.of(code); parameters code the code to provide depends on the type: if the type is "region", code should be either an iso-3166 two letters region code, or a three digits un m49 geographic regions. if the type is "script", code should be an iso-15924 four letters script code. ...
...thub.com/mdn/interactive-examples and send us a pull request. syntax displaynames.of(code); parameters code the code to provide depends on the type: if the type is "region", code should be either an iso-3166 two letters region code, or a three digits un m49 geographic regions. if the type is "script", code should be an iso-15924 four letters script code. if the type is "language", code should be a languagecode ["-" scriptcode] ["-" regioncode ] *("-" variant ) subsequence of the unicode_language_id grammar in uts 35's unicode language and locale identifiers grammar. languagecode is either a two letters iso 639-1 language code or a three letters iso 639-2 language code. if the type is "currency", code should be a 3-letter iso 4217 currency code. return value a language-...
Intl.Locale() constructor - JavaScript
examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types. ...
... examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types. ...
Intl.Locale.prototype.calendar - JavaScript
the intl.locale.prototype.calendar property is an accessor property which returns the type of calendar used in the locale. description the calendar property returns the part of the locale that indicates the locale's calendar era. while most of the world uses the gregorian calendar, there are several regional calendar eras used around the world. ...
...e type of calendar used in the locale. description the calendar property returns the part of the locale that indicates the locale's calendar era. while most of the world uses the gregorian calendar, there are several regional calendar eras used around the world. the following table shows all the valid unicode calendar key strings, along with a description of the calendar era they represent. unicode calendar keys unicode calendar keys calendar key (name) description buddhist thai buddhist calendar chinese traditional chinese calendar coptic coptic calendar dangi traditional korean calendar ethioaa ethiopic calendar, amete alem (epoch approx. 5493 b.c.e) ethiopic ethiopic calendar, amete mihret (epoch ap...
Intl.Locale.prototype.language - JavaScript
the intl.locale.prototype.language property is an accessor property that returns the language associated with the locale. description language is one of the core features of a locale. the unicode specification treats the language identifier of a locale as the language and the region together (to make a distiction between dialects and variations, e.g. british english vs. american english). the language property of a locale returns strictly the locale's language subtag. ...
...f a locale. the unicode specification treats the language identifier of a locale as the language and the region together (to make a distiction between dialects and variations, e.g. british english vs. american english). the language property of a locale returns strictly the locale's language subtag. examples setting the language in the locale identifer string argument in order to be a valid unicode locale identifier, a string must start with the language subtag. the main argument to the locale constructor must be a valid unicode locale identifier, so whenever the constructor is used, it must be passed an identifier with a language subtag. let langstr = new intl.locale("en-latn-us"); console.log(langstr.language); // prints "en" overriding language via the configuration object while the ...
Intl.Locale.prototype.numberingSystem - JavaScript
the numeral system used by the locale. description a numeral system is a system for expressing numbers. the numberingsystem property helps to represent the different numeral systems used by various countries, regions, and cultures around the world. as with most internationalization schemas, the numeral systems that can be represented in a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen below. value description adlm adlam digits ahom ahom digits arab arabic-indic digits arabext extended arabic-indic digits armn armenian upper case numerals — algorithmic armnlow armenian lower case numerals — algorithmic bali balinese di...
...nu is considered a locale string "extension subtag". these subtags add additional data about the locale, and are added to locale identifiers by first adding the -u key. to set the numberingsystem value via the string argument to the locale constructor, first add the -u extension key. next, add the -nu extensi...
Intl.PluralRules() constructor - JavaScript
minimumintegerdigits the minimum number of integer digits to use. possible values are from 1 to 21; the default is 1. minimumfractiondigits the minimum number of fraction digits to use. ...
... minimumsignificantdigits the minimum number of significant digits to use. possible values are from 1 to 21; the default is 1. maximumsignificantdigits the maximum number of significant digits to use. possible values are from 1 to 21; the default is 21. ...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
ctive-examples and send us a pull request. syntax relativetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given relativetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. style the length of the internationalized message. possible values are: "long" (default, e.g., in 1 month) "short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). the narrow style could be similar to t...
...short" (e.g., in 1 mo.), or "narrow" (e.g., in 1 mo.). the narrow style could be similar to the short style for some locales. numeric the format of output message. possible values are: "always" (default, e.g., 1 day ago), or "auto" (e.g., yesterday). the "auto" value allows to not always have to use numeric values in the output. numberingsystem the value requested using the unicode extension key "nu" or filled in as a default. examples using the resolvedoptions method var de = new intl.relativetimeformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.style; // "long" usedoptions.numeric; // "always" usedoptions.numberingsystem; // "latn" specifications specification status commen...
JSON.parse() - JavaScript
if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // parsing happens in four stages. in the first stage, we replace certain // unicode characters with escape sequences. javascript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = string(text); rx_dangerous.lastindex = 0; if (rx_dangerous.test(text)) { text = text.replace(rx_dangerous, function(a) { return ( "\\u" + ("0...
...ith escape sequences. javascript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = string(text); rx_dangerous.lastindex = 0; if (rx_dangerous.test(text)) { text = text.replace(rx_dangerous, function(a) { return ( "\\u" + ("0000" + a.charcodeat(0).tostring(16)).slice(-4) ); }); } // in the second stage, we run the text against regular expressions that look // for non-json patterns. we are especially concerned with "()" and "new" // because they can cause invocation, and "=" because it can cause mutation. // but just to be safe, we want to reject all unexpected forms.
Object.freeze() - JavaScript
oved from the array. freeze() returns the same object that was passed into the function. it does not create a frozen copy. in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned. ...
...assed into the function. it does not create a frozen copy. in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned. ...
Object.isSealed() - JavaScript
...
...ility matters for accessor properties) non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a sealed ordinary object, simply return true. object.issealed(1); // typeerror: 1 is not an object (es5 code) object.issealed(1); // true (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.issealed' in that specification. ...
Object.prototype.__proto__ - JavaScript
warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, a very slow operation, in every browser and javascript engine. the effects on the performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statements, but may extend to any code that has access to any object whose [[prototype]] has been altered. if you care about performance you should avoid setting the [[prototype]] of an object. instead, create a new object with the desired [[prototype]] using object.create(). warning: while object.prototype.__proto__ is supported today in most browsers, its existence and exact behavior has only been standardized in the ecmascript 2015 specificati...
...n access that does not consult object.prototype will not. if some other __proto__ property is found before object.prototype is consulted, that property will hide the one found on object.prototype. examples using __proto__ var circle = function () {}; var shape = {}; var circle = new circle(); // set the object prototype. // deprecated. this is for example purposes only. do not do this in real code. shape.__proto__ = circle; // get the object prototype console.log(shape.__proto__ === circle); // true var shape = function () {}; var p = { a: function () { console.log('aaa'); } }; shape.prototype.__proto__ = p; var circle = new shape(); circle.a(); // aaa console.log(shape.prototype === circle.__proto__); // true // or var shape = function () {}; var p = { a: function ...
Object.prototype.valueOf() - JavaScript
valueof method yourself; javascript automatically invokes it when encountering an object where a primitive value is expected. by default, the valueof method is inherited by every object descended from object. every built-in core object overrides this method to return an appropriate value. if an object has no primitive value, valueof returns the object itself. you can use valueof within your own code to convert a built-in object into a primitive value. when you create a custom object, you can override object.prototype.valueof() to call a custom method instead of the default object method. overriding valueof for custom objects you can create a function to be called in place of the default valueof method. your function must take no arguments. suppose you have an object type mynumbertype and ...
... you create a custom object, you can override object.prototype.valueof() to call a custom method instead of the default object method. overriding valueof for custom objects you can create a function to be called in place of the default valueof method. your function must take no arguments. suppose you have an object type mynumbertype and you want to create a valueof method for it. the following code assigns a user-defined function to the object's valueof method: mynumbertype.prototype.valueof = function() { return customprimitivevalue; }; with the preceding code in place, any time an object of type mynumbertype is used in a context where it is to be represented as a primitive value, javascript automatically calls the function defined in the preceding code. an object's valueof method is us...
Promise.all() - JavaScript
l([1,2,3]); // this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled var p2 = promise.all([1,2,3, promise.resolve(444)]); // this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected var p3 = promise.all([1,2,3, promise.reject(555)]); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log(p); console.log(p2); console.log(p3); }); // logs // promise { <state>: "fulfilled", <value>: array[3] } // promise { <state>: "fulfilled", <value>: array[4] } // promise { <state>: "rejected", <reason>: 555 } asynchronicity or synchronicity of promise.all this following example demonstrates the asynchronicity (or synchro...
...(or synchronicity, if the iterable passed is empty) of promise.all: // we are passing as argument an array of promises that are already resolved, // to trigger promise.all as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.all(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: array[2] } the same thing happens if promise.all rejects: var mixedpromisesarray = [promise.resolve(33), promise.reject(44)]; var p = promise.all(mixedpromi...
Promise.prototype.finally() - JavaScript
syntax p.finally(onfinally); p.finally(function() { // settled (fulfilled or rejected) }); parameters onfinally a function called when the promise is settled. ...
... syntax p.finally(onfinally); p.finally(function() { // settled (fulfilled or rejected) }); parameters onfinally a function called when the promise is settled. ...
Promise.prototype.then() - JavaScript
(new error("error!")); }); p1.then(value => { console.log(value); // success! }, reason => { console.error(reason); // error! }); chaining the then method returns a promise which allows for method chaining. if the function passed as handler to then returns a promise, an equivalent promise will be exposed to the subsequent then in the method chain. the below snippet simulates asynchronous code with the settimeout function. promise.resolve('foo') // 1. receive "foo", concatenate "bar" to it, and resolve that to the next then .then(function(string) { return new promise(function(resolve, reject) { settimeout(function() { string += 'bar'; resolve(string); }, 1); }); }) // 2. receive "foobar", register a callback function to work on that string ...
... }, 1); }); }) // 2. receive "foobar", register a callback function to work on that string // and print it to the console, but not before returning the unworked on // string to the next then .then(function(string) { settimeout(function() { string += 'baz'; console.log(string); // foobarbaz }, 1) return string; }) // 3. print helpful messages about how the code in this section will be run // before the string is actually processed by the mocked asynchronous code in the // previous then block. .then(function(string) { console.log("last then: oops... didn't bother to instantiate and return " + "a promise in the prior then so the sequence may be a bit " + "surprising"); // note that `string` will not have the...
handler.construct() - JavaScript
the construct method must return an object. description the handler.construct() method is a trap for the new operator. interceptions this trap can intercept these operations: new proxy(...args) reflect.construct() invariants if the following invariants are violated, the proxy will throw a typeerror: the result must be an object. examples trapping the new operator the following code traps the new operator. const p = new proxy(function() {}, { construct: function(target, argumentslist, newtarget) { console.log('called: ' + argumentslist.join(', ')); return { value: argumentslist[0] * 10 }; } }); console.log(new p(1).value); // "called: 1" // 10 the following code violates the invariant. const p = new proxy(function() {}, { const...
...the target in proxy initialization must itself be a valid constructor for the new operator. ...
handler.getOwnPropertyDescriptor() - JavaScript
a property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object. the result of object.getownpropertydescriptor(target) can be applied to the target object using object.defineproperty() and will not throw an exception. ...
... const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { getownpropertydescriptor: function(target, prop) { return undefined; } }); object.getownpropertydescriptor(p, 'a'); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[getownproperty]]' in that specification. ...
handler.set() - JavaScript
obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. that proxy's set() handler will be called, and obj will be passed as the receiver. return value the set() method should return a boolean value. return true to indicate that assignment succeeded. if the set() method returns false, and the assignment happened in strict-mode code, a typeerror will be thrown. description the handler.set() method is a trap for setting property value. interceptions this trap can intercept these operations: property assignment: proxy[foo] = bar and proxy.foo = bar inherited property assignment: object.create(proxy)[foo] = bar reflect.set() invariants if the following invariants are violated, the proxy will throw a typeerror: c...
...nding target object property is a non-writable, non-configurable data property. cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[set]] attribute. in strict mode, a false return value from the set() handler will throw a typeerror exception. examples trap setting of a property value the following code traps setting a property value. const p = new proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); return true; } }) console.log('a' in p); // false p.a = 10; // "property set: a = 10" console.log('a' in p); // true console.log(p.a); // 10 specifications specifica...
Proxy - JavaScript
the proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object. description a proxy is created with two parameters: target: the original object which you want to proxy handler: an object that defines which operations will be intercepted and how to redefine intercepted operations. ...
...c purposes, we will try to proxify a non-native object that is particularly suited to this type of operation: the doccookies global object created by the "little framework" published on the document.cookie page. /* var doccookies = ... ...
RangeError() constructor - JavaScript
the rangeerror() constructor creates an error when a value is not in the set or range of allowed values. syntax new rangeerror([message[, filename[, linenumber]]]) parameters message optional human-readable description of the error. ...
... the rangeerror() constructor creates an error when a value is not in the set or range of allowed values. syntax new rangeerror([message[, filename[, linenumber]]]) parameters message optional human-readable description of the error. ...
String.prototype.split() - JavaScript
has the effect of splitting. the result is an empty (i.e. zero length) string, which appears at the first (or last) position of the returned array. if separator is an empty string (""), str is converted to an array of each of its utf-16 "characters". warning: when the empty string ("") is used as a separator, the string is not split by user-perceived characters (grapheme clusters) or unicode characters (codepoints), but by utf-16 codeunits. this destroys surrogate pairs. see “how do you get a string to a character array in javascript?” on stackoverflow. limit optional a non-negative integer limiting the number of pieces. if provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. any leftover te...
...] note: \d matches the character class for digits between 0 and 9. reversing a string using split() this is not a robust way to reverse a string: const str = 'asdfghjkl' const strreverse = str.split('').reverse().join('') // 'lkjhgfdsa' // split() returns an array on which reverse() and join() can be applied it doesn't work if the string contains grapheme clusters, even when using a unicode-aware split. (use, for example, esrever instead.) const str = 'résumé' const strreverse = str.split(/(?:)/u).reverse().join('') // => "́emuśer" bonus: use === operator to test if the original string was a palindrome. specifications specification ecmascript (ecma-262)the definition of 'string.prototype.split' in that specification. ...
Symbol - JavaScript
such as enabling opaque data types, or serving as an implementation-supported unique identifier in general. some further explanation about purpose and usage can be found in the glossary entry for symbol. description to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. it creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be ...
...mple, new boolean, new string and new number). if you really want to create a symbol wrapper object, you can use the object() function: let sym = symbol('foo') typeof sym // "symbol" let symobj = object(sym) typeof symobj // "object" shared symbols in the global symbol registry the above syntax using the symbol() function will not create a global symbol that is available in your whole codebase. to create symbols available across files and even across realms (each of which has its own global scope), use the methods symbol.for() and symbol.keyfor() to set and retrieve symbols from the global symbol registry. finding symbol properties on objects the method object.getownpropertysymbols() returns an array of symbols and lets you find symbol properties on a given object. note that ever...
SyntaxError - JavaScript
constructor syntaxerror() creates a new syntaxerror object. instance properties syntaxerror.prototype.message error message. although ecma-262 specifies that syntaxerror should provide its own message property, in spidermonkey, it inherits error.prototype.message. syntaxerror.prototype.name error name. inherited from error. syntaxerror.prototype.filename path to file that raised this error. inherited from error. ...
... ...
TypeError() constructor - JavaScript
the typeerror() constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. syntax new typeerror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error filename optional optional. ...
...ration could not be performed, typically (but not exclusively) when a value is not of the expected type. syntax new typeerror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error filename optional optional. the name of the file containing the code that caused the exception linenumber optional optional. ...
TypedArray.prototype.map() - JavaScript
e first invocation of mapfn. elements which are appended to the array after the call to map() begins will not be visited by mapfn. if existing elements of the typed array are changed, or deleted, their value as passed to mapfn will be the value at the time map() visits them; elements that are deleted are not visited. ...
...the argument will automatically be assigned to each element of the typed array as map loops through the original typed array. ...
URIError() constructor - JavaScript
the urierror() constructor creates an error when a global uri handling function was used in a wrong way. syntax new urierror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error. filename optional optional. the name of the file containing the code that caused the exception. linenumber optional optional. the line number of the code that caused the exception. ...
... was used in a wrong way. syntax new urierror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error. filename optional optional. the name of the file containing the code that caused the exception. linenumber optional optional. the line number of the code that caused the exception. ...
WeakRef - JavaScript
old references to things which look like they are unreachable (e.g., in closures, or inline caches). different javascript engines may do these things differently, or the same engine may change its algorithms across versions. complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain apis. notes on weakrefs some notes on weakrefs: if your code has just created a weakref for a target object, or has gotten a target object from a weakref's deref method, that target object will not be reclaimed until the end of the current javascript job (including any promise reaction jobs that run at the end of a script job). that is, you can only "see" an object get reclaimed between turns of the event loop. this is primarily to avoid making the behavio...
...target object from a weakref's deref method, that target object will not be reclaimed until the end of the current javascript job (including any promise reaction jobs that run at the end of a script job). that is, you can only "see" an object get reclaimed between turns of the event loop. this is primarily to avoid making the behavior of any given javascript engine's garbage collector apparent in code — because if it were, people would write code relying on that behavior, which would break when the garbage collector's behavior changed. (garbage collection is a hard problem; javascript engine implementers are constantly refining 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 th...
WebAssembly.CompileError() constructor - JavaScript
the webassembly.compileerror() constructor creates a new webassembly compileerror object, which indicates an error during webassembly decoding or validation. syntax new webassembly.compileerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" co...
... ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the d...
WebAssembly.CompileError - JavaScript
from error. webassembly.compileerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.compileerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.compileerror.prototype.stack stack trace. inherited from error. instance methods webassembly.compileerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.compileerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10...
... ecmascript (ecma-262)the definition of 'nativeerror' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please ...
WebAssembly.LinkError() constructor - JavaScript
the webassembly.linkerror() constructor creates a new webassembly linkerror object, which indicates an error during module instantiation (besides traps from the start function). syntax new webassembly.linkerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello"...
... ecmascript (ecma-262)the definition of 'nativeerror constructors' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please ch...
WebAssembly.LinkError - JavaScript
r. inherited from error. webassembly.linkerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.linkerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.linkerror.prototype.stack stack trace. inherited from error. instance methods webassembly.linkerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.linkerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (...
... ecmascript (ecma-262)the definition of 'nativeerror' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https...
WebAssembly.Memory() constructor - JavaScript
the webassembly.memory() constructor creates a new memory object whose buffer property is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance. a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly. syntax new webassembly.memory(memorydescriptor); parameters memorydescriptor an object that can contain the following members: initial the initial size of the webassembly memory, in units of webassembly pages. maximum optional the maximum size the webassembly memory is allowed to grow to, in units of webassembly pages. when present, the maximum parameter acts as a hint to the engine to reserve memory up front. however, the engine may ignore or clamp th...
... 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } ...
WebAssembly.Memory - JavaScript
constructor webassembly.memory() creates a new memory object. instance properties memory.prototype.buffer an accessor property that returns the buffer contained in the memory. ...
...10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } ...
WebAssembly.Module - JavaScript
constructor webassembly.module() creates a new module object. static properties webassembly.module.customsections() given a module and string, returns a copy of the contents of all custom sections in the module with the given string name. webassembly.module.exports() given a module, returns an array containing descriptions of all the declared exports. webassembly.module.imports() given a module, returns an array containing descriptions of all the declared imports. ...
...y.module.exports() given a module, returns an array containing descriptions of all the declared exports. webassembly.module.imports() given a module, returns an array containing descriptions of all the declared imports. examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends the resulting module instance to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the modul...
WebAssembly.RuntimeError() constructor - JavaScript
the webassembly.runtimeerror() constructor creates a new webassembly runtimeerror object — the type that is thrown whenever webassembly specifies a trap. syntax new webassembly.runtimeerror(message, filename, linenumber) parameters message optional human-readable description of the error. filename optional the name of the file containing the code that caused the exception. linenumber optional the line number of the code that caused the exception. examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" cons...
... ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contrib...
WebAssembly.RuntimeError - JavaScript
from error. webassembly.runtimeerror.prototype.linenumber line number in file that raised this error. inherited from error. webassembly.runtimeerror.prototype.columnnumber column number in line that raised this error. inherited from error. webassembly.runtimeerror.prototype.stack stack trace. inherited from error. instance methods webassembly.runtimeerror.prototype.tosource() returns code that could eval to the same error. inherited from error. webassembly.runtimeerror.prototype.tostring() returns a string representing the specified error object.. inherited from error. examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10...
... ecmascript (ecma-262)the definition of 'nativeerror' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please ...
WebAssembly.Table - JavaScript
note: tables can currently only store function references, but this will likely be expanded in the future. constructor webassembly.table() creates a new table object. instance properties table.prototype.length returns the length of the table, i.e. the number of elements. ...
...ments. instance methods table.prototype.get() accessor function — gets the element stored at a given index. table.prototype.grow() increases the size of the table instance by a specified number of elements. table.prototype.set() sets an element stored at a given index to a given value. examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" consol...
globalThis - JavaScript
vent use of function in this way. the globalthis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. in this way, you can access the global object in a consistent manner without having to know which environment the code is being run in.to help you remember the name, just remember that in global scope the this value is globalthis. html and the windowproxy in many engines globalthis will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a proxy around the actual global object (which you can't directly access). this distinction i...
...owsers, due to iframe and cross-window security considerations, it references a proxy around the actual global object (which you can't directly access). this distinction is rarely relevant in common usage, but important to be aware of. naming several other popular name choices such as self and global were removed from consideration because of their potential to break compatibility with existing code. see the language proposal's "naming" document for more details. examples search for the global across environments prior to globalthis, the only reliable cross-platform way to get the global object for an environment was function('return this')(). however, this causes csp violations in some settings, so es6-shim uses a check like this, for example: var getglobal = function () { if (typeof ...
undefined - JavaScript
e undefined. a method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. a function returns undefined if a value was not returned. be careful. while it is possible to use it as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug. // don't do this // logs "foo string" (function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })(); // logs "foo string" (function(undefined) { console.log(undefined, typeof undefined); })('foo'); examples strict equality and undefined you can use undefined and the strict equality and inequality operators to determine whethe...
...t do this // logs "foo string" (function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })(); // logs "foo string" (function(undefined) { console.log(undefined, typeof undefined); })('foo'); examples strict equality and undefined you can use undefined and the strict equality and inequality operators to determine whether a variable has a value. in the following code, the variable x is not initialized, and the if statement evaluates to true. var x; if (x === undefined) { // these statements execute } else { // these statements do not execute } note: the strict equality operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. this is because null is n...
unescape() - JavaScript
ards"), it is defined in annex b of the ecma-262 standard, whose introduction states: … all of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. … … programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code. … the unescape() function computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. the escape sequences might be introduced by a function like escape. usually, decodeuri or decodeuricomponent are preferred over unescape. note: do not use unescape to decode uris, use decodeuri instead. syntax unescape(str) parameters str a string ...
... return value a new string in which certain characters have been unescaped. description the unescape function is a property of the global object. ...
uneval() - JavaScript
note: this will not return a json representation of object. description uneval() is a top-level function and is not associated with any object. ...
... note: this will not return a json representation of object. description uneval() is a top-level function and is not associated with any object. ...
Standard built-in objects - JavaScript
andard objects by category value properties these global properties return a simple value. they have no properties or methods. infinity nan undefined globalthis function properties these global functions—functions which are called globally, rather than on an object—directly return their results to the caller. eval() uneval() isfinite() isnan() parsefloat() parseint() encodeuri() encodeuricomponent() decodeuri() decodeuricomponent() deprecated escape() unescape() fundamental objects these are the fundamental, basic objects upon which all other objects are based. this includes general objects, booleans, functions, and symbols. object function boolean symbol error objects error objects are a special type of fundamental object. they ...
...array int32array uint32array float32array float64array bigint64array biguint64array keyed collections these objects represent collections which use keys. the iterable collections (map and set) contain elements which are easily iterated in the order of insertion. map set weakmap weakset structured data these objects represent and interact with structured data buffers and data coded using javascript object notation (json). arraybuffer sharedarraybuffer atomics dataview json control abstraction objects control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example). promise generator generatorfunction asyncfunction reflection reflect proxy internationalization additions to the ecmascript c...
new operator - JavaScript
turns this if the function doesn't return an object. creating a user-defined object requires two steps: define the object type by writing a function. create an instance of the object with new. to define an object type, create a function for the object type that specifies its name and properties. an object can have a property that is itself another object. see the examples below. when the code new foo(...) is executed, the following things happen: a new object is created, inheriting from foo.prototype. the constructor function foo is called with the specified arguments, and with this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments. the object (not null, false, 3.1415 or other primitive ty...
...y other objects. to add the new property to all objects of the same type, you must add the property to the definition of the car object type. you can add a shared property to a previously defined object type by using the function.prototype property. this defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. the following code adds a color property with value "original color" to all objects of type car, and then overwrites that value with the string "black" only in the instance object car1. for more information, see prototype. function car() {} car1 = new car(); car2 = new car(); console.log(car1.color); // undefined car.prototype.color = 'original color'; console.log(car1.color); // 'original color' car1.col...
void operator - JavaScript
mmediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void function iife() { console.log("executed!"); }(); // output: "executed!" executing the above function without the void keyword will result in an uncaught syntaxerror. javascript uris when a browser follows a javascript: uri, it evaluates the code in the uri and then replaces the contents of the page with the returned value, unless the returned value is undefined. the void operator can be used to return undefined. for example: <a href="javascript:void(0);"> click here to do nothing </a> <a href="javascript:void(document.body.style.backgroundcolor='green');"> click here for green background </a> note: javascript: pseudo protocol is...
...hat previously returned nothing. to be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing apis do not cause arrow functions' behaviors to change. button.onclick = () => void dosomething(); this ensures the return value of dosomething changing from undefined to true will not change the behavior of this code. specifications specification ecmascript (ecma-262)the definition of 'the void operator' in that specification. ...
export - JavaScript
inside the current module. ...
...rt cube from './my-module.js'; console.log(cube(3)); // 27 using export from let's take an example where we have the following hierarchy: childmodule1.js: exporting myfunction and myvariable childmodule2.js: exporting myclass parentmodule.js: acting as an aggregator (and doing nothing else) top level module: consuming the exports of parentmodule.js this is what it would look like using code snippets: // in childmodule1.js let myfunction = ...; // assign something useful to myfunction let myvariable = ...; // assign something useful to myvariable export {myfunction, myvariable}; // in childmodule2.js let myclass = ...; // assign something useful to myclass export myclass; // in parentmodule.js // only aggregating the exports from childmodule1 and childmodule2 // to re-export the...
function declaration - JavaScript
lt, functions return undefined. to return any other value, the function must have a return statement that specifies the value to return. conditionally created functions functions can be conditionally declared, that is, a function statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. for conditional function creation, use function expressions instead. var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (false) { function foo(){ return 1; } } // in chrome: // 'foo' name is hoisted. typeof foo is undefined // // in firefox: // 'foo' name is hoisted. typeof foo is undefined // // in edge: // 'foo' name...
...cript are hoisted to the top of the enclosing function or global scope. you can use the function before you declared it: hoisted(); // logs "foo" function hoisted() { console.log('foo'); } note that function expressions are not hoisted: nothoisted(); // typeerror: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; examples using function the following code declares a function that returns the total amount of sales, when given the number of units sold of products a, b, and c. function calc_sales(units_a, units_b, units_c) { return units_a * 79 + units_b * 129 + units_c * 699; } specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification. ...
if...else - JavaScript
... else statementn to see how this works, this is how it would look if the nesting were properly indented: if (condition1) statement1 else if (condition2) statement2 else if (condition3) ... to execute multiple statements within a clause, use a block statement ({ ... }) to group those statements. in general, it is a good practice to always use block statements, especially in code involving nested if statements: if (condition) { statements1 } else { statements2 } do not confuse the primitive boolean values true and false with truthiness or falsiness of the boolean object. any 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.
... 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 confused with equality when glancing over the code. for example, do not use the following code: if (x = y) { /* do something */ } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. for example: if ((x = y)) { /* do something */ } specifications specification ecmascript (ecma-262)the definition of 'if statement' in that specificati...
with - JavaScript
many cases this benefit can be achieved by using a temporary variable to store a reference to the desired object. contra: the with statement forces the specified object to be searched first for all name lookups. therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object. ambiguity contra contra: the with statement makes it hard for a human reader or javascript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. so given this example: function f(x, o) { with (o) { console.log(x); } } only when f is called is x either found or not, and if foun...
...(x, o) { with (o) { console.log(x); } } only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. if you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error -- just unexpected results. contra: code using with may not be forward compatible, especially when used with something other than a plain object. consider this example: function f(foo, values) { with (foo) { console.log(values); } } if you call f([1,2,3], obj) in an ecmascript 5 environment, then the values reference inside the with statement will resolve to obj. however, ecmascript 2015 introduces a values property on array...
Trailing commas - JavaScript
javascript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ecmascript 5) and most recently (ecmascript 2017) to function parameters. json, however, disallows trailing commas. ...
... javascript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ecmascript 5) and most recently (ecmascript 2017) to function parameters. json, however, disallows trailing commas. ...
MathML documentation index - MathML
Web › MathML › Index
ved from the latest mathml standard and modern browsers no longer support it. 15 <mfrac> mathml, mathml reference, mathml:element, mathml:general layout schemata the mathml <mfrac> element is used to display fractions. 16 <mglyph> mathml, mathml reference, mathml:element the mathml <mglyph> element is used to display non-standard symbols where existing unicode characters are not available. it may be used within token elements. 17 <mi> mathml, mathml reference, mathml:element, mathml:token elements the mathml <mi> element indicates that the content should be rendered as an identifier such as function names, variables or symbolic constants. you can also have arbitrary text in it to mark up terms. 18 <mlabeledtr> mathml...
...erence, mathml:element, mathml:script and limit schemata the mathml <munderover> element is used to attach accents or limits both under and over an expression. 40 <semantics> mathml, mathml reference, mathml:element in mathml there are two ways to mark up mathematics: presentation mathml is used to control the layout of equations, whereas content mathml is designed to encode the semantic mathematical meaning and to make expressions understandable to computer algebra systems. the mathml elements <semantics>, <annotation> and <annotation-xml> are used to combine presentation and content markup and to provide both, layout information and semantic meaning of mathematical expressions. ...
Guide to streaming audio and video - Web media technologies
https live streaming https live streaming (hls) is a protocol developed by apple and supported by safari on all of their platforms. ...
... https live streaming https live streaming (hls) is a protocol developed by apple and supported by safari on all of their platforms. ...
Animation performance and frame rate - Web Performance
pes. the performance cost of animating a css property can vary from one property to another, and animating expensive css properties can result in jank as the browser struggles to hit a smooth frame rate. for animated media, such as video and animated gifs, the main performance concern is file size - downloading the file size fast enough to not negatively impact performance is the greatest issue. code based animations, be it css, svg, <canvas>, webgl or other javascript animations, can cause performance issues even if the bandwidth footprint is small. these animations can consume cpu and/or cause jank. while performance is sensitive to the particular system and its load, performance tools can help you understand the work the browser's doing to render your site, and help you prevent and diagno...
... is not always possible to maintain 60fps, it is important to maintain a high and steady frame rate for all animations. let's take a look at how we can use browser tools to inspect the frame rate. we'll also discuss some tips to create and maintain a fast and steady frame rate. the developer tool's frame rate and waterfall charts provide insight into the work the browser is performing to animate code. using these tools you can measure an application's animation frame rate, and diagnose performance bottlenecks if any are found. with css animations you specify a number of keyframes, each of which uses css to define the appearance of the element at a particular stage of the animation. the browser creates the animation as a transition from each keyframe to the next. compared with animating elem...
Populating the page: how browsers work - Web Performance
okup. other processes javascript compilation while the css is being parsed and the cssom created, other assets, including javascript files, are downloading (thanks to the preload scanner). javascript is interpreted, compiled, parsed and executed. the scripts are parsed into abstract syntax trees. some browser engines take the abstract syntax tree and pass it into an interpreter, outputting bytecode which is executed on the main thread. this is known as javascript compilation. building the accessibility tree the browser also builds an accessibility tree that assistive devices use to parse and interpret content. the accessibility object model (aom) is like a semantic version of the dom. the browser updates the accessibility tree when the dom is updated. the accessibility tree is not modifia...
...s children and any nodes with display: none, such as the script { display: none; } you will find in user agent stylesheets, are not included in the render tree as they will not appear in the rendered output. nodes with visibility: hidden applied are included in the render tree, as they do take up space. as we have not given any directives to override the user agent default, the script node in our code example above will not be included in the render tree. each visible node has its cssom rules applied to it. the render tree holds all the visible nodes with content and computed styles -- matching up all the relevant styles to every visible node in the dom tree, and determining, based on the css cascade, what the computed styles are for each node. layout the fourth step in the critical rending...
Lazy loading - Web Performance
es that are not critical for the first render to happen. a practical example would be when, you land on the home page of an e-commerce site which has a link to a cart page/section and all its resources (js, css, images...) are downloaded only when the user navigates to that cart page. strategies lazy loading can be applied to multiple resources and through multiple strategies. ...
... home page of an e-commerce site which has a link to a cart page/section and all its resources (js, css, images...) are downloaded only when the user navigates to that cart page. strategies lazy loading can be applied to multiple resources and through multiple strategies. general code splitting javascript, css and html can be split into smaller chunks. this enables sending the minimal code required to provide value upfront, improving page-load times. the rest can be loaded on demand. entry point splitting: separates code by entry point(s) in the app dynamic splitting: separates code where dynamic import() statements are used javascript script type module any script tag with type="module" is treated like a javascript module and is deferred by default. css b...
Navigation and resource timings - Web Performance
r the rest of this explanation, we use the following variable: let timing = performance.getentriesbytype('navigation')[0]; protocol we can check the protocol used by querying: let protocol = timing.nexthopprotocol it returns the network protocol used to fetch the resource: in this case h2 for http/2. compression to get the compression savings percentage, we divide the transfersize by the decodedbodysize, and subtract that from 100%. we see a savings of over 74%. let compressionsavings = 1 - (timing.transfersize / timing.decodedbodysize) we could have used let compressionsavings = 1 - (timing.encodedbodysize / timing.decodedbodysize) but using transfersize includes the overhead bytes. for comparison, we can look at the network tab and see that we transferred 22.04kb for an uncompres...
...rammatically check transfer sizing and bandwidth savings. note that this is the size for this single document alone: for this resource alone, not for all the resources combined. however, the duration, load events and dom related timings have to do with the entire navigation, not this single asset. client-side web applications may seem faster than this one with ​transfer sizes under 10000 and decoded body sizes under 30000, but that doesn't mean javascript, css, or media assets aren't adding bloat. checking compression ratios is important but ensure to also check duration and the time between when the domcontentloaded event ended and when the dom is complete, as running javascript on the main thread for long periods of time can lead to a non-responsive user interface. request time the api ...
Web Performance
garding the loading of an application's resources.optimizing startup performanceregardless of platform, it's always a good idea to start up as quickly as possible. since that's a universal issue, we won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. that means not running all your startup code in a single event handler on the app's main thread.performance budgetsa performance budget is a limit to prevent regressions. it can apply to a file, a file type, all files loaded on a page, a specific metric (e.g. time to interactive), a custom metric (e.g. time to hero element), or a threshold over a period of time. performance fundamentalsperformance means efficiency. in the context of open ...
... other documentation developer tools performance features this section provides information on how to use and understand the performance features in your developer tools, including waterfall, call tree, and flame charts. profiling with the built-in profiler learn how to profile app performance with firefox's built-in profiler. ...
SVG Presentation Attributes - SVG: Scalable Vector Graphics
value: auto|baseline|before-edge|text-before-edge|middle|central|after-edge|text-after-edge|ideographic|alphabetic|hanging|mathematical|inherit; animatable: yes baseline-shift it allows repositioning of the do...
...ue: none|underline|overline|line-through|blink|inherit; animatable: yes text-rendering hints about what tradeoffs to make as the browser renders text. value: auto|optimizespeed|optimizelegibility|geometricprecision|inherit; animatable: yes transform defines a list of transform definitions that are applied to an element and the element's children. value: <transform-list>; animatable: yes unicode-bidi - value:; animatable: - vector-effect specifies the vector effect to use when drawing an object. value: default|non-scaling-stroke|inherit|<uri>; animatable: yes visibility lets you control the visibility of graphical elements. value: visible|hidden|collapse|inherit; animatable: yes word-spacing specifies spacing behavior between words. value: <length>|inherit; animatable: yes wr...
clip-rule - SVG: Scalable Vector Graphics
« svg attribute reference home the clip-rule attribute only applies to graphics elements that are contained within a <clippath> element. the clip-rule attribute basically works as the fill-rule attribute, except that it applies to <clippath> definitions. ...
...applies to <clippath> definitions. the following fragment of code will cause an evenodd clipping rule to be applied to the clipping path because clip-rule is specified on the <path> element that defines the clipping shape: <g> <clippath id="myclip"> <path d="..." clip-rule="evenodd" /> </clippath> <rect clip-path="url(#myclip)" ... /> </g> whereas the following fragment of code will not cause an evenodd clipping rule to be applied because the clip-rule is specified on the referencing element, not on the object defining the clipping shape: <g> <clippath id="myclip"> <path d="..." /> </clippath> <rect clip-path="url(#myclip)" clip-rule="evenodd" ... /> </g> as a presentation attribute, it also can be used as a property directly inside a css styleshe...
glyph-name - SVG: Scalable Vector Graphics
the glyph names can be referenced in kerning definitions created by <hkern> and <vkern> elements. ...
... the glyph names can be referenced in kerning definitions created by <hkern> and <vkern> elements. ...
u1 - SVG: Scalable Vector Graphics
Web › SVG › Attribute › u1
the u1 attribute specifies list of unicode characters (refer to the description of the unicode attribute of the <glyph> element for a description of how to express individual unicode characters) and/or ranges of unicode characters, which identify a set of possible first glyphs in a kerning pair. if a given unicode character within the set has multiple corresponding <glyph> elements (i.e., there are multiple <glyph> elements with the same unicode attribute value but different glyph-name values), then all such glyphs are included in the set. comma is the separator character; thus, to kern a comma, specify the comma as part of a range of unicode characters or as a glyph name using the g1 attribute. the total set of possible first glyphs in the kerning pair is the union of glyphs specified by t...
...bute. the total set of possible first glyphs in the kerning pair is the union of glyphs specified by the u1 and g1 attributes. two elements are using this attribute: <hkern> and <vkern> context notes value [ <character> | <urange> ]# default value none animatable no [ <character> | <urange> ]# this value indicates a comma-separated sequence of unicode characters and/or ranges of unicode characters, which identify a set of possible first glyphs in a kerning pair. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'u1' in that specification. recommendation initial definition ...
u2 - SVG: Scalable Vector Graphics
Web › SVG › Attribute › u2
the u2 attribute specifies list of unicode characters (refer to the description of the unicode attribute of the <glyph> element for a description of how to express individual unicode characters) and/or ranges of unicode characters, which identify a set of possible second glyphs in a kerning pair. if a given unicode character within the set has multiple corresponding <glyph> elements (i.e., there are multiple <glyph> elements with the same unicode attribute value but different glyph-name values), then all such glyphs are included in the set. comma is the separator character; thus, to kern a comma, specify the comma as part of a range of unicode characters or as a glyph name using the g2 attribute. the total set of possible second glyphs in the kerning pair is the union of glyphs specified by...
...ute. the total set of possible second glyphs in the kerning pair is the union of glyphs specified by the u2 and g2 attributes. two elements are using this attribute: <hkern> and <vkern> context notes value [ <character> | <urange> ]# default value none animatable no [ <character> | <urange> ]# this value indicates a comma-separated sequence of unicode characters and/or ranges of unicode characters, which identify a set of possible second glyphs in a kerning pair. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'u2' in that specification. recommendation initial definition ...
SVG Attribute reference - SVG: Scalable Vector Graphics
Web › SVG › Attribute
hrough-thickness string stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfacescale systemlanguage t tabindex tablevalues target targetx targety text-anchor text-decoration text-rendering textlength to transform transform-origin type u u1 u2 underline-position underline-thickness unicode unicode-bidi unicode-range units-per-em v v-alphabetic v-hanging v-ideographic v-mathematical values vector-effect version vert-adv-y vert-origin-x vert-origin-y viewbox viewtarget visibility w width widths word-spacing writing-mode x x x-height x1 x2 xchannelselector xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type x...
...tion-vertical, image-rendering, kerning, letter-spacing, lighting-color, marker-end, marker-mid, marker-start, mask, opacity, overflow, pointer-events, shape-rendering, stop-color, stop-opacity, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, text-decoration, text-rendering, transform, transform-origin, unicode-bidi, vector-effect, visibility, word-spacing, writing-mode filters attributes filter primitive attributes height, result, width, x, y transfer function attributes type, tablevalues, slope, intercept, amplitude, exponent, offset animation attributes animation attribute target attributes attributetype, attributename animation timing attributes begin, dur, end, min, max, restart, repeatco...
<glyph> - SVG: Scalable Vector Graphics
Web › SVG › Element › glyph
example svg <svg width="400px" height="300px" version="1.1" xmlns="http://www.w3.org/2000/svg"> <!-- example copied from https://www.w3.org/tr/svg/fonts.html#glyphelement --> <defs> <font id="font1" horiz-adv-x="1000"> <font-face font-family="super sans" font-wei...
...font-style="normal" units-per-em="1000" cap-height="600" x-height="400" ascent="700" descent="300" alphabetic="0" mathematical="350" ideographic="400" hanging="500"> <font-face-src> <font-face-name name="super sans bold"/> </font-face-src> </font-face> <missing-glyph><path d="m0,0h200v200h-200z"/></missing-glyph> <glyph unicode="!" horiz-adv-x="80" d="m0,0h200v200h-200z"></glyph> <glyph unicode="@" d="m0,50l100,300l400,100z"></glyph> </font> </defs> <text x="100" y="100" style="font-family: 'super sans', helvetica, sans-serif; font-weight: bold; font-style: normal">text using embe@dded font!</text> </svg> result specifications specification status comment ...
SVG 1.1 Support in Firefox - SVG: Scalable Vector Graphics
polygon implemented. text module text implemented. various presentation attributes don't work (alignment-baseline, baseline-shift, dominant-baseline, kerning, letter-spacing, word-spacing, writing-mode, glyph-orientation-horizontal, glyph-orientation-vertical) recently implemented presentation attributes: direction, unicode-bidi, font-variant, text-decoration svgtextelement recently imlemented bindings: selectsubstring recently implemented attributes: textlength, lengthadjust tspan implemented. various presentation attributes don't work (alignment-baseline, baseline-shift, dominant-baseline, kerning, letter-spacing, word-spacing, writing-...
...ently implemented attributes: textlength, lengthadjust tspan implemented. various presentation attributes don't work (alignment-baseline, baseline-shift, dominant-baseline, kerning, letter-spacing, word-spacing, writing-mode, glyph-orientation-horizontal, glyph-orientation-vertical) recently implemented presentation attributes: direction, unicode-bidi, font-variant, text-decoration svgtspanelement recently implemented bindings: selectsubstring recently implemented attributes: textlength, lengthadjust tref this feature, present in early draft of the spec, has been removed from it and is therefor not implemented (bug 273171). textpath im...
Paths - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Paths
elling clockwise or counter-clockwise. each ellipse has one short arc and one long arc. the two ellipses are just mirror images of each other. they are flipped along the line formed from the start→end points. if the start→end points are farther than the ellipse's x and y radius can reach, the ellipse's radii will be minimally expanded so it could reach the start→end points. the interactive codepen at the bottom of this page demonstrates this well. to determine if an ellipse's radii are large enough to require expanding, a system of equations would need to be solved, such as this on wolfram alpha. this computation is for the non-rotated ellipse with start→end (110, 215)→(150.71, 170.29). the solution, (x, y), is the center of the ellipse(s). the solution will be imaginary if the elli...
...defined. it's possible to approximate them by making the start and end points of the path slightly askew, and then connecting them with another path segment. ...
Texts - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Texts
font-size-adjust, kerning, letter-spacing, word-spacing and text-decoration. other text-related elements tspan this element is used to mark up sub-portions of a larger text. it must be a child of a text element or another tspan element. a typical usecase is to paint one word of a sentence bold red. ...
...d text length doesn't meet the one provided here. textpath this element fetches via its xlink:href attribute an arbitrary path and aligns the characters, that it encircles, along this path: <path id="my_path" d="m 20,20 c 80,60 100,40 120,20" fill="transparent" /> <text> <textpath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#my_path"> a curve. </textpath> </text> playable code 2 <svg width="200" height="100" xmlns="http://www.w3.org/2000/svg"> <path id="my_path" d="m 20,20 c 80,60 100,40 120,20" fill="transparent" /> <text> <textpath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#my_path"> a curve. </textpath> </text> <style><![cdata[ text{ dominant-baseline: hanging; font: 28px verdana, helvetica, arial, sans-serif; } ]]></style> </svg> ...
Web Components
this has traditionally not been so easy for custom markup structures — think of the complex html (and associated style and script) you've sometimes had to write to render custom ui controls, and how using them multiple times can turn your page into a mess if you are not careful. ...
...le and script) you've sometimes had to write to render custom ui controls, and how using them multiple times can turn your page into a mess if you are not careful. web components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions. custom elements: a set of javascript apis that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface. shadow dom: a set of javascript apis for attaching an encapsulated "shadow" dom tree to an element — which is rendered separately from the main document dom — and controlling associated functionality. in this way, you...
Index - XPath
Web › XPath › Index
...
...using xpath in javascript internally, in extensions, and from websites. mozilla implements a fair amount of the dom 3 xpath, which means that xpath expressions can be run against both html and xml documents. 57 xpath snippets example, snippets, xml, xpath, xslt this article provides some xpath code snippets. the snippets are functions you can use in the real world in your own code. ...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
6 advanced example xslt this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). 7 basic example xslt the basic example will load an xml file and apply a xsl transformation on it. these are the same fil...
...heet to be used in the transformation. the stylesheet has to be passed in as an xml document, which means that the .xsl file has to be loaded by the page before calling xsltprocessor.importstylesheet(). this can be done via xmlhttprequest or xmldocument.load(). 11 resources xslt no summary! 12 setting parameters xslt while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful. for example, javascript and xslt could be used to sort xml data and then display it. the sorting would have to alternate between ascending and descending sorting. 13 transforming xml with xslt needsmigration, transforming_xml_with_xslt, xml, xslt the separation of content ...
Loading Content Scripts - Archive of obsolete content
s enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery. unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it using contentscriptfile. this makes your code easier to maintain, secure, debug and review. the contentscriptwhen option specifies when the content script(s) should be loaded. it takes one of three possible values: "start" loads the scripts immediately after the document element for the page is inserted into the dom. at this point the dom content hasn't been loaded yet, so the script won't be able to interact with it. "ready" l...
Reddit Example - Archive of obsolete content
finally, it registers a listener to the user-defined click event which in turn passes the url into the open function of the tabs module. this is the panel.js content script that intercepts link clicks: $(window).click(function (event) { var t...
Getting Started - Archive of obsolete content
learn how to contribute to the add-on sdk. this page is now maintained alongside the sdk code itself: https://github.com/mozilla/gecko-dev/blob/master/addon-sdk/source/contributing.md. ...
SDK and XUL Comparison - Archive of obsolete content
ks in add-on development, and tool support which greatly simplifies the process of developing, testing, and packaging an add-on. compatibility although we can't promise we'll never break a high-level api, maintaining compatibility across firefox versions is a top priority for us. we've designed the apis to be forward-compatible with the new multiple process architecture (codenamed electrolysis) planned for firefox. we also expect to support both desktop and mobile firefox using a single edition of the sdk: so you'll be able to write one extension and have it work on both products. security if they're not carefully designed, firefox add-ons can open the browser to attack by malicious web pages. although it's possible to write insecure add-ons ...
clipboard - Archive of obsolete content
currently the image type doesn't support transparency on windows. examples set and get the contents of the clipboard. ...
indexed-db - Archive of obsolete content
ts running in web pages can access indexeddb via the window object. for example: window.indexeddb = window.indexeddb || window.webkitindexeddb || window.mozindexeddb || window.msindexeddb; var request = window.indexeddb.open("mydatabase"); request.onerror = function(event) { console.log("failure"); }; request.onsuccess = function(event) { console.log("success"); }; because your main add-on code can't access the dom, you can't do this. so you can use the indexed-db module to access the same api: var { indexeddb } = require('sdk/indexed-db'); var request = indexeddb.open('mydatabase'); request.onerror = function(event) { console.log("failure"); }; request.onsuccess = function(event) { console.log("success"); }; most of the objects that implement the indexeddb api, such as idbtransa...
notifications - Archive of obsolete content
n's data directory. see the self module documentation for more information. var notifications = require("sdk/notifications"); var self = require("sdk/self"); var myiconurl = self.data.url("myicon.png"); notifications.notify({ text: "i have an icon!", iconurl: myiconurl }); from firefox 34, you can use "./myicon.png" as an alias for self.data.url("myicon.png"). so you can rewrite the above code like this: var notifications = require("sdk/notifications"); var myiconurl = "./myicon.png"; notifications.notify({ text: "i have an icon!", iconurl: myiconurl }); this module depends on the underlying system's notification service. if the user's system does not support desktop notifications or if its notifications service is not running: if firefox was started normally, notifications ...
passwords - Archive of obsolete content
he www-authenticate response header sent by the server may include a "realm" field as detailed in rfc 2617. if it does, this property contains the value for the "realm" field. otherwise, it is omitted. the realm is displayed in firefox's password manager, under "site", in brackets after the url. ...
querystring - Archive of obsolete content
ring the query string. separator : string the string to use as a separator between each name:value pair. by default this is "&". assignment : string the string to use between each name and its corresponding value. by default this is "=". returns object : an object containing the components of the query string as name : value pairs. escape(query) the escape function used by stringify to encodes a string safely matching rfc 3986 for application/x-www-form-urlencoded. parameters query : string the query string to escape. returns string : the escaped query string. unescape(query) the unescape function used by parse to decode a string safely. parameters query : string an escaped query string. returns string : the unescaped string. ...
simple-prefs - Archive of obsolete content
preference type, this may be an integer, string, or boolean value. hidden a boolean value which, if present and set to true, means that the preference won't appear in the add-ons manager interface, so users of your add-on won't be able to see or alter it. { "name": "myhiddeninteger", "type": "integer", "title": "how many?", "hidden": true } your add-on's code will still be able to access and modify it, just like any other preference you define. type-specific attributes these are settings that are only applicable to certain preference types. they are documented along with the preference types themselves. preference types the setting types map to the inline settings types used by the add-on manager. all the inline preferences are supported...
simple-storage - Archive of obsolete content
cess your add-on's simple-storage programmatically from the console using the following: loader.modules['resource://gre/modules/commonjs/sdk/simple-storage.js'].exports.storage clarification from mozilla needed: writing the above line in add-on debugger console results in "referenceerror: loader is not defined". constructing arrays be careful to construct array objects conditionally in your code, or you may zero them each time the construction code runs. for example, this add-on tries to store the urls of pages the user visits: var ss = require("sdk/simple-storage"); ss.storage.pages = []; require("sdk/tabs").on("ready", function(tab) { ss.storage.pages.push(tab.url); }); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: f...
system - Archive of obsolete content
host application version console.log("version = " + system.version); // host application vendor console.log("vendor = " + system.vendor); // host application profile directory console.log("profile directory = " + system.pathfor("profd")); quit the host application to quit the host application, use the exit() function. var system = require("sdk/system"); system.exit(); globals functions exit(code) quits the host application with the specified code. if code is omitted, exit() uses the success code 0. to exit with failure use 1. var system = require("sdk/system"); system.exit(); parameters code : integer to exit with failure, set this to 1. to exit with success, omit this argument. pathfor(id) firefox enables you to get the path to certain "special" directories, such as the desktop o...
windows - Archive of obsolete content
= modelfor(chromewindow); // now we can use the sdk's high-level window api console.log(highlevelwindow.title); } browserwindows.on("open", converttochromeandback); note that directly accessing low-level chrome objects like this means you're no longer protected by the compatibility guarantees made by the sdk's high-level apis. in particular, depending on what you do with these objects, your code might not work with multiprocess firefox. globals functions open(options) open a new window. var windows = require("sdk/windows").browserwindows; // open a new window. windows.open("http://www.example.com"); // open a new window and set a listener for "open" event. windows.open({ url: "http://www.example.com", onopen: function(window) { // do stuff like listen for content // lo...
High-Level APIs - Archive of obsolete content
4 data encoding and decoding using base64 algorithms. clipboard interact with the system clipboard, setting and getting its contents. context-menu adds items, submenus, and menu separators to the page's context menu. hotkeys assign hotkey combinations to functions in your add-on. indexed-db exposes the indexeddb api to add-ons. l10n localize strings appearing in the add-on's javascript code. notifications display transient, toaster-style desktop messages to the user. page-mod run scripts in the context of web pages whose url matches a given pattern. page-worker create a permanent, invisible page and access its dom. panel creates transient dialogs to implement part of an add-on's user interface. passwords interact with firefox's password manager to add, retrieve and remove ...
content/symbiont - Archive of obsolete content
used by sdk modules that can load web content and attach content scripts to it. usage a symbiont loads the specified contenturl and content scripts into a frame, and sets up an asynchronous channel between the content scripts and the add-on code, enabling them to exchange messages using the port or postmessage apis. you map optionally pass a frame into the symbiont's constructor: if you don't, then a new hidden frame will be created to host the content. this trait is composed from the loader and worker traits. it inherits functions to load and configure content scripts from the loader, and functions to exchange messages between content scripts and the main add-on code from the worker. var { symbiont } = require('sdk/content/content'); var thing = symbiont.resolve({ constructor: '_init' ...
core/namespace - Archive of obsolete content
prototype.postmessage = function postmessage(message) { let { sandbox } = sandboxes(this); sandbox.postmessage(json.stringify(json.parse(message))); ... }; widget.prototype.destroy = function destroy() { view.prototype.destroy.call(this); // ... delete sandboxes(this).sandbox; }; exports.widget = widget; in addition access to the namespace can be shared with other code by just handing them a namespace accessor function. let { dom } = require('./view'); widget.prototype.setinnerhtml = function setinnerhtml(html) { dom(this).element.innerhtml = string(html); }; ...
frame/hidden-frame - Archive of obsolete content
also useful in the construction of apis that load web content for intermittent display, such as panel. usage the module exports a constructor function, hiddenframe, and two other functions, add and remove. hiddenframe constructs a new hidden frame. add registers a hidden frame, preparing it to load content. remove unregisters a frame, unloading any content that was loaded in it. ...
io/file - Archive of obsolete content
, it won't work for users on windows. to ensure your add-on works for everyone, generate paths using the join function. unfortunately this api does not currently provide a way to obtain an absolute base path which you could then use with join. for now, you need to require("chrome") and use the xpcom directory service as described in this article about file i/o. note that if you do decide to hardcode windows-style paths, be sure to escape backslashes in strings. for example, to specify the file at c:\users\myk, you need to use the string "c:\\users\\myk", not "c:\users\myk". read more about escaping characters in strings. globals functions basename(path) the path parameter must be an absolute path, relative paths will cause an error. use the fs/path module for relative path support. ...
lang/functional - Archive of obsolete content
: moe!"; function greet (name) { return "hi: " + name; } function exclaim (statement) { return statement + "!"; } parameters fn... : function takes a variable number of functions as arguments and composes them from right to left. returns function : the composed function. wrap(fn, wrapper) returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function. let { wrap } = require("sdk/lang/functional"); let wrappedhello = wrap(hello, function (fn, name) { return "before, " + fn(name) + "after"; }); wrappedhello("moe"); // "before, hello: moe, after" function hello (name) { return "hello: " + name; } parameters fn : function the function to be passed into the wrapper function...
system/child_process - Archive of obsolete content
below for writing to child process stdin) examples adaption of node's documentation for spawn(): var child_process = require("sdk/system/child_process"); var ls = child_process.spawn('/bin/ls', ['-lh', '/usr']); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('close', function (code) { console.log('child process exited with code ' + code); }); writing to child process' stdin because the sdk implementation does not include a write() method for child processes, you must use the "raw" emit event. const { emit } = require('sdk/event/core'); const { spawn } = require('sdk/system/child_process'); var proc = spawn("/bin/cat"); emit(proc.stdin, 'data', "hello from add-on code...
system/events - Archive of obsolete content
api for working with the application observer service. usage the system/events module provides core (low level) api for working with the application observer service, also known as nsiobserverservice. you can find a list of events dispatched by the firefox codebase here. var events = require("sdk/system/events"); var { ci } = require("chrome"); function listener(event) { var channel = event.subject.queryinterface(ci.nsihttpchannel); channel.setrequestheader("user-agent", "mybrowser/1.0", false); } events.on("http-on-modify-request", listener); globals functions emit(type, event) send an event to observer service parameters type : string the event type. event : object an optional object with data and subject attributes. data refers to a string that you would like to pass t...
test/httpd - Archive of obsolete content
rver for the mozilla platform, which can be used in unit tests. usage the most basic usage is: var { startserverasync } = require("sdk/test/httpd"); var srv = startserverasync(port, basepath); require("sdk/system/unload").when(function cleanup() { srv.stop(function() { // you should continue execution from this point. }) }); this starts a server in background (assuming you're running this code in an application that has an event loop, such as firefox). the server listens at http://localhost:port/ and serves files from the specified directory. you can serve static content or use sjs scripts, as described in documentation on developer.mozilla.org. you can also use nshttpserver to start the server manually: var { nshttpserver } = require("sdk/test/httpd"); var srv = new nshttpserver(); ...
ui/button/action - Archive of obsolete content
nly of an event emitted by the button. the button only emits one type of event, click. the listener is automatically removed after the first time the event is emitted. parameters event : string the event to listen for. action buttons only emit one type of event, "click". listener : function function that will be called on click. removelistener() removes an event listener. for example, this code is equivalent to once(): button.on("click", handleclick) function handleclick(state) { console.log("button '" + state.label + "' was clicked"); button.removelistener("click", handleclick); } parameters event : string the event to listener is listening for. action buttons only emit one type of event, "click". listener : function the listener to remove. destroy() destroy the button. a...
ui/toolbar - Archive of obsolete content
+ e.title); } function hiding(e) { console.log("hiding: " + e.title); } parameters event : string the name of the event to listen to. toolbar supports the following events: attach, detach, show, and hide. listener : function the listener function. this may be passed arguments, depending on the particular event. removelistener(event, listener) removes an event listener. ...
util/collection - Archive of obsolete content
he collection and adds all the items in the array. parameters object : object the property will be defined on this object. propname : string the name of the property. backingarray : array if given, this will be used as the collection's backing array. collection a collection object provides for...in-loop iteration. items are yielded in the order they were added. for example, the following code... var collection = require("sdk/util/collection"); var c = new collection.collection(); c.add(1); c.add(2); c.add(3); for (item in c) console.log(item); ... would print this to the console: 1 2 3 iteration proceeds over a copy of the collection made before iteration begins, so it is safe to mutate the collection during iteration; doing so does not affect the results of the iteration...
util/deprecate - Archive of obsolete content
globals functions deprecatefunction(fun, msg) dump to the console the error message given in the second argument, prefixed with "deprecated:", and print the stacktrace; then execute the function passed as first argument and returns its value. it does not raise an exception, but just displays the error message and continues to execute the function. this function is mostly used to flag usage of deprecated functions, that are still available but which we intend to remove in a future release. ...
Low-Level APIs - Archive of obsolete content
d html, css and javascript, that can be added to a designated area of the firefox user interface. ui/id create ui component ids. ui/sidebar enables you to create sidebars. ui/toolbar add a toolbar to the firefox user interface. util/array helper functions for working with arrays. util/collection a simple list-like class and utilities for using it. util/deprecate functions to deprecate code. util/list building blocks for composing lists. util/match-pattern test strings containing urls against simple patterns. util/object functions for working with objects. util/uuid generate or parse uuids. window/utils functions for working with browser windows. ...
console - Archive of obsolete content
o the corresponding functions and functions with a higher severity will have any effect. for example, if the logging level is set to "info", then calls to info(), log(), warn(), and error() will all result in output being written. but if the logging level is "warn" then only calls to warn() and error() have any effect, and calls to info() and log() are simply discarded. this means that the same code can be more verbose in a development environment than in a production environment - you just need to arrange for the appropriate logging level to be set. the complete set of logging levels is given in the table below, along with the set of functions that will result in output at each level: level will log calls to: all any console method debug debug(), error(...
package.json - Archive of obsolete content
ager, but other metadata required of add-ons. some of its entries, such as icon, name, and description, have direct analogues in the install manifest format, and entries from package.json are written into the install manifest when the add-on is built using jpm xpi. others, such as lib, permissions, and preferences, represent instructions to the jpm tool itself to generate and include particular code and data structures in your add-on. creating a manifest the package.json file is initially generated in your add-on's root directory the first time you run jpm init. it looks like this (assuming the add-on's directory is "my-addon"): { "name": "my-addon", "title": "my-addon", "id": "jid1-1fergv45e4f4f@jetpack", "description": "a basic add-on", "author": "", "license": "mpl-2.0", ...
Adding a Button to the Toolbar - Archive of obsolete content
or toggle button modules. create a new directory, navigate to it, and execute jpm init, accepting all the defaults. ...
Listening for Load and Unload - Archive of obsolete content
will be passed an object containing a string describing the reason it was loaded as well as any arguments passed to it. if your add-on exports a function called onunload(), then that function will be called when the add-on is unloaded, and it will be passed a string describing the reason it was unloaded. you don't have to use exports.main() or exports.onunload(). you can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main(). it will be loaded in the same circumstances, but you won't get access to the load/unload reason or arguments. exports.main() your add-on's main.js code is executed as soon as it is loaded. it is loaded when it is installed, when it is enabled, or when firefox starts. if your add-on exports a function called main(...
Developing for Firefox Mobile - Archive of obsolete content
r android to learn more about development of webextensions for firefox for android. to follow this tutorial you'll need to have learned the basics of jpm. firefox for android implements its ui using native android widgets instead of xul. with the add-on sdk you can develop add-ons that run on this new version of firefox mobile as well as on the desktop version of firefox. you can use the same code to target both desktop firefox and firefox mobile, and use jpm-mobile instead of the normal jpm. right now not all modules are fully functional, but we're working on adding support for more modules. the tables at the end of this guide list the modules that are currently supported on firefox mobile. this tutorial explains how to run sdk add-ons on an android device connected via usb to your deve...
Modifying the Page Hosted by a Tab - Archive of obsolete content
draws a red border around the page. then open any web page in the browser window, and click the button . you should see a red border appear around the page, like this: keeping content scripts in a separate file in the example above, we've passed in content script as a string. unless script is extremely simple, maintain the script as a separate file in add-on's data directory. this makes the code easier to maintain, debug, and review. to do this, provide option contentscriptfile not contentscript, whose value is a url pointing to one or more content script files. for example, if we save the script above under the add-on's data directory in a file called my-script.js: var self = require("sdk/self"); var button = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: ...
Troubleshooting - Archive of obsolete content
ple installations, jpm may have found the wrong one. in those cases you need to use jpm's --binary option. see the jpm guide for more information. when you run jpm to test your add-on or run unit tests, it prints out the location of the firefox or xulrunner binary that it found, so you can check its output to be sure. check your text console when errors are generated in the sdk's apis and your code, they are logged to the text console. this should be the same console or shell from which you ran the jpm command. search for known issues someone else might have experienced your problem, too. other users often post problems to the project mailing list. you can also browse the list of known issues or search for specific keywords. contact the project team and user group sdk users and project ...
Using XPCOM without chrome - Archive of obsolete content
notice the small l var bmlistener = bmlistener(); placesutils.bookmarks.addobserver(bmlistener, false); ...
Using third-party modules (jpm) - Archive of obsolete content
xplains how to use npm-hosted third-party sdk modules with jpm. we'll use the menuitem package to add a new menu item to firefox. summary first, while in the root of your add-on, install the package that contains the modules you want to use: npm install menuitem --save now you'll see a new directory in your add-on root called "node_modules" that contains a directory "menuitem". ...
Tutorials - Archive of obsolete content
com object. creating event targets enable the objects you define to emit their own events. listen for load and unload get notifications when your add-on is loaded or unloaded by firefox, and pass arguments into your add-on from the command line. using third-party modules (jpm) install and use additional modules which don't ship with the sdk itself. localization writing localizable code. mobile development develop add-ons for firefox mobile on android. add-on debugger debug your add-on's javascript. putting it together annotator add-on a walkthrough of a relatively complex add-on. ...
Add-on SDK - Archive of obsolete content
nents create user interface components such as toolbar buttons, context menus, menu items, and dialogs. modify web pages modify pages matching a url pattern or dynamically modify a particular tab. putting it together walkthrough of the annotator example add-on. guides contributor's guide learn how to start contributing to the sdk and about the most important idioms used in the sdk code such as modules, classes and inheritance, private properties, and content processes. sdk infrastructure aspects of the sdk's underlying technology: modules, the program id and the rules defining firefox compatibility. content scripts a detailed guide to working with content scripts. sdk idioms the sdk's event framework and the distinction between add-on scripts and content scripts. xu...
Alerts and Notifications - Archive of obsolete content
it uses nsialertsservice. ...
Cookies - Archive of obsolete content
services.cookies.add(".host.example.com", "/cookie-path", "cookie_name", "cookie_value", is_secure, is_http_only, is_session, expiry_date); see also document.cookie nsicookie nsicookie2 nsicookieservice nsicookiemanager nsicookiemanager2 http cookies ...
HTML in XUL for rich tooltips - Archive of obsolete content
this example demonstrates the dynamic injection of html into a xul element. specifically, we create a rich tooltip that uses html instead of plain text. dynamic html in xul tooltip insert the appropriate code from below into your xul overlay. this example is what the final xul overlay could look like, assuming a javascript overlay titled overlay.js: <?xml version="1.0" encoding="utf-8"?> <overlay id="htmltip-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> <script type="application/x-javascript" src="overlay.js"/> <popup id="contentareacontextmenu"> <menuitem id="htmltip1" label="foo1" onmouseover="htmltip.onmousetooltip(event)" tooltip="myhtmltip" /> <menuitem id="htmltip2...
JS XPCOM - Archive of obsolete content
contract ids a contract id is a unique name for an xpcom object. they are used to create or access well-known objects in xpcom. interfaces every xpcom object implements one or more interfaces. an interface is simply a list of constants and methods that can be called on the object, an example is nsifile. every xpcom object must implement the nsisupports interface. accessing xpcom components from javascript xpcom objects are either created as new instances (each creation gives you a completely new com object) or as services (each access gives you the same com object, often called a singleton). ...
Toolbar - Archive of obsolete content
ing the steps needed to add a toolbar button assuming you already have a working extension and know the basics of extension development: creating toolbar buttons adding button by default when you create and deploy your extension and include a toolbar button for it by overlaying the customize toolbarpalette, it is not available by default. the user has to drag it onto the toolbar. the following code will place your button on the toolbar by default. this should only be done on the first run of your add-on after installation so that if the user decides to remove your button, it doesn't show up again every time they start the application. notes insert your button by default only once, at first run, or when an extension update adds a new button. please only add your button by default if it ...
URI parsing - Archive of obsolete content
when dealing with the facilities of nsiuri, the task of parsing a uri can still require additional work. it's advised that you use the nsieffectivetldservice. grabbing the main domain using the effectivetldservice even using the etldservice, you're unable to get just the base domain sans tld. so, here's some sample code to determine the base domain without any suffixes: var etldservice = components.classes["@mozilla.org/network/effective-tld-service;1"]. getservice(components.interfaces.nsieffectivetldservice); var suffix = etldservice.getpublicsuffix(auri); var basedomain = etldservice.getbasedomain(auri); // this includes the tld basedomain = basedomain.substr(0, (basedomain.length - suffix.length - 1)); // - 1 to remove the period before the tld ...
View Source for XUL Applications - Archive of obsolete content
importing gviewsourceutils xul applications wanting to show the source code for documents should import the viewsourceutils.js script instead of attempting to open the viewsource.xul window themselves: <script type="application/javascript" src="chrome://global/content/viewsourceutils.js"/> viewsourceutils.js exposes a gviewsourceutils global into the scope of the window that imports that script. method overview gviewsourceutils exposes several methods, but the only one you should be using directly is the viewsource method. the rest of those methods should be considered private, and might become inaccessible in the future. void viewsource(aobject); methods viewsource opens a viewer to the source code for some document or uri. parameters the viewsource method takes an ...
XPath - Archive of obsolete content
notes and sample code for xpath and ajax (the following was moved from document.evaluate) obj.evaluate(xpathexpression,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return;...
Communication between HTML and your extension - Archive of obsolete content
. eventually i put the creation of the custom event into the statechanged function that was handling the receipt of the ajax request. after the html component was update with the result of the ajax request, i created and dispatched the event like this: var event = document.createevent("events"); event.initevent("my-custom-event", true, true); document.body.dispatchevent(event); in the code of the extension that catches the loading of a new page i added this code: var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a location object (see below for a link). // you can use it to make your code executed on certain pages only. if (doc && doc.addeventlistener) doc.addeventlistener("...
Custom about: URLs - Archive of obsolete content
more about generating uuid's: uuid. it is imported to queryinterface the components.manager otherwise this will not work. this example can be easily modified, just modify the global const at in the // globals section. in bug 1254752 things changed for firefox 48 and up. services.io.newchannel was deprecated, and the signature of the newchannel method changed. this change is reflected in the code below. this code will work for all versions of firefox 4 and up. const {classes: cc, interfaces: ci, manager: cm, results: cr, utils: cu, constructor: cc} = components; cm.queryinterface(ci.nsicomponentregistrar); components.utils.import("resource://gre/modules/services.jsm"); // globals const aboutpage_description = 'this is my custom about page'; const aboutpage_id = 'aa132730-2278-11e5-867...
Extension Theming Guidelines - Archive of obsolete content
custom themes may then register a replacement for your skin package allowing them to provide their own styles for all of your content. ...
Inline options - Archive of obsolete content
: function(asubject, atopic, adata) { if (atopic == "addon-options-displayed" && adata == "my_addon@my_domain") { var doc = asubject; var control = doc.getelementbyid("myaddon-pref-control"); control.value = "test"; } } }; services.obs.addobserver(observer, "addon-options-displayed", false); // don't forget to remove your observer when your add-on is shut down. this code should be in bootstrap.js (within the startup() function) for restartless extensions or in an xpcom component or a javascript code module (not an overlay!) for traditional extensions. note: starting in gecko 13.0, you can also listen for the addon-options-hidden notification, which has the same subject and data as above, to find out when the ui is about to be removed. use this notification to r...
Migrating raw components to add-ons - Archive of obsolete content
nted a set of best practices. javascript c-types some add-on authors create binary components not because they want to interact with firefox at the c++ level, but strictly so that they can make use of third party dlls. if this is the only reason you are using a binary component instead of javascript, take a look at the new javascript c-types support introduced in firefox 3.6. it allows javascript code to load functions from dlls on windows, and should allow you to eliminate your dependence on binary components entirely. this leads to a better compatibility path as new versions of firefox are released. ...
Introduction - Archive of obsolete content
ver a dozen xul developers conformed glaxstar at the time this tutorial was created, and the combined experiences of years creating firefox extensions are reflected here. with this tutorial you'll learn how to develop firefox extensions. you'll learn how to quickly do the most common tasks in extension development, comparing several different approaches to solve them. in most cases we'll provide code samples that you can easily copy and adapt to your needs, as well as some working example extensions. the tutorial aims to be as brief as possible, often falling back on mozilla documentation for more detailed information. you can think of it as a quick guide to the expansive world that is the mozilla platform. most links in this documentation are meant to be clicked and read. we'll start with a...
Useful Mozilla Community Sites - Archive of obsolete content
of users that use a localized version of firefox, so you shouldn't neglect them. using babelzilla takes little time and is very valuable. mozdev mozdev.org provides free project hosting and software development tools for mozilla applications and add-ons. it is the only hosting service tailored to the needs of the mozilla community. it offers many necessary services such as bug tracking, source code repositories, download mirrors and many communication tools. there are other free hosting sites such as souceforge and google code that are also very good, but not as specialized as mozdev. you should pick the one that best fits your development needs. conclusion that's it! this is the end of the xul school tutorial. hopefully this guide has helped you get started with add-on development and y...
Using the Stylesheet Service - Archive of obsolete content
oad the stylesheets. the order the sheets are applied in is undefined. usage notes stylesheets added using this service get applied to both chrome and content documents. remember to declare the correct namespace if you want to apply stylesheets to xul documents. registered style sheets are not remembered across restarts. loadandregistersheet fails if css contains #id. '#' must be percent-encoded, details see bug 659650. historical information nsistylesheetservice was introduced in firefox 1.5. in firefox 1.5 and 2, adding and removing such style sheets takes effect upon the next load of a page. in firefox 3, the changes take effect immediately, though some declarations (especially those affecting xul) won't work until a reload. backwards compatibility you can check for the availabi...
XML data - Archive of obsolete content
; } depth:before { content: "mean depth: "; } depth:after { content: " m"; } open the document in your browser: oceans arctic area: 13,000 million km² mean depth: 1,200 m atlantic area: 87,000 million km² mean depth: 3,900 m . . . notes about this demonstration: the superscript 2 (in "million km²") a unicode character, coded as \b2 in the css file. the heading, "oceans", has a negative top margin, moving it up so it is displayed on top of the border. challenge change the stylesheet so that it displays the document as a table. (see the tables chapter in the css specification for examples that you can adapt.) what next? if you had difficulty understanding this page, or if ...
XUL user interfaces - Archive of obsolete content
-interface language, usually pronounced like "zool"). in xul, many common user interface features are built in. for example, xul provides specialized windows like dialogs and wizards, as well as status bars, menus, tool bars, and even browsers. more specialized features can be built from parts by using xul together with other technologies that you have seen in this tutorial: css style, javascript code, and xbl bindings. like other xml-based languages, xul uses css stylesheets. more details for more information about xul user interfaces, see the xul page in this wiki. action: a xul demonstration make a new xul document as a plain text file, doc7.xul. copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <?xml-stylesheet ty...
Beginner tutorials - Archive of obsolete content
learn why this is so, and how to keep your sites from being bitten by this problem. ...
CSS3 - Archive of obsolete content
alues for properties. the css all property. the scoping mechanism. clarifies: interaction of media-dependent @import statements and style sheet loading requirements. css writing modes module level 3 proposed recommendation defines the writing modes of both horizontal and vertical scripts and clarifies how the css direction and unicode-bidi properties interact with the new css text-orientation property, and extends them where needed. css counter styles level 3 candidate recommendation testing modules css images module level 3 candidate recommendation defines the <image> data type. extends the url() syntax to support image slices using media fragments. adds...
DOMSubtreeModified - Archive of obsolete content
this event has been deprecated in favor of the mutation observer api this event can cause infinite loops if you decide to change the dom inside the event handler, hence it has been disabled in a number of browsers (see domattrmodified and domsubtreemodified events are no longer fired when style attribute is changed via cssom for example). ...
MozAudioAvailable - Archive of obsolete content
e description target read only eventtarget the event target (the topmost target in the dom tree). type read only domstring the type of event. bubbles read only boolean does the event normally bubble? cancelable read only boolean is it possible to cancel the event? framebuffer read only framebuffer (array) the decoded audio sample data (i.e., floats). time read only float timestamp for these samples measured from the start in seconds. ...
Getting the page URL in NPAPI plugin - Archive of obsolete content
1 = npn_getproperty( m_pnpinstance, swindowobj, identifier, &variantvalue ); // get a pointer to the "location" object. npobject *locationobj = variantvalue.value.objectvalue; // create a "href" identifier. identifier = npn_getstringidentifier( "href" ); // get the location property from the location object. bool b2 = npn_getproperty( m_pnpinstance, locationobj, identifier, &variantvalue ); this code is just a rough example. remember to release any references after using them. tradeoffs: uses npapi only works in most browsers does not work in mozillas older than firefox 1.0 via npp_newstream from braden mcdaniel: if you want the uri of the resource for which the plug-in is invoked, the most npapi-friendly way to do that is to get it from the npstream that is passed to npp_newstream. trad...
cert_override.txt - Archive of obsolete content
.840.1.101.3.4.2.3 certificate fingerprint using previous hash algorithm one or more characters for override type: m : allow mismatches in the hostname u : allow untrusted certs (whether it's self signed cert or a missing or invalid issuer cert) t : allow errors in the validity time, for example, for expired or not yet valid certs certificate's serial number and the issuer name as a base64 encoded string ...
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
etermine where to install a given plugin (for mozilla browsers) on windows. since the prospect of embedded gecko browsers raises the scenario of more than one gecko-based browser that a netscape-style plugin can work with, it becomes important to let plugin developers know how to discover these browsers on a windows machine. this information applies to mozilla based browsers that pull the mozilla codebase after the mozilla 0.9.1 milestone release. none of the registry keys mentioned here are written by browsers before the mozilla 0.9.1 timeframe. for example, netscape 6.0 and 6.01 do not write any of these keys into the registry, and thus these keys are not available for plugin vendors to parse for these two browsers. netscape 6.1 and onwards, however, will write these keys, and so creating a ...
No Proxy For configuration - Archive of obsolete content
www.mozilla.org:81 direct direct port number .mozilla.org:80 www.mozilla.org:80 www.mozilla.org direct direct :81 www.mozilla.org:81 proxy developer notes the no_proxy for logic is written in c++. pac is written in js, so there are potential problems with feature consistency and porting. david baron has pointed out that the original pac code in the "classic" tree is written in c++. the pac in c++ has not been tested in mozilla, so porting pac in c++ forward would not be a panacea. the relevant code lives in nsprotocolproxyservice.cpp. nsprotocolproxyservice::prefschanged - loads preferences nsprotocolproxyservice::loadfilters - parses filters nsprotocolproxyservice::examineforproxy - decides to check filters if configuration is...
Visualizing an audio spectrum - Archive of obsolete content
t fourier transform (fft) spectrum data for the playing audio. the function handling the loadedmetadata event stores the metadata of the audio element in global variables; the function for the mozaudioavailable event does an fft of the samples and displays them in a canvas. note: you can use the audionode called analysernode to perform real-time fft analysis on an audio stream, rather than the code shown below. <!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.g...
Bookmark Keywords - Archive of obsolete content
sult page has been bookmarked, we need only adjust the boookmark's properties. in this case, we'll give it a keyword and title of google and replace the term "geitost" with the %s, as shown (with extra highlighting) in figure 8. now we can run google searches straight from the address bar. these searches can be as complex as google will tolerate, since the entered data will be converted to url-encoded text before it's sent to the google servers. thus we could type any of the following into the address bar and get back useful results: <tt>google geitost</tt> <tt>google mozilla keyword bookmark</tt> <tt>google bookmark site:developer.netscape.com</tt> <tt>google netscape xml support -site:netscape.com</tt> a few examples in the course of writing this article, a number of potentially use...
Structure of an installable bundle - Archive of obsolete content
: /platform/win*/), it would provide the following files: /platform/linux_x86-gcc3/plugins/libmyplugin.so /platform/winnt_x86-msvc/plugins/myplugin.dll /platform/darwin_ppc-gcc3/plugins/libmyplugin.dylib because xpt files are not platform-specific, any associated xpt files would go in the generic components directory: /components/myplugin.xpt if an extension has non-binary platform-specific code (such as code which uses the windows registry from script), it can also use just the operating system identifier as a platform-subdirectory: /platform/winnt/components/registerdoctype.js when platform-specific jar files are used, each platform directory should have its own chrome.manifest file: chrome.manifest chrome/mytheme-base.jar platform/darwin/chrome.manifest platform/darwin/chrome/myth...
Conclusion - Archive of obsolete content
ucture and installer script to install these files in that subdirectory? how could you modify the extension to load the tinderbox page when you click on the status icon? mozilla has a fourth ui layer--localized text--that wasn't discussed in the tutorial because there is no text to localize. how could it be added to the extension if necessary? tinderbox actually keeps track of more than one codebase. in particular, it tracks both the main mozilla codebase (the trunk) and a stable branch. how could you modify tinderstatus to show the status of both the trunk and the branch? this extension can be installed into netscape 7 without problems. firefox has slightly different chrome registry requirements, so you may need to modify the contents.rdf files. for example, you need to change chrome:...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
the first step is to write a function that queries the tinderbox server and retrieves the current status. var gxmlhttprequest; function loadtinderboxstatus() { gxmlhttprequest = new xmlhttprequest(); gxmlhttprequest.onload = updatetinderboxstatus; gxmlhttprequest.open("get", "http://tinderbox.mozilla.org/seamonkey/panel.html"); gxmlhttprequest.send(null); } xmlhttprequest is an interface in mozilla for retrieving documents via http. ...
Enabling the behavior - updating the status bar panel - Archive of obsolete content
request.responsetext.match("11dd11")) icon.setattribute("status", "success"); else icon.setattribute("status", ""); } updatetinderboxstatus() retrieves a reference to the statusbarpanel element then searches through the retrieved html document (stored in the responsetext property of the xmlhttprequest instance) for one of several color references. the color red (represented by the rgb code ee0000) means a tinderbox client failed to build mozilla. the color orange ("ffaaoo") means a client successfully built mozilla, but the build failed tests. the color green ("11dd11") means the client successfully built and tested mozilla. when it finds a color, it sets the panel's status attribute to the corresponding status, which causes the previously defined css rules to switch to the icon ap...
Finding the file to modify - Archive of obsolete content
(alignment), and the behavior layer specifies how the widgets behave and how users can use them to accomplish their goals. mention the localization layer (note: these layers are not completely mutually exclusive. in particular, positioning information can be specified in both the structure layer and the style layer, and some behavior can be partly defined in the style layer.) we're going to add code to all three ui layers, starting with the structure layer. the structure layer consists of xul files. xul, which is short for xml-based user interface language (and is pronounced like "zool"), is an xml-based language specifically designed for describing application interfaces. it contains elements for all common ui widgets (menus, buttons, toolbars, etc.) and many sophisticated ones (trees, brow...
Getting Started - Archive of obsolete content
hat the structure of your new directory and classic.jar will be slightly different.) creating the install files icon.png and preview.png these are some png images containing the icon and the preview of the theme. chrome.manifest make a copy of chrome.manifest and place it in \my_theme and open it up in your text editor. this file is a small manifest file which is used to describe the skin. in the code search for all instances of "my_theme" and replace them with the name of your theme. the packages section lists which components of the browser you're modifying. if we also had skins for chatzilla, we would need to add another line resembling the other ones and change it to point to chatzilla. but this list includes everything that we changed, so just modify the blue text to point to match the na...
Creating a hybrid CD - Archive of obsolete content
'tvod' 'moov' "quicktime movie" .bin raw 'sitx' 'bina' "mac binary" .h ascii 'cwie' 'text' "c/c++ header file" .c ascii 'cwie' 'text' "c source file" .cp ascii 'cwie' 'text' "c++ source file" .cpp ascii 'cwie' 'text' "c++ source file" .exp ascii 'cwie' 'text' "symbol export file" .mcp raw 'cwie' 'mmpr' "codewarrior project file" .r ascii 'mps ' 'text' "rez file" .html ascii 'moss' 'text' "html file" .htm ascii 'moss' 'text' "html file" .txt ascii 'moss' 'text' "text file" readme ascii 'moss' 'text' "text file" changes ascii 'moss' 'text' "text file" install ascii 'moss' 'text' "text file" license ascii 'moss' 'text' "text f...
FAQ - Archive of obsolete content
to the interface, either visible or behind the scenes, your skin will have problems. when the mozilla developers make changes like this, they increase the skin version number. this is the number that is defined in contents.rdf. test your skin with every major release of mozilla. if a message appears in the preferences window telling you that it's an old skin, you're going to have to look over the code to see what changed. developers try to keep changes like this to a minimum, but sometimes it just can't be helped. what is an access key? an access key is a keyboard shortcut to access something. in the case of skins the access key that you are defining is accessible by going to edit->preferences, appearance->themes, and then pressing a letter. c will select classic and m will select modern. ...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
help, and mozapps directories from above, as well as the icon.png and preview.png files. (yes, this means that the structure of your new directory and classic.jar will be slightly different.) creating the install files contents.rdf make a copy of contents.rdf, place it in \my_theme and open it up in your text editor. this file is a small xml database which is used to describe the skin. in the code, search for all instances of "my_theme" and replace them with the name of your theme. the packages section lists which components of the browser you're modifying. if we also had skins for chatzilla, we would need to add another line resembling the other ones and change it to point to chatzilla. but this list includes everything that we changed, so just modify the blue text to point to match the ...
Installing Dehydra - Archive of obsolete content
to generate preprocessed mozilla source files (*.ii), see the pork install instructions. see also dehydra_manual treehydra build instructions ...
Dehydra - Archive of obsolete content
abandoned sometime in 2010. use at your own risk. the development focus switched to dxr (where the "d" comes from "dehydra"), which is based on clang instead of gcc. try dxr instead, or else try the gcc python plugin: https://fedorahosted.org/gcc-python-plugin/. dehydra was a lightweight, scriptable, general purpose static analysis tool capable of application-specific analyses of c++ code. in the simplest sense, dehydra could be thought of as a semantic grep tool. it presented a wealth of semantic information that can be queried with concise javascripts. it was also useful to find bugs in source code as it allows for much more error checking than c++ is capable of by itself. dehydra was built as a gcc plugin, thus it is easy to use for projects that already support gcc. dehydra i...
Download Manager improvements in Firefox 3 - Archive of obsolete content
firefox 3 offers improvements to the download manager that allow multiple progress listeners, use of the storage api for data management, download resuming, and more. in addition, you can augment or replace the download manager's user interface by implementing the new nsidownloadmanagerui interface. note: these changes will require some modest revisions to code using the download manager; several methods have had minor changes. download manager interfaces nsidownloadmanager gives applications and extensions access to the download manager, allowing them to add and remove files to the download list, retrieve information about past and present downloads, and request notifications as to the progress of downloads. nsidownload describes a file in the download queue; t...
Drag and Drop - Archive of obsolete content
ton. the element can simply ignore the event or can handle it some way, such as pasting the dragged object into itself. ondragend called when the drag operation is finished. there are two ways that drag and drop events can be handled. this first involves using the drag and drop xpcom interfaces directly. the second is to use a javascript wrapper object that handles some of this for you. the code for this wrapper can be found in a file named toolkit/content/nsdraganddrop.js nsdraganddrop.js which is contained in the widget-toolkit (or global) package. xpcom drag and drop interfaces two interfaces are used to support drag and drop. the first is a drag service, nsidragservice and the second is the drag session, nsidragsession. the nsidragservice is responsible for creating drag sessions ...
Editor Embedding Guide - Archive of obsolete content
state "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommandblock >all string cmd_acronym toggles acronym on selection. getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommand no parameters note this is logical style. cmd_code toggles code on selection. getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "s note this is logical style. typically it is displayed with monospace font. cmd_samp toggles program output sample style on selection. getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "stat...
Error Console - Archive of obsolete content
devtools.errorconsole.enabled preference to true. use the web console instead, for web content, or the browser console for chrome content. the error console is a tool available in most mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. it reports javascript-related errors and warnings, css errors and arbitrary messages from chrome code. in firefox, the error console can be opened from the tools menu or by ctrl-shift-j. for information about what javascript exceptions get logged into the error console, and how to make all exceptions get logged, read the article exception logging in javascript. see setting up extension development environment#development preferences for the preferences you should set if you want to see errors fr...
Block and Line Layout Cheat Sheet - Archive of obsolete content
t 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_external_reference ns_frame_replaced_element ns_frame_generated_content ns_frame_has_loaded_images ns_frame_out_of_flow ns_frame_selected_content ns_frame_is_dirty ns_frame_is_unflowable an unflowable frame is an error condition; for example, due to system limitations. currently, the on...
Downloading Nightly or Trunk Builds - Archive of obsolete content
derlying 'platform' called 'gecko' or 'mozilla' that firefox uses). as it turns out there is a platform number for every firefox number, but they are not the same number. firefox 3.0 corresponds to mozilla 1.9.0; firefox 3.5 corresponds to mozilla 1.9.1; firefox 3.6 corresponds to mozilla 1.9.2. however, the numbers are not used all of the time. sometimes the firefox releases are described by a code name. for example "shiretoko" is used for firefox 3.5. and very often neither names nor numbers are used, but rather special words indicating relative order are used. the three common cases are "trunk", meaning the most recent version of mozilla; "branch", meaning the version before trunk (though it can be any version before trunk); and "next", meaning a possible version in the future. so, if yo...
Firefox Sync - Archive of obsolete content
zilla.com/howtos/run-sync.html. ...
CRMF Request object - Archive of obsolete content
rack. 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. deprecatedthis feature has been removed from the web standards. though some browsers may still support it, it is in the process of being dropped. avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. be aware that this feature may cease to work at any time. warning: the features mentioned in this article are deleted proprietary mozilla extensions, and are not supported in any other browser. they won't work in firefox 34 or later. use <keygen> or the future web crypto api instead. rfc 4211...
Twitter - Archive of obsolete content
about the parameters of the various methods at twitter's api reference.) there are two special, optional properties: success and error. success is a function that's called when the request successfully completes, and error is a function called when it fails to complete. the library simply passes them to jquery.ajax(), and so they are called like so: success(data, textstatus) data is twitter's decoded json response. textstatus is a simple string describing the status. error(xmlhttprequest, textstatus, errorthrown) xmlhttprequest is the xhr used in the request. textstatus is a simple string describing the type of error. errorthrown is an exception object, if one was thrown. the examples below all use this first, simpler style. the second style will be familiar if you have used jquery.aja...
Settings - Archive of obsolete content
oolean", label: "music", default: true }, { name: "volume", type: "range", label: "volume", min: 0, max: 10, default: 5 } ] }; // import after defining manifest! jetpack.future.import("storage.settings"); this definition will result in a user interface with an input field for each setting defined above. ...
Settings - Archive of obsolete content
oolean", label: "music", default: true }, { name: "volume", type: "range", label: "volume", min: 0, max: 10, default: 5 } ] }; // import after defining manifest! ...
Clipboard - Archive of obsolete content
ods set(contentstringflavorstring) stringwrites data from jetpack to the clipboard. this is the recommended method of copying data to the clipboard. contentthe content to be copied to the clipboard. if no other arguments are specified, the flavor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard");// in text formatjetpack.clipboard.set("hello world");// in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flav...
Clipboard Test - Archive of obsolete content
ods set(contentstringflavorstring)writes data from jetpack to the clipboard. this is the recommended method of copying data to the clipboard. string contentthe content to be copied to the clipboard. if no other arguments are specified, the flavor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard");// in text formatjetpack.clipboard.set("hello world");// in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flav...
Clipboard - Archive of obsolete content
hods set(contentstringflavorstring)writes data from jetpack to the clipboard. this is the recommended method of copying data to the clipboard. string contentthe content to be copied to the clipboard. if no other arguments are specified, the flavor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if f...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
if a user forgets or is unable to tell whether a certain menuitem is part of firefox or provided by a feature, she does not know where to turn when she has problems with it. if many features' menus are local to one area, the user need not hunt and peck through many menus trying to find a particular item of a feature. no one likes it when add-ons clutter her tools menu willy-nilly. it's less code. (ok, slightly less.) this is only a recommended practice; developers are of course free to do as they wish. jetpack.menu.file the browser's file menu. a jetpack.menu object. jetpack.menu.edit the browser's edit menu. a jetpack.menu object. jetpack.menu.view the browser's view menu. a jetpack.menu object. jetpack.menu.history the browser's history menu. a jetpack.menu object. jetpack.menu.bookma...
slideBar - Archive of obsolete content
t update: v0.6 summary: slidebar is a reinvention of the old sidebar feature of browsers. they allow quick access to a wide range of both temporary and permanent information at the side of your browser window. when a slidebar feature is selected, its contents will be revealed from behind the current web page. creating a slidebar and adding options to implement a new slidebar within your jetpack code, use the method jetpack.slidebar.append(options) ...
Clipboard - Archive of obsolete content
hods set(contentstringflavorstring) stringwrites data from jetpack to the clipboard. this is the recommended method of copying data to the clipboard. contentthe content to be copied to the clipboard. if no other arguments are specified, the flavor of the content is assumed to 'plain'.string flavordata type. this is an optional parameter. the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard. jetpack.import.future("clipboard"); // in text format jetpack.clipboard.set("hello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if f...
Jetpack - Archive of obsolete content
-ons using common web technologies. ...
Makefile.mozextension.2 - Archive of obsolete content
sion - mozillazine knowledge base (2005). note that the original makefile.mozextention merely repeats the steps in getting started with extension development - mozillazine knowledge base (2008). the same goes for this slight makefile rework here. ...
Metro browser chrome tests - Archive of obsolete content
running the metro browser chrome tests to run mochitest, first build mozilla with your changes; then run ./mach mochitest-metro this will launch metro browser chrome tests in the default immersive browser. ...
Microsummary topics - Archive of obsolete content
y generator to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator() method, passing it an xml document containing the generator. ...
How to Write and Land Nanojit Patches - Archive of obsolete content
obsolete since gecko 11 (firefox 11 / thunderbird 11 / seamonkey 2.8)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. nanojit was removed during the development of (firefox 11 / thunderbird 11 / seamonkey 2.8), so this information is relevant to earlier versions of the codebase. adobe and mozilla share a copy of nanojit. this means that landing nanojit patches is a bit complicated, but experience has taught us that this is much better than having separate versions of nanojit. (note: this document is called nanojitmerge for historical reasons -- adobe and mozilla used to have separate copies of nanojit, but this was a maintenance headache so they were merged. the first version o...
Plug-n-Hack Phase1 - Archive of obsolete content
ts but, for testing purposes, ringleader (the firefox addon implementation of the browser component) allows you to set a preference to relax or disable origin checks. the preference is ringleader.check.origin this can be set to 'off' to disble origin checks completely, or 'noport' to disable only port checks. ...
Plugin Architecture - Archive of obsolete content
me. classes there are some classes involved in plugins: nsobjectloadingcontent embed, object and applet nodes inherit from that class, which provides services for loading various kinds of objects. it takes care of most of the work involved in loading the data and instantiating plugins. nsobjectframe the frame responsible for displaying plugins nsplugininstanceowner glue between plugin code (modules/plugin) and layout code (layout/generic). a refcounted object, contrary to nsobjectframe. note that while nsobjectloadingcontent also deals with images and documents, this document concentrates on plugins. sequence of events in content a content node for a plugin dom element gets created in bindtotree (usually) or another function, it calls loadobject loadobject either notices ...
Build - Archive of obsolete content
building prism is similar to building mccoy, but there are some differences which is why a separate build documentation article. to build prism, you must first build the xulrunner tree, and then build prism. make sure you have the required build prerequisites. grab the latest release source code from mozilla's ftp site. extract the source code, and you should have a directory called mozilla/. change directory into mozilla/ and checkout the latest prism code : cd mozilla/ svn co http://svn.mozilla.org/projects/webrunner/trunk prism create a file called .mozconfig make sure it is in the mozilla/ directory. the contents of the file should look something like this : mk_add_options moz_co_project=xulrunner mk_add_options moz_objdir=@topsrcdir@/mozilla-obj ac_add_options --enable-application...
Extensions - Archive of obsolete content
s features is an extreme lack of ui elements, which means that trying to use the same overlays in firefox and prism is really not possible. the basics in order to install an extension in prism, you need to follow the guidelines for building a mozilla-based extension. to support prism specifically, you'll need to add prism to the list of target applications in the extension's install.rdf file. the code snippet will look something like this: <em:targetapplication> <!– prism –> <description> <em:id>prism@developer.mozilla.org</em:id> <em:minversion>0.8</em:minversion> <em:maxversion>1.0.0.*</em:maxversion> </description> </em:targetapplication> in addition to the install manifest changes, you may want to expose your extension into the prism ui. prism does have a few ui elem...
FAQ - Archive of obsolete content
Archive › Mozilla › Prism › FAQ
, and dock, and it opens those applications in their own window separate from a web browser and without the browser interface (back and forward buttons, location bar, etc.). is prism a mozilla product? no, prism is not a mozilla product. it is one of the experiments being conducted by mozilla labs to bridge the divide in the user experience between web applications and desktop apps. prism is the codename for the project, and if the functionality provided by prism becomes a product or is integrated into other products (like firefox), then it won't necessarily continue to be called by this codename. is prism a platform? no, prism is not a platform. prism is built on top of the mozilla platform and its gecko rendering engine, just like mozilla firefox, so it provides the same capabilities to we...
Scripting - Archive of obsolete content
e server is not accessible). shutdown just before the application terminates. prism exposes desktop integration features through an property of the window object called platform. the platform property implements the nsiplatformglue interface, whose methods are described in the following section. methods of the window.platform object can be called from webapp.js or from web content. the following code can be used by web content to determine whether it is running in prism: if ("platform" in window) { // prism-specific code goes here } see the nsiplatformglue idl definition file for details of the methods available to prism apps. currently, the webapp script also has access to full xpcom functionality, just like a firefox extension. this level of functionality is commonly called chrome-level p...
New Skin Notes - Archive of obsolete content
k this is one of those "don't hold your breath" things because that's not managed by the skin. i could probably just eliminate it entirely. that'd work, too; you'd mentioned that it was very rarely used --beltzner the category template must be improved, it looks very unpolished comparing to rest of devmo. -- gandalf unfortunately the category styling is very much embedded into the mediawiki code. there are some other changes i need to make, however, so i'll try to fix it up a bit while i'm digging around in there. --dria how about modifying style for the side-bar to have a :hover class added which modifies (to a slightly lighter shade) the background color of the link, this will help to make items "appear as links" to many users, possibly add a text-decoration: underline as well. --ca...
Proxy UI - Archive of obsolete content
blank. ...
RDF Datasource How-To - Archive of obsolete content
., the entire file system structure). [more info on what each method needs to do here] rdf commands [describe what commands are, and why you'd implement them.] registering the datasource component a datasource is an xpcom component. as such, it must (currently, see [1]) have: an xpcom clsid to identify the data source implementation an implementation class (that corresponds to the clsid) whose code lives in a dll. the dll must be located in the xpcom components directory a factory that is registered to an xpcom progid in order to be instantiated from the repository. constructing a dll for a component is beyond the scope of this document; the reader is referred to the rdf factory as a guideline. registering an rdf datasource is fairly simple: in the dll's nsregisterself() method, you simply...
Safely loading URIs - Archive of obsolete content
third argument is a set of flags that can be used to impose additional restrictions on the uris that may be loaded. it's important to make sure that the first argument to these methods identifies the source of the uri. so if you're implementing a context menu and you add a "view image" option, the source of the image uri would be the page the image is in, not the chrome document the context menu code is in. differences between the methods the three methods differ from each other in how the source of the uri is identified and in what is known about the uri to be loaded. in general, the following guidelines apply for gecko 1.8: if you plan pass a uri string to nsiwebnavigation.loaduri (which can happen indirectly, e.g. by passing the string to something that loads it in a <browser> or <if...
Space Manager Detailed Design - Archive of obsolete content
the banddata collection, then add a trapezoid to the banddata collection such that it is marked as available and has arect that represents the space between the reference band tna dht band being examined if there is no more room in the banddata collection, estimate the number of entries requires as the current count + twice the number of bands below the reference band, plus two. return an error code so the caller can reallocate the collection and try again. check the size of the collection again, if there is no room left then estimate the number of items requires as the current count + twice the number of bands below the band in question plus one. create a new trapezoid in the band collection that has a region corresponding to the reference band rect, marked as occupied by either a single...
SpiderMonkey coding conventions - Archive of obsolete content
naming conventions public function names begin with js_ followed by capitalized "intercaps", e.g. js_newobject. extern but library-private function names use a js_ prefix and mixed case, e.g. js_searchscope. most static function names have unprefixed, mixed-case names: getchar. ...
open - Archive of obsolete content
l here. type a string describing the type of file being opened. description this method opens the file, preparing its resources for use by subsequent methods to examine or modify the file. certain methods of file, such as read and write should not be used when the file is not open. other methods, such as remove may not be used when the file is open. valid file types are text, binary and unicode. text indicates ascii text without nul characters. binary indicates utf-8 files. unicode indicates ucs-2 files. for all file types, carriage returns and linefeeds are treated in a platform-agnostic way. examples example: using open in the following example, myfile is a file object: myfile.open("read", "text"); see also ...
Archived SpiderMonkey docs - Archive of obsolete content
ocumentation. file objectnon-standard server-side objectmerging tracemonkey repothese are the steps to merge the tracemonkey repository to mozilla-central. between resolving conflicts, finding a good time to land, watching the tree, and marking bugs as fixed, it takes around half a day.spidermonkey coding conventionsthe spidermonkey project owners enforce coding conventions pretty strictly during code reviews. ...
String Quick Reference - Archive of obsolete content
why: avoid copying and conversion from literal char-based strings to utf16 strings. old way: use nsautostring and assignwithconversion() nsautostring widestring; widestring.assignwithconversion("some string"); callwidefunction(widestring); // use widestring again, but need a const prunichar* callwidewithflatstring(widestri...
Supporting private browsing mode - Archive of obsolete content
["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); var inprivatebrowsingmode = pbs.privatebrowsingenabled; if (!inprivatebrowsingmode) { /* save private information */ } in the above example, we only save the user's private information if not in private browsing mode. note: private browsing mode may only be detected by chrome code, such as extensions; web content cannot detect whether or not private browsing is in effect. detecting whether private browsing mode is permanent requires gecko 2.0(firefox 4 / thunderbird 3.3 / seamonkey 2.1) firefox 4 added support for having private browsing mode permanently enabled. the theme looks different in this scenario. to determine whether or not the browser is permanently in...
Table Layout Strategy - Archive of obsolete content
specs the table layout algorithm is based on two w3c recommendations: html 4.01 (chapter 11) and css2.1 (chapter 17).in css2 a distinction between fixed and auto layout of tables has been introduced. the auto-layout mechanism is implemented in basictablelayoutstrategy.cpp the fixed-layout in fixedtablelayoutstrategy.cpp. all these files are in the layout/html/table/src subdirectory. the code the layout strategies are invoked from nstableframe::reflow. the overload of the initialize and balancecolumnwidths routines depends on the table style and is decided at runtime. on the first reflow nstableframe::balancecolumnwidths is called. inside this routine the corresponding table layout strategy is created and initialized (basictablelayoutstrategy::initialize). later the column widths are...
Tamarin Acceptance Test Template - Archive of obsolete content
you may not use this file except in compliance with * the license. you may obtain a copy of the license at * http://www.mozilla.org/mpl/ * * software distributed under the license is distributed on an "as is" basis, * without warranty of any kind, either express or implied. see the license * for the specific language governing rights and limitations under the * license. * * the original code is [open source virtual machine.]. * * the initial developer of the original code is * adobe system incorporated. * portions created by the initial developer are copyright (c) 2005-2010 * the initial developer. all rights reserved. * * contributor(s): * adobe as3 team * * alternatively, the contents of this file may be used under the terms of * either the gnu general public license v...
Tamarin Acceptance Testing - Archive of obsolete content
in order to ensure that changes to the tamarin code base are high quality before submitting, all developers are required to complete the following steps. successfully build release and debug versions of the shell with the debugger enabled [info] successfully run the following test suites: acceptance test suite [info] self tests [info] submit a sandbox build request to test against platforms that you may not have locally [info] available tamarin acceptance test suites actionscript acceptance tests: actionscript acceptance tests running tamarin acceptance tests abc assembler tests cmdline tests performance tests actionscript performance tests running tamarin performance tests built-in self tests...
Tamarin Build System Documentation - Archive of obsolete content
nd will appear under sandbox phase what are the build phases? compile, smoke, test. when all of the slave machines are free they all start the first build phase simultaneously. if an error or failure occurs on any slave in a phase the build stops. the next phase is started when all slaves have completed the previous phase successfully. the compile phase compiles all of the tamarin source code and builds all of the shell executables, any errors will stop the phase and a red box will appear on the slave where the error occurred. the compile phase takes about 20-25 minutes. the smoke phase runs a set of tests on each platform until 2 minute is exceeded. the set of smoke tests can contain any shell build and any test suite (including performance). the smoke test list is constantly upda...
Tamarin-central rev 703:2cee46be9ce0 - Archive of obsolete content
buildsize flash10576k tc-700740k tc-703655k known issues known failures in the acceptance testsuite include: ...
Tamarin Releases - Archive of obsolete content
this page tracks tamarin source code releases, past, present and future. upcoming release name(s)release datelinks tc next~ april 2009roadmap current release namerelease datelinks tc "mar 2009" a5c9ed928c9603/27/09tamarin-devel announcement prior release name(s)release datelinks tc "feb 2009" a5c9ed928c9602/19/09tamarin-devel announcement tamarin-central rev 703:2cee46be9ce0 12/02/08tamarin-devel announcement ...
Tamarin mercurial commit hook - Archive of obsolete content
tip of tamarin-redux then add the following to your tamarin-redux/.hg/hgrc file (or to ~/.hgrc to implement for all local repos): [hooks] pretxncommit.commit = python:/path/to/tamarin-redux/utils/hooks/tamarin-commit-hook.py:master_hook once added, all commits will run the commit hook. hook use on every commit to your local repository, the hook will only check for violations in any new / changed code. any untouched lines of code that violate the check will be ignored. when a violation is found the following will be displayed: > hg commit -m "change with a tab" tab(s) found in test/test.txt for rev 1458 (change 53543674b8e6): @@ -65,4 +65,6 @@ +# tab here ^ (n)o, (y)es, (a)llow tabs for current file are you sure you want to commit this change? [n]: note that the prompt gives you the...
The new nsString class implementation (1999) - Archive of obsolete content
s. i18n issues another concern (mainly of the i18n team) has to do with the use of a 1-byte (ascii) nscstring at all. the i18n team correctly points out that that anarchy will prevail if judicious control over their use is not mandated. the problem stems from assumptions that programmers make regarding ascii strings; the typical assumption being that they will never need to interoperate with code that assumes ucs2 strings. this assumption is nearly always wrong -- and will seriously hinder our ability to localize the source base. it is recognized that (ascii) nscstring's are useful in the following contexts: whenever calling libraries that expect a char* variant whenever maximum memory efficiency is essential i would argue that only the first case is normatively legitimate. the i18n f...
[Deprecated] The Mozilla build VM - Archive of obsolete content
nterest may include: developer guide (documentation about developing on and for mozilla projects). mentored bugs have a mentor who commits to helping you every step of the way. generally, there should be enough information in the bug to get started. whenever you need help, contact the mentor via matrix, in the bug itself, or by email. when you've completed the bug, they will help you get your code into the tree. "good" first bugs may be a little stale, but at some point in their lives we considered that they would be a good first step for newcomers to mozilla. we are in the process of migrating these bugs to mentored bugs, but more recent "good first bugs" may be good starting points if there are no appropriate mentored bugs. you can also ask your getting-started questions in the introd...
Binding Attachment and Detachment - Archive of obsolete content
ing events occur: if required, anonymous content is cloned from the binding's content template and inserted around the bound element. the methods and properties of the binding are installed on the element and become available to scripts that reference the bound element. any specified event handlers are installed on their requested targets. if the binding needs to execute any initialization code following its attachment to an element, it can do so using a <constructor> block inside <implementation> section. this block contains script that executes upon completion of the binding attachment. within this block this refers to the bound element. <destructor> call bindings attached through css are detached when any of the following conditions are met: a bound element matches a style rule ...
XBL - Archive of obsolete content
removal of the xbl implementation is being tracked in bug 1566221. see also: xbl removal design review packet, problems with xbl and the xbl and web components comparison. xml binding language (xbl, sometimes also called extensible bindings language) is a language for describing bindings that can be attached to elements in other documents. the element that the binding is attached to, called the bound element, acquires the new behavior specified by the binding. ...
Unix stub installer - Archive of obsolete content
copy the installer.ini and config.ini files over into the src2 directory. if you don't want the installer to download then grab a nightly "full" installer, say from <ftp://ftp.mozilla.org/pub/mozilla/ni...gnu-sea.tar.gz>. then untar and gunzip this to /tmp. ...
Trigger Scripts and Install Scripts - Archive of obsolete content
triggers use the installtrigger object methods to compare software versions, install chrome, and perform simple software installations. install scripts use the install, file, installversion and platform-specific installation object methods to initialize, queue, manage, and perform the installation of one or more software packages. these install scripts are typically located at the top level of the xpi archives in which the installations are stored. ...
copy - Archive of obsolete content
summary makes a queued copy of the specified file. method of file object syntax int copy( filespecobject source, filespecobject dest ) parameters the copy method has the following parameters: source a filespecobject object reprsenting the file to be copied. dest a filespecobject object representing the destination directory. returns an integer error code. for a list of possible values, see return codes. description the destination can be a directory or a filename. if destination does not exist a new file will be created. ...
dirRename - Archive of obsolete content
dirrename renames a directory in place. method of file object syntax int dirrename( filespecobject directory, string newname ); parameters the dirrename method has the following parameters: directory a filespecobject representing the directory to be renamed. newname the new terminal (or leaf) name of the directory. returns an integer error code. for a list of possible values, see return codes. ...
execute - Archive of obsolete content
filespecobject executablefile, [string aparameters] ); parameters the execute method has the following parameters: executablefile a filespecobject representing the local file already on disk to be executed. note that file names are case sensitive. aparameters an optional parameter string that is passed to the executable. (ignored on mac os) returns an integer error code. for a list of possible values, see return codes. description the specified file is not actually executed until the performinstall method is called. see performinstall for more information about queued commands during the installation process. example f = getfolder("program", "mytexteditor.exe"); err = file.execute(f, "myfile.txt"); // indicates that 'myfile.txt' will be // opened in the editor...
macAlias - Archive of obsolete content
that represents the directory into which the program file will be installed. filename a string representing the name of the file to be installed. aliasdir a filespecobject that represents the directory into which the alias file will be installed (e.g.,"mac desktop"). aliasname a string representing the name of the alias itself. returns an integer error code. for a list of possible values, see return codes. example see file.macalias in the script examples chapter. ...
move - Archive of obsolete content
move moves a file from one location to another. method of file object syntax int move( filespecobject source, filespecobject dest ); parameters the move method has the following parameters: source a filespecobject representing the source file. dest a filespecobject representing the target directory. returns an integer error code. for a list of possible values, see return codes. description you must create a filespecobject for the destination directory to pass in for this function. if the destination doesn't already exist a file name for the destination is assumed. example source = getfolder("program", "file.txt"); dest = getfolder("chrome"); err = file.move(source, dest); ...
remove - Archive of obsolete content
summary deletes a specified file. method of file object syntax int remove( filespecobject file ) parameters the remove method has the following parameters: file a filespecobject representing the file to be removed. returns an integer error code. for a list of possible values, see return codes. ...
rename - Archive of obsolete content
summary renames a specified file in place. method of file object syntax int rename( filespecobject file, string newname ) parameters the rename method has the following parameters: file a filespecobject representing the file to be renamed. newname the new terminal (or leaf) name of the file. returns an integer error code. for a list of possible values, see return codes. ...
windowsRegisterServer - Archive of obsolete content
summary windowsregisterserver registers installed dlls with the windows registry. method of file object syntax int windowsregisterserver( object localdirspec ) parameters the windowsregisterserver method has the following parameters: localdirspec a filespecobject representing a directory obtained by getcomponentfolder or getfolder. returns an integer error code. for a list of possible values, see return codes. example filecdtool = getfolder("file:///", faod + "cdtool.dll"); err = file.windowsregisterserver(filecdtool); ...
windowsShortcut - Archive of obsolete content
r where atarget will is to be run from. aparams parameters that atarget requires. aicon a filespecobject representing the absolute path (including fiilename) to a file that contains icons. can be either .ico, .dll, .exe, or any other binary file that contains icons. aiconid index of the icon from aicon to use for this shortcut. returns an integer error code. for a list of possible values, see return codes. example see file.windowsshortcut in the script examples chapter. ...
compareTo - Archive of obsolete content
proceed to update ... } ...
addDirectory - Archive of obsolete content
rectory to the getfolder method. subdir the name of a directory to append to localdirspec, using '/' as the path separator regardless of the platform.if subdir is missing, null, or "", the filenames are appended directly to the folder name specified by localdirspec. flags an optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. in some situations, adddirectory may return other errors. description the adddirectory method puts the files in the specified directory in a temporary location. to move the files and all other subcomponents to their final location, call the performinstall method after you've successfully added all subcomponents. also see the note about binaries o...
addFile - Archive of obsolete content
ative to the localdirspec parameter. the file is installed in this location on the user's machine. you must always use forward slashes (/) in this pathname, regardless of the convention of the underlying operating system. if this parameter is blank or null, xpisourcepath is used. flags an optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. description the addfile method puts the file in a temporary location. to move this and all other files to their final location, call the performinstall method after you've successfully added all files. note: if you are installing binary files on a macintosh, be aware that the binary format for those files must be applesingle if the resource info...
cancelInstall - Archive of obsolete content
summary aborts installation of the software; performs cleanup of temporary files. method of install object syntax void cancelinstall() void cancelinstall( int errorcode ) parameters none. returns an integer error code. the optional argument is an error code that can be returned to the triggering page. for most purposes, it's recommended that one of the standard return codes be used. but a script can, in fact, return any valid integer. for a list of possible values, and any custom errorcode created by install writer, see return codes. example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ... err = getlasterror(); if (!err) perf...
deleteRegisteredFile - Archive of obsolete content
support this method.) deletes the specified file and removes its entry from the client version registry. method of install object syntax int deleteregisteredfile (string registryname); parameters the deleteregisteredfile method has the following parameter: registryname the pathname in the client version registry for the file that is to be deleted. returns an integer error code. for a list of possible values, see return codes. description the deleteregisteredfile method deletes the specified file and removes the file's entry from the client version registry. if the file is currently being used, the name of the file that is to be deleted is saved and netscape 6 attempts to delete it each time it starts up until the file is successfully deleted. this method is used to de...
execute - Archive of obsolete content
rameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this method in versions of netscape before 6.1/mozilla 0.9.3. returns an integer error code. for a list of possible values, see return codes. description the execute method extracts the named file from the xpi file to a temporary file name. your code must call the performinstall method to actually execute the file. you can use this method to launch an installshield installer or any install executable file stored in a xpi file. executing installed files note: if the file you wish to...
gestalt - Archive of obsolete content
gestalt (macintosh only) retrieves information about the operating environment. method of install object syntax int gestalt ( string selector ); parameters the gestalt method takes the following parameters: selector the selector code for the information you want. returns returns the requested information. the format depends on the select code specified in the selector parameter. description the gestalt method is a wrapper for the gestalt function of the macintosh toolbox. for information on that function, see inside macintosh: operating system utilities. this method returns null on unix and windows platforms. ...
logComment - Archive of obsolete content
logcomment adds a comment line to the installation log. method of install object syntax int logcomment( string acomment ); parameters the sole input parameter is a string whose value will be written to the log during the installation process. returns an integer error code. for a list of possible values, see return codes. description the install log is created in the product directory by default (where the browser executable is) if it can be, and if the installation doesn't have proper permission, the install log is written to the user's profile directory. respectively, these directories correspond to the "program" and "current user" keywords for the getfolder method. ...
performInstall - Archive of obsolete content
summary performs the actual installation of the software. moves all components to their final locations, launches any pending executions, and registers the package and all of its subcomponents in the client version registry. method of install syntax int performinstall(); parameters none. returns an integer error code. for a list of possible values, see return codes. in some situations the method may return other errors. in a few cases you may get a registry error. example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner", "/royalairways/tripplanner", "1.0.0.0"); ... err = getlasterror(); if (!err) performinstall(); else cancelinstall(err); ...
registerChrome - Archive of obsolete content
jects like that required by this function are created using the getfolder method on the install object. xpipath xpipath is the path within the xpi in where the contents.rdf file defining the chrome is located. for example, "locale/mylocale/aim," points to the locale/mylocale/aim subdirectory of the same xpi file in which the installation script is located. returns an integer error code. for a list of possible values, see return codes. in some situations the method may return other errors. in a few cases you may get a registry error. description when the third parameter is omitted (pointing to a specific location within the xpi file), this function is being used in a somewhat deprecated way. in this case, registerchrome is supporting the old format of installation archives, in ...
Properties - Archive of obsolete content
his property to "detect" the application version may produce false results. additionally, the build id can be 0 for custom builds. jarfile alias for archive platform contains information about the platform xpinstall was compiled for/runs on. for example, the value could begin with "windows", "macintosh" or "x11" (for unix/linux). for more details, see the corresponding code living in the getinstallplatform method of class nsinstall. url the fully qualified url of the xpi (file url, http url, ftp url, etc.) (e.g. http://dolfin/sgehani/zzz/ip.xpi). note, even if triggered using relative urls this will show the full url (after qualification). ...
Install Object - Archive of obsolete content
l with the name of the installation and the necessary registry and version information. add the files to the installation add files to the installation by calling getfolder to get file objects and passing those object refs to addfile as many times as necessary. perform installation check that the files have been added successfully (e.g., by checking the error return codes from many of the main installation methods, and go ahead with the install if everything is in order: performorcancel(); function performorcancel() { if (0 == getlasterror()) performinstall(); else cancelinstall(); } for complete script examples, see script examples. ...
createKey - Archive of obsolete content
the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". classname usually an empty string. for information on this parameter, see the description of regcreatekeyex in your windows api documentation. returns 0 if it succeeded; a nonzero number if it failed to schedule the creation. for a list of possible values, see return codes. description the createkey method adds a key to the registry. you must add a key to the registry before you can add a value for that key. ...
deleteKey - Archive of obsolete content
a key from the registry. method of winreg object syntax int deletekey ( string subkey); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". returns 0 if it succeeded; a nonzero number if it failed to schedule the deletion. for a list of possible values, see return codes. ...
setValue - Archive of obsolete content
hy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value a winregvalue object representing the new non-string value. see winregvalue for information about these values. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvalue method sets the value of an arbitrary key. use this method if the value you want to set is not a string. if the value is a string, the setvaluestring method is more convenient. ...
setValueNumber - Archive of obsolete content
the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value a number representing the new string value. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvaluenumber method sets the value of a key when that value is a number. use this method if the value you want to set is a number. if the value is not a number, use the setvalue or setvaluestring methods instead. ...
setValueString - Archive of obsolete content
ameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail". valname the name of the value-name/value pair whose value you want to change. value the new string value. returns 0 if it succeeded; a nonzero number if it failed to schedule the action. for a list of possible values, see return codes. description the setvaluestring method sets the value of a key when that value is a string. use this method if the value you want to set is a string. if the value is not a string, use the setvalue method instead. ...
XPInstall API reference - Archive of obsolete content
no properties methods createkey deletekey deletevalue enumkeys enumvaluenames getvalue getvaluenumber getvaluestring iskeywritable keyexists setrootkey setvalue setvaluenumber setvaluestring valueexists winregvalue constructor other information return codes see complete list examples trigger scripts and install scripts code samples file.macalias file.windowsshortcut install.adddirectory install.addfile installtrigger.installchrome installtrigger.startsoftwareupdate windows install ...
dir - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › dir
« xul reference home dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the elements are placed left to right or top to bottom in the order they appear in the xul code. reverse for scales, the scale's values are ordered from right to left (for horizontal scales) or from bottom to top (for vertical scales). for other elements, they are placed right to left or bottom to top. this is reverse of the order in which they appear in the xul code. see also resizer.dir ...
emptytext - Archive of obsolete content
...
image.onload - Archive of obsolete content
this applies whether the image is applied via the src attribute or the list-style-image style property. if you change the image, the event will fire again when the new image loads. ...
onbeforeaccept - Archive of obsolete content
« xul reference home onbeforeaccept type: script code the code in this attribute is called when the ok button is pressed or the acceptdialog method is called. returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ...
onchange - Archive of obsolete content
« xul reference home overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="hori...
onclick - Archive of obsolete content
« xul reference home onclick type: script code this event handler is called when the object is clicked. example <image src="hello.png" onclick="alert('hi')"/> see also click dom element ...
onclosetab - Archive of obsolete content
...
oncommandupdate - Archive of obsolete content
« xul reference home oncommandupdate type: script code this event occurs when a command update occurs. you would use this to update the disabled status of items. ...
onerror - Archive of obsolete content
...
onerrorcommand - Archive of obsolete content
...
oninput - Archive of obsolete content
this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. example <!-- this sets the label's text to the textbox value on each keystroke. ...
onnewtab - Archive of obsolete content
...
onpopuphidden - Archive of obsolete content
this event may also be received while the popup is still open, but when sub-menus contained within this popup are hidden. ...
onpopuphiding - Archive of obsolete content
...
onpopupshowing - Archive of obsolete content
this handler is usually used to dynamically set the contents when the user requests to display it. ...
onpopupshown - Archive of obsolete content
...
onsearchbegin - Archive of obsolete content
...
onsearchcomplete - Archive of obsolete content
...
ontextcommand - Archive of obsolete content
« xul reference home ontextcommand obsolete since gecko 1.9.1 type: script code note: applies to: thunderbird, seamonkeythis event handler is called when a result is selected for the textbox. as of gecko 1.9.1, this attribute is superseded by the ontextentered attribute. ...
ontextentered - Archive of obsolete content
...
ontextrevert - Archive of obsolete content
« xul reference home ontextrevert obsolete since gecko 1.9.1 type: script code note: applies to: thunderbird, seamonkey this event handler is called when the user presses escape to revert the textbox to its original uncompleted value. as of gecko 1.9.1, this attribute is superseded by the ontextreverted attribute. ...
ontextreverted - Archive of obsolete content
...
ordinal - Archive of obsolete content
« xul reference home ordinal type: string (representing an integer) an integer which specifies the position of the element within its parent. by default, elements appear in the order they appear in the xul code. the ordinal attribute can be used to change the order. note the default ordinal for elements is 1. you can retrieve the displayed order by using the properties of the boxobject of the container. ...
preference.type - Archive of obsolete content
« xul reference home type type: one of the values below the preference type which should be one of the following values. bool a boolean set to either true or false. usually a checkbox would be connected to these preferences. int an integer string a string unichar a unicode string wstring a localized string. in this situation the preference will save the path to a property file which contains the actual value of the preference. file a file. the file path will be stored in the preferences. ...
prefwindow.onload - Archive of obsolete content
...
sizemode - Archive of obsolete content
maximized windows). note: when a window is minimized, the sizemode attribute is not updated. this is done so that if a window is closed while minimized, its persisted sizemode attribute wouldn't be minimized. setting this attribute does not change the window state. use window.maximize(), window.restore(), or window.minimize() to change the window state. to get the window state from javascript code, use window.windowstate. listen to the sizemodechange event dispatched to the dom window to get notified when the window state changes. note: prior to gecko 13.0, this did not work on mac os x. note: prior to gecko 1.9.2, this was not always reliable. issues with this attribute (at least on firefox 3): sizemode is only updated when the value of the persist attribute on the root elem...
tabs.onselect - Archive of obsolete content
« xul reference home onselect type: script code this event is sent to the tabs element when this tab is changed. see also onselect ...
template - Archive of obsolete content
« xul reference home template type: id for template generated elements, this attribute may optionally be placed on the root node (the element with the datasources attribute) to refer to a template that exists elsewhere in the xul code. this template attribute should be set to the id of the template element. this might be used to share a single template between multiple trees or menus. if this attribute is not specified, there should be a template element directly inside the node. ...
textbox.onblur - Archive of obsolete content
« xul reference home onblur type: script code this event is sent when a textbox loses keyboard focus. note: the behavior of this event has evolved over time. prior to gecko 1.9 (firefox 3), the script code would execute in the context of the anonymous html <input> element inside the textbox binding. from gecko 1.9 to gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9), the script code would actually execute twice, once in the context of the anonymous html <input> element and once in the context of the <textbox> element itself. as of gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10), the script code only runs in the context of the <textbox> element, matching the behavior of all other event handlers. ...
textbox.onchange - Archive of obsolete content
the event is not sent until the focus is moved to another element. ...
textbox.onfocus - Archive of obsolete content
« xul reference home onfocus type: script code this event is sent when a textbox receives keyboard focus. note: the behavior of this event has evolved over time. prior to gecko 1.9 (firefox 3), the script code would execute in the context of the anonymous html <input> element inside the textbox binding. from gecko 1.9 to gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9), the script code would actually execute twice, once in the context of the anonymous html <input> element and once in the context of the <textbox> element itself. as of gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10), the script code only runs in the context of the <textbox> element, matching the behavior of all other event handlers. ...
tree.onselect - Archive of obsolete content
the user can select multiple rows by holding down shift or control and clicking on a row. the onselect event will be sent for each item added to or removed from the selection. ...
onunload - Archive of obsolete content
...
visuallyselected - Archive of obsolete content
« xul reference home visuallyselected type: boolean new in firefox 40. indicates that a tab is selected. the visuallyselected attribute is set asynchronously, once the browser has switched to the selected tab. if your code needs to apply some styling to the currently selected tab, this is the attribute you should use from firefox 40 onwards. this value is read-only. to change the selection, set either the selectedindex or selecteditem property of the containing element. ...
Attribute (XUL) - Archive of obsolete content
tooltiptext group handlectrltab height helpuri hidden hidechrome hidecolumnpicker hideheader hideseconds hidespinbuttons highlightnonmatches homepage href icon id ignoreblurwhilesearching ignorecase ignoreincolumnpicker ignorekeys image inactivetitlebarcolor increment index inputtooltiptext insertafter insertbefore instantapply inverted iscontainer isempty key keycode keytext label lastpage lastselected last-tab left linkedpanel max maxheight maxlength maxpos maxrows maxwidth member menu menuactive min minheight minresultsforpopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate newlines next noautofocus noautohide noinitialfocus nomatch norestorefocus object observes onbeforeaccept onbookm...
Deprecated and defunct markup - Archive of obsolete content
{many elements on this page are wrongly marked as deprecated, this page needs review} the following xul tags and attribute should be considered deprecated, if not defunct. the list below may include a few elements which are actually in use, but at a deeper level in the code. even some of the information on the tags below may be out of date, but is provided here for historical reference and to help anyone who comes across them in old code or documentation. elements <actions> (listed here by mistake or was it a container tag?) typo for <action> --neil 03 march 2011 <autorepeatbutton> (action occurs repeatedly on mouse hover--used to construct other elements; used in <arrowscrollbox> and large drop-down menus) so, not deprecated? --neil 03 march 2011 <bulletinboard> (made to...
Dynamically modifying XUL-based user interface - Archive of obsolete content
ferent web pages (and even different instances of the same web page) correspond to different documents. each xul window has its own distinct document, and there may even be a few different documents in a single window, when there is an <iframe>, <browser>, or a <tabbrowser> element. you must be sure to always manipulate the correct document. (read more about this in working with windows in chrome code.) when your script is included using a <script> tag, the document property references the dom document that includes the script. examples: using dom methods this section demonstrates the use of appendchild(), createelement(), insertbefore(), and removechild() dom methods. removing all children of an element this example removes all children of an element with id=someelement from the current docum...
Accessing Files - Archive of obsolete content
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. accessing files this section describes how to create a file reference. retrieving a file when working with files, usage is always done via a file object and not via string paths. this allows files to used in a portable way. because string paths are not used, references to files...
Working With Directories - Archive of obsolete content
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. a reference to a directory may be created in the same way as with a file by using nsiscriptableio.getfile(). you can access a subdirectory by supplying a directory name as the second argument, or refer to one of the special directories by supplying a null string for the second ...
Getting File Information - Archive of obsolete content
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. the nsifile object has a number of useful attributes which may be used to retrieve information about a file. two useful attributes filesize and lastmodifiedtime (nsifile.attributes) provide a means of retrieving the size of a file and the time when the file was last changed. ...
Uploading and Downloading Files - Archive of obsolete content
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. the io object and stream objects can be used to upload files to servers in various ways. the exact method depends on the type of upload that you wish to perform. http file upload some web sites allow one to upload a file. this is done by using an html <input> element using t...
IO - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › IO
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. files and streams this section describes how to access and get information about files, read from files and create and write files. using files a xul application or extension may access files on disk, and either read or write to files. a file is accessed via a file object. to g...
Moving, Copying and Deleting Files - Archive of obsolete content
es ] important note: the pages from the file and stream guide use the io object (nsiscriptableio), which was not available in any released version of the platform (pending some fixes). there are alternative xpcom apis you can use, your help in updating this pages to use the supported api is very much welcome! other documentation on files and i/o not using the unavailable nsiscriptableio apis: code snippets: file i/o, open and save dialogs, reading textual data, writing textual data, list of file-related error codes. there are several methods of the nsifile object which may be used to move and copy files on disk. nsifile.copyto() is used to copy a file, while nsifile.moveto() is used to move files. nsifile.remove() may be used to delete a file. copying a file nsifile.copyto() is used to ...
How to implement a custom XUL query processor component - Archive of obsolete content
} else if (leftvalue > rightvalue) { return 1; } else { return 0; } } }; var components = [templatequeryprocessor]; function nsgetmodule(compmgr, filespec) { return xpcomutils.generatemodule(components); } our sample query processor is very simple. a few explanatory notes: we are using a the getbindingfor rather than getbindingobjectfor to simplify the code. the variable passed into getbindingfor still has the "?" prepended to it, so be sure to handle it appropriately. we are not handling any datasources, but instead hard code the datasource in the component. you could easily extend this sample to handle multiple datasources by checking the datasources value in getdatasource and initializeforbuilding. we do not make use of any <query/> or <rule/> ...
addTab - Archive of obsolete content
Archive › Mozilla › XUL › Method › addTab
page with the specified url. the rest of the parameters are optional. the row of tabs will appear if needed. firefox 3.6 note the second form of this method was added in firefox 3.6; it allows you to specify the parameters by name, in any order. it also adds the relatedtocurrent parameter; firefox uses this to decide whether the new tab should be inserted next to the current tab. see code snippets: tabbed browser for examples. see preprocessing post data for preparing postdata out of a string. ...
advance - Archive of obsolete content
Archive › Mozilla › XUL › Method › advance
« xul reference home advance( pageid ) return type: no return value call this method to go to the next page. this is equivalent to pressing the next button. the canadvance property must be set to true for the page to be changed. the code in the onwizardnext attribute is called before the page is changed. the pageid argument allows you to specify the index of the page to which to jump. supply null as the argument to go to the next page in the sequence. ...
cancel - Archive of obsolete content
Archive › Mozilla › XUL › Method › cancel
...
extra1 - Archive of obsolete content
Archive › Mozilla › XUL › Method › extra1
...
extra2 - Archive of obsolete content
Archive › Mozilla › XUL › Method › extra2
...
goTo - Archive of obsolete content
Archive › Mozilla › XUL › Method › goTo
...
rewind - Archive of obsolete content
Archive › Mozilla › XUL › Method › rewind
...
ContextMenus - Archive of obsolete content
('open link'). on platforms that support it, it will be marked as a default item. on other platforms, the attribute will just be ignored and the menuitem will be displayed normally. naturally, it only makes sense to have one default item per context menu. note that the default attribute just affects how the item is displayed, it performs no other function itself. you will still need to associate code with the element to handle the default operation. menu separators to group menu items together for better visual clarity, use a menu separator. <menuseparator/> child context menus sometimes it may be convenient to place the menupopup for the context menu as a child of the element the menu is associated with instead of referring to the menupopup by id. this may be useful, for example, when ...
Special per-platform menu considerations - Archive of obsolete content
u items which open the application preferences and which quit the application. this can be accomplished by ensuring that certain common ids are set for the menu items that need to be placed on the application menu. on the mac, these menu items will be moved onto the application menu, but on other platforms, they will be left in their original locations. this makes it easier to write the same xul code for all platforms. here is a list of the menu item ids which are automatically handled. menu_filequitseparator the separator just before the quit/exit item. menu_filequititem the item which exits the application. menu_prefsseparator the separator just before the preferences/options item. menu_preferences the item which opens the application prefere...
Positioning - Archive of obsolete content
enpopup(label, "end_before", 0, 0, false, false); note that the position has been set to 'end_before', as above. when both are used, the value supplied to openpopup overrides the attribute. however, if the attributesoverride argument to openpopup (the last argument, false in the example above) was true, the attribute would override the value supplied to openpopup. this allows the script and xul code to coordinate in different ways as to how the popup should be opened. positioning using coordinates a popup can be positioned further using the x and y arguments to openpopup. after the popup is positioned using the anchor, the x and y arguments may be used to offset the popup by a certain distance. the section on the openpopup method provides an example of this. if a menupopup, panel or toolt...
emptyText - Archive of obsolete content
...
Additional Navigation - Archive of obsolete content
the result is kept. like the first result, there is no arc for the third photo, so it is also removed. the resulting data will look like the following: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg) here is the example. naturally, we will need to add a binding for the ?title variable if we wish to display it, or we could just hardcode it since we know the value will be 'canal'. usually you won't be filtering on a title though--you would instead filter on a value that acts like a type. there has to be at least one variable used in a triple in either the subject or the object attributes, or both. you can't have a triple with no variables. that's not an issue though, since it wouldn't be particularly useful. also, you cannot use...
Attribute Substitution - Archive of obsolete content
er, a bug can make this appear to not work at times. recall that the template builder doesn't load the datasource before processing a template. as the datasource loads, the query and rules are examined with the new data as it arrives. this causes rules to create matches as the data loads. however, variables determined from a binding are evaluated using a much simpler process. the bug is that this code path for bindings doesn't handle the textnode element properly. thus, if you use a variable set in a binding, you must ensure the datasource is loaded before the template is built, or just rebuild the template. another possibilty is to rearrange the rdf such that the values, in this example, the descriptions, are specified before the containers. this issue is fixed in firefox 3 (mozilla 1.9) and ...
RDF Modifications - Archive of obsolete content
this involves a third type of observer involved in a template builder, an nsirdfobserver, used to listen for modifications to the rdf datasource. ...
Rule Compilation - Archive of obsolete content
builder will be invoked and the content will be generated. does this mean that templates cannot be used inside hidden areas of the ui? no, you can still do that. changing the hidden state of an element isn't the only way to cause content to be generated. calling a dom api which needs to get at the generated content will cause the template builder to generate output. for example, just calling the code like the following on the hidden vbox above will start off the template builder. var length = vbox.childnodes.length; this request to return the number of children of the vbox will make the template builder process the query and output content. once done, the correct length can be returned. all of this is transparent to the xul developer. when the template builder decides to start generation is ...
Simple Query Syntax - Archive of obsolete content
can use the simple syntax. here is what it might look like: <template> <vbox class="box-padded" uri="rdf:*"> <image src="rdf:*"/> <label value="rdf:http://purl.org/dc/elements/1.1/title"/> </vbox> </template> there is no <query> or <action> element used. instead, the builder uses a default query, and the action is placed directly inside the <template> element. you can see that this code is much simpler than the full syntax. to understand how this works, let's examine how the builder processes a simple query. first, it evaluates the default query as above, except that no variables are used, or at least, not ones that are used externally. in reality, the builder could be considered to convert a simple query into an extended query, so that it can be processed in the same way. after...
Sorting Results - Archive of obsolete content
the arguments to the sort method specify the root node (the listbox), the sort key and the sort direction. « previousnext » ...
Toolbars - Archive of obsolete content
a look at the events that are sent during toolbar customization; you can use these to be kept aware of changes to toolbars. creating toolbar buttons how to use overlays to add toolbar buttons to mozilla applications. custom toolbar button another example of how to create a toolbar button, complete with a sample extension you can download and try. code snippets: toolbar code snippets that are helpful when working with toolbars. community view mozilla extension development forums... mailing list newsgroup rss feed #extdev irc channel mozillazine forum about:addons newsletter mozilla's web-tech blog mozdev project own...
Adding HTML Elements - Archive of obsolete content
with the description or label element. you should use these elements when you can. you can also add labels to controls either by using the html label element, or you can simply put the text inside another html block element (such as p or div) as in the example below. example 1 : source view <html:p> search for: <html:input id="find-text"/> <button id="okbutton" label="ok"/> </html:p> this code will cause the text 'search for:' to be displayed, followed by an input element and an ok button. notice that the xul button can appear inside the html elements, as it does here. plain text will only be displayed when placed inside an html element that would normally allow you to display text (such as a p tag). text outside of one will not be displayed, unless the xul element the text is inside a...
Box Objects - Archive of obsolete content
« previousnext » this section describes the box object, which holds display and layout related information about a xul box as well as some details about xul layout. about mozilla layout mozilla divides things into two sets of trees, the content tree and the layout tree. the content tree stores the nodes as they are found in the source code. the layout tree holds a different tree of nodes for each individual component that can be displayed. the layout tree holds the structure as the nodes are expected to be displayed there is not necessarily a one to one relationship between content and layout nodes. some content nodes may have several layout objects, for example, each line of a paragraph has a separate layout object. conversely, some content nodes have no layout objects at all...
Creating a Skin - Archive of obsolete content
a clip region for the image. you set the property to a position and size within an image and the button will display only that section of the image. this allows you to use the same image for multiple buttons and set a different region for each one. when you have lots of buttons, with states for hover, active and disabled, this saves space that would normally be occupied by mutliple images. in the code above, we use the same image for each button, but set a different image region each one. if you look at this image (btn1.gif), you will notice that it contains a grid of smaller images, each one 16 by 16 pixels. the -moz-box-orient property is used to orient the button vertically, so that the image appears above the label. this property has the same meaning as the orient attribute. this is conve...
Creating a Wizard - Archive of obsolete content
if it returns false, then the wizard does not close, which might occur if the function savedoginfo() encountered invalid input, for example. there are also related onwizardback, onwizardnext and onwizardcancel attributes, which are called when the back, next and cancel buttons are pressed respectively. these functions are called regardless of which page is currently displayed. to have different code called depending on which page you are on, use the onpagerewound or onpageadvanced attributes on a wizardpage element. they work in a similar way to the other functions except that you can use different code for each page. this allows you to validate the input entered on each page before the user continues. a third option is to use the onpagehide and onpageshow attributes on the wizardpage eleme...
Creating an Installer - Archive of obsolete content
r"] = "calendar.xpi"; installtrigger.install(xpi,donefn); first, we define a callback function donefn() which will be called when the install is complete. you can name the function whatever you like of course. this function has two arguments. the first is the name of the package that was just installed. this is important if you are installing multiple components. the second argument is a result code. if the result is 0, the installation completed successfully. if the result is non-zero, an error occured and the value is an error code. the function donefn() here just displays an alert box to the user. next, we create an array xpi which will hold the name (calendar) and url (calendar.xpi) of the installer. you can add an additional similar such line for each package you wish to have installed...
Features of a Window - Archive of obsolete content
as in html, you can use the window interface's open() method loads the specified resource into the browsing context (window, <iframe> or tab) with the specified name. ...
Focus and Selection - Archive of obsolete content
ements the nsidomxulcommanddispatcher interface. this interface also provides a number of other methods which may be useful. platform specific behaviors mac os x there is a preference called "full keyboard access" (fka). note that xul adheres to this. this means that when the fka preference is off, only textboxes and lists/trees are focusable with the keyboard, as well as from your code using focus(). handling text changes there are two events that can be used when the user changes the value of a textbox. naturally, these events will only be sent to the textbox that has the focus. the input event is fired whenever the text is modified in the field. the new value will be different than the old value. you may want to use this event instead of using key events, as some keys suc...
Install Scripts - Archive of obsolete content
s and only install updated files, or perhaps you wish to apply patches to existing files. the install script is even flexible enough to allow you to uninstall files. for this reason, installers include an install script to handle the installation process. the installer script must be called install.js and must be placed at the top level of the installer archive. the script will contain javascript code which calls a number of install functions. in an html document, or a xul document, the window object is the root global object. that means that you can call the methods of the window object with the qualifier before it, which means that window.open() can simply be written open(). in an install script, there is no associated window, however the global object will be an install object which contain...
Introduction to RDF - Archive of obsolete content
ever, it would be inconvenient to do so by entering the data directly into the xul file. it would make it very difficult to modify the bookmarks if they were directly in the xul file. the way to solve this is by using rdf datasources. rdf (resource description framework) is a format that can be used to store resources such as bookmarks or mail. alternatively, data in other formats can be used and code written that will read the file and create rdf data from it. this is how mozilla works when it reads data such as bookmarks, the history or mail messages. mozilla provides datasources for this common data so that you can easily use them. you can use any of the provided rdf datasources to populate trees with data or you can point to an rdf file stored in xml which contains the data. this makes it ...
Manipulating Lists - Archive of obsolete content
roperty instead. or, use the selectedpanel property to get the selected panel, that is, return the content associated with the tab. changing the selection all of the selection related properties described above may also be assigned a new value to change the selection. in the next example, the selectedindex property of a radiogroup element is changed based on the value entered in a textbox. this code isn't foolproof though; for example it doesn't check if the value entered is out of range. you will want to make sure that you add this kind of error checking. example 3 : source view <script> function doselect(){ var val = document.getelementbyid('number').value; val = number(val); if (val != null) document.getelementbyid('level').selectedindex = val - 1; } </script> <hbox align="ce...
Open and Save Dialogs - Archive of obsolete content
seperated list of file masks. you can add more masks or fewer masks as needed. you can call appendfilter as many times as necessary to add additional filters. the order you add them determines their priority. typically, the first one added is selected by default. getting the selected file finally, you can show the dialog by calling the show() function. it takes no arguments but returns a status code that indicates what the user selected. note that the function does not return until the user has selected a file. the function returns one of three constants: returnok - the user selected a file and pressed ok. the file the user selected will be stored in the file picker's file property. returncancel - the user pressed cancel. returnreplace - in the save mode, this return value identifies th...
Styling a Tree - Archive of obsolete content
an return a string of space-separated property names from these functions. getrowproperties : function(row){ return ''} getcolumnproperties : function(column,columnelement){ return ''} getcellproperties : function(row,column){ return ''} let's look at an example of changing a specific cell. let's make every fourth row have blue text, using the example from a previous section. we'll need to add code to the getcellproperties() function, to add a property 'makeitblue' for cells in every fourth row. (we don't use getrowproperties() as the text color will not be inherited into each cell.) prior to gecko 22 the properties object that is passed as the last argument to the getcellproperties() is an xpcom object that implements nsisupportsarray. it is really just an xpcom version of an array. it co...
Tabboxes - Archive of obsolete content
lly stacked. next, adjust the tabbox so it has horizontal orientation. this will make the tabs appear to the left of, not above, the tab pages. note that changing the orientation of the tabpanels element will have no effect, since the tabbed pages are layered on top of each other. you can place the tabs on the right or bottom side by moving the tabs element to after the tabpanels element in your code. alternatively, you could set the dir attribute to reverse on the tabbox. however, you should probably leave the tabs on top, otherwise they might not look very good under particular themes. adding tabs to our find files dialog let's add a second panel to the find files dialog. we'll create an options tab (and select it by default) that will contain some options for searching. this may not be ...
Templates - Archive of obsolete content
provided with mozilla such as bookmarks, history and mail messages. more details on these will be provided in the later section. usually, elements such as treeitems and menuitems will be populated with data. however, you can use other elements if you want although they are more useful for specialized cases. nevertheless, we'll start with these other elements because trees and menus require more code. to allow the creation of elements based on rdf data, you need to provide a simple template which will be duplicated for each element that is created. essentially, you provide only the first element and the remaining elements are constructed based on the first one. the template is created using the template element. inside it, you can place the elements that you want to use for each constructed...
Tree Selection - Archive of obsolete content
. it takes a row index as an argument and returns true if that row is selected. alert(tree.view.selection.isselected(3)); modifying the tree selection the selection object has a number of functions which may be used to change the selection. the simplest function is the select() function, which deselects any rows that are currently selected and selects one specific row. for example, the following code will select the row at index 5: tree.view.selection.select(5); note that you should not just change the tree's currentindex property to change the selection. instead, you should use the selection's select function as in the example above. you can select all rows with the selectall() function. note that rows nested inside containers that are not open will not be selected. naturally, this will onl...
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
n the shift or control keys and clicking additional rows. to disable multiple selection, place a seltype attribute on the tree, set to the value single. with this, the user may only select a single row at a time. add a tree to our find files example let's add a tree to the find files window where the results of the search would be displayed. the tree will use a content tree view. the following code should be added in place of the iframe. <tree flex="1"> <treecols> <treecol id="name" label="filename" flex="1"/> <treecol id="location" label="location" flex="2"/> <treecol id="size" label="size" flex="1"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="mozilla"/> <treecell label="/usr/local"/> <treecell label="2520 bytes"/> ...
Using Spacers - Archive of obsolete content
see that the elements have remained where they started. none of them have been moved or resized even though the window has more room in it. let's see what happens when a spacer is added between the text box and the find button. by adding a spacer and resizing the window, you can see that the spacer has expanded to fill the space. the buttons have been pushed over. our find file example the code to add a spacer is shown below. insert it just before the find button. <spacer flex="1"/> <button id="find-button" label="find"/> more about flexibility xul lays out elements on a window by calculating suitable widths and heights for the elements and then adding space where they are flexible. unless you specify information about the width and height of an element, the default size of an elem...
Using the standard theme - Archive of obsolete content
ur widgets (apart from the standard global skin) you can take two different routes. you can either add multiple <tt>xml-stylesheet</tt> processing instructions to your xul file, or create an <tt>@import</tt> chain. no matter which approach you choose, do not forget to register your custom skin in the <tt>chrome.manifest</tt>. note that you can also mix these two approaches, although it makes your code more readable when sticking to only one way. multiple <tt>xml-stylesheet</tt> processing instructions simply add one <tt>xml-stylesheet</tt> processing instruction for every style sheet you want to associate with your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="chrome://myextension/skin/custom.css" type="text/css"?> <tt>@import</tt> chains f...
Window icons - Archive of obsolete content
...
XUL Parser in Python/source - Archive of obsolete content
import sys, glob, xmllib import os, re el_list = {} w = open('res.html', 'w') # unfortunately, i had to put this hack in here to suppress the printing out of the resolved namespace: # "xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul window", etc. ...
XUL accessibility tool - Archive of obsolete content
ile, web url, or currently open window from the file menu to generate a xul report for that document. be aware that the report might take a little while to be ready depending on the complexity of the application being analyzed and the speed of your machine. ...
XML - Archive of obsolete content
, tools, and methodologies. there are many times, for example, when you may use javascript tricks to add extra behavior. but the necessary tradeoff for xul's flexibility is a lack of implicit functionality -- the lack ofintuition, you might say, that xul has in interpreting what it is you want. in order to provide flexibility to you as adesigner of interfaces, xul offers no flexibility to you as acoder. you must be very careful about your syntax, and in particular about these four cardinal rules of xul: all events and attributes must be written in lowercase. unlike html, xul is very sensitive to case. all of the events and attributes -- even the javascript event listeners normally formatted in the javascript world with uppercase verbs (e.g., onclick, onload) -- must be lowercase or they ...
button - Archive of obsolete content
> menu { max-width: none; } dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the elements are placed left to right or top to bottom in the order they appear in the xul code. reverse for scales, the scale's values are ordered from right to left (for horizontal scales) or from bottom to top (for vertical scales). for other elements, they are placed right to left or bottom to top. this is reverse of the order in which they appear in the xul code. disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the el...
colorpicker - Archive of obsolete content
ype: color string the currently selected color. this is modified when the user selects a color. you can assign a string of the form #rrggbb to this property to change the selected color. overview an onchange attribute is an event listener to the object for the event change. a change event is fired in different ways for different xul input elements as listed below: onchange type: script code textbox when enter key is pressed radio/check box when the state is changed select list when the selected item is changed what is accessible the script context at this point can only access the following things: global values/functions i.e. window, document, or any of the functions/objects/variables bound to the window object event object exampl...
commandset - Archive of obsolete content
or you can use your own events. you can send a custom event by calling the updatecommands method of the command dispatcher. focus: occurs when the focused element changes. select: occurs when the selected text changed. clipboard: occurs when the clipboard is changed. undo: occurs when the undo buffer is changed. oncommandupdate type: script code this event occurs when a command update occurs. you would use this to update the disabled status of items. targets type: comma-separated list of element ids a comma-separated list of element ids that the command updater will update upon. if this attribute is not specified, or you set it to the value '*', all elements are valid. the command update will only occur w...
dialog - Archive of obsolete content
xul reference home [ examples | attributes | properties | methods | related ] this element should be used in place of the window element for dialog boxes. the buttons attribute may be used to set which buttons should appear in the dialog box. these buttons will be placed in the correct locations for the user's platform. more information is available in the xul tutorial and dialogs and prompts (code snippets). attributes buttonaccesskeyaccept, buttonaccesskeycancel, buttonaccesskeydisclosure, buttonaccesskeyextra1, buttonaccesskeyextra2, buttonaccesskeyhelp, buttonalign, buttondir, buttondisabledaccept, buttonlabelaccept, buttonlabelcancel, buttonlabeldisclosure, buttonlabelextra1, buttonlabelextra2, buttonlabelhelp, buttonorient, buttonpack, buttons, defaultbutton, title properties ...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
ght or maxwidth. the new behavior aligns more with the html <img> element and shrinks both the width and height down proportionally. attributes onerror, onload, src, validate properties accessibletype, src style classes alert-icon, error-icon, message-icon, question-icon examples <image src='firefoxlogo.png' width='135' height='130'/> attributes onerror type: script code this event is sent to an image element when an error occurs loading the image. image.onload type: script code this event handler will be called on the image element when the image has finished loading. this applies whether the image is applied via the src attribute or the list-style-image style property. if you change the image, the event will fire again when the new image loads. this e...
notificationbox - Archive of obsolete content
indow (usually just window), and notifywindow is the web content window for the tab you want to find the notification box for. also it is possible to call function with the same name (they are different) of global object gbrowser: notifybox = gbrowser.getnotificationbox() examples <notificationbox flex="1"> <browser src="http://www.mozilla.org"/> </notificationbox> there is a more complex code available in the code snippets area. properties currentnotification, allnotifications, notificationshidden methods appendnotification, getnotificationwithvalue, removeallnotifications, removecurrentnotification, removenotification, removetransientnotifications, attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs...
preferences - Archive of obsolete content
flex, height, hidden, id, , , left, , maxheight, maxwidth, menu, minheight, minwidth, , , , , , , observes, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods void firechangedevent(in domelement preference); creates and dispatches a changed (non-bubbling) event to the specified preference element. also executes code specified in onchanged attribute of the element. see also the description of change event of <preference>. void observe(in nsisupports asubject, in string atopic, in wstring adata); nsiobserver method used internally to react to changes to preferences listed as children of this element. inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition...
prefpane - Archive of obsolete content
or left out, no image appears. the position of the image is determined by the dir and orient attributes. label type: string the label that will appear on the element. if this is left out, no text appears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. onpaneload type: script code code defined here is called when the pane has been loaded, much like the load event for a window. selected type: boolean this attribute will be set to true for the currently selected prefpane. to change the selected pane, use the prefwindow's showpane method. src type: uri the uri of the overlay contents of preference pane. if this is not ...
scale - Archive of obsolete content
Archive › Mozilla › XUL › scale
orient="vertical"/> attributes dir type: one of the values below the direction in which the child elements of the element are placed. normal for scales, the scale's values are ordered from left to right (for horizontal scales) or from top to bottom (for vertical scales) for other elements, the elements are placed left to right or top to bottom in the order they appear in the xul code. reverse for scales, the scale's values are ordered from right to left (for horizontal scales) or from bottom to top (for vertical scales). for other elements, they are placed right to left or bottom to top. this is reverse of the order in which they appear in the xul code. disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the el...
script - Archive of obsolete content
a script to be used by the xul window. you should usually put scripts in a separate file pointed to by the src attribute, but you may also place the script inline inside the opening and closing script tags. more information is available in the xul tutorial. attributes src, type examples <script src="test.js"/> <script src="http://example.com/js/test.js"/> <script> function foo(){ // code } </script> attributes src type: uri the uri of the script. type type: language content type the language of the script. usually, you would set this to application/javascript. note: if the javascript file is in chrome://, setting this attribute to application/javascript will always use the latest available javascript version. if you omit this attribute, the default (and old...
tab - Archive of obsolete content
Archive › Mozilla › XUL › tab
o the panel at the corresponding index in the tabpanels element that the tab is in its tabs container. however, if this attribute is used, this behavior is overridden, and the tab will always be linked to a specific panel. this might be used to avoid duplication by linking several tabs to one panel with slight differences to the content adjusted in the select event. oncommand type: script code this event handler is called when the command is activated. this occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. pending type: boolean this attribute is set to true if the tab is currently in the process of being restored by the session store service. once the tab is restored, this attribute is removed. you can determine if a tab...
tabs - Archive of obsolete content
Archive › Mozilla › XUL › tabs
ontrols. using it with an anchor tag (an <a> link) will have no effect. the element will, however, still respond to mouse events. to enable the element, leave this attribute out entirely. visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. onclosetab type: script code this script will be called when the close tab button is clicked. onnewtab not in firefox type: script code this script will be called when the new tab button is clicked. onselect type: script code this event is sent to the tabs element when this tab is changed. selectedindex type: integer gets and sets the index of the currently selected panel. the first item is at i...
treecol - Archive of obsolete content
n't take effect. */ list-style-image: none; } treechildren::-moz-tree-checkbox(checked){ /* css for checked cells. cbox-check.gif isn't available in firefox 1, 2, and 3 on mac os x, so you should specify a url to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } for example: create a css file. copy and paste the code above and link the css file to your xul file. reload the page to see the checkbox. if you want, you can also style the tree using css. attributes crop type: one of the values below if the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. an ellipsis will be used in place of the cropped text...
Building XULRunner - Archive of obsolete content
s on how to get sources and set up build prerequisites. by default, xulrunner is built with javaxpcom support; the build system must be able to find an appropriate jdk on the system; see the instructions on building javaxpcom for more details. if you do not want to build javaxpcom support, specify --disable-javaxpcom in your configuration. on mac, xulrunner requires mac os x 10.3 or higher and xcode 1.5 or higher to build properly. the runtime requirement is mac os x 10.2. a basic minimal mozconfig which will build a release configuration of xulrunner is: mk_add_options moz_co_project=xulrunner mk_add_options moz_objdir=@topsrcdir@/obj-xulrunner ac_add_options --enable-application=xulrunner #uncomment the following line if you don't want to build javaxpcom: #ac_add_options --disable-javax...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
the xulrunner sdk, you'll need a .mozconfig of your own. here's an example for mccoy: # options for client.mk. mk_add_options moz_co_projects=browser mk_add_options moz_objdir=@topsrcdir@/../mccoybase # options for 'configure' (same as command-line options). ac_add_options --with-libxul-sdk=/path/to/xulrunner-sdk ac_add_options --enable-application=mccoy you still need to get the mozilla source code and put your project in a subdirectory underneath the mozilla root. of course, you only really need the mozilla build system since all the other mozilla files are in the xulrunner sdk, and there is a bug filed to make it possible to check out the build system only. okay, okay, can i build it now? sorry, no. first you're going to have to write a whole bunch of makefiles and stuff. oh, and actually...
Custom app bundles for Mac OS X - Archive of obsolete content
contents/ info.plist (application bundle properties are specified in this xml file.) pkginfo (this is a simple text file and is created along with the info.plist file) macos/ (the macos folder will contain your xulrunner executable) xulrunner (this is the xulrunner stub) resources/ (this is where you place your xul application code and support files) application.ini (xulrunner-related application settings) example.icns (this is the icon which will be used by your application bundle) chrome/ content/ example.xul (this directory contains your application's chrome) example.manifest defaults/ ...
Deploying XULRunner - Archive of obsolete content
s.dll" and/or "mozcrt19.dll" from the xulrunner directory to the root directory. this should be fixed with xulrunner 11.0 with xulrunner 11.0 you may need to copy "gkmedias.dll" from the xulrunner directory to the root directory mac os x on mac os x, the exact layout of your application bundle depends on which version of xulrunner you're using. xulrunner 39 and later due to mac os x code signing rules and how they interact with the design of xulrunner (see bug 1105044 for the inside scoop), starting with xulrunner 39 the xulrunner library files are no longer able to reside in a xulrunner framework directory. instead, the library files are placed directly into the macos directory alongside the main executable file. here's how the entire application bundle looks: myapp.app/ ...
Dialogs in XULRunner - Archive of obsolete content
aption label="select favorite fruit"/> <radiogroup> <radio id="1" label="oranges because they are fruity"/> <radio id="2" selected="true" label="strawberries because of color"/> <radio id="3" label="bananna because it pre packaged"/> </radiogroup> </groupbox> </dialog> xul window elements have a special method to open dialogs, called window.opendialog(). here is the code needed to open a dialog: function opendialog() { window.opendialog("chrome://basicapp/content/dialog.xul", "newdlg", "modal"); } the resulting dialog looks like this on windows 2000, and will look similar on other operating systems: the first thing that caught my eye about dialog is the button-related attributes on the element. in an effort to make things easier for developers and more co...
Using LDAP XPCOM with XULRunner - Archive of obsolete content
. this is due to the fact that the native ldap library files are not found by the xulrunner process. the solution is to use the bsmedberg stub, described in using dependent libraries in extension components: the component library is just a loader of the real library and all its dependencies, so as all the needed libraries are loaded. create a subdirectory extensions/ldapstub in the mozilla source code directory, containing two files, makefile.in and ldapstubloader.cpp: makefile.in: # copyright (c) 2005 benjamin smedberg <benjamin@smedbergs.us> depth = ../.. srcdir = @srcdir@ topsrcdir = @top_srcdir@ vpath = @srcdir@ include $(depth)/config/autoconf.mk module = mozldapstub library_name = mozldap_stub is_component = 1 force_shared_lib = 1 requires = \ xpcom \ string \ $(null) cppsrcs = l...
What XULRunner Provides - Archive of obsolete content
activestate uses pyxpcom in their products...
XUL Application Packaging - Archive of obsolete content
egal values are 1 and 0. optional - default is 0 note: this option does not add menu items that make the extension/theme manager available in the ui; that is the responsibility of the application author. example: enableextensionmanager=1 enableprofilemigrator specifies whether, when the application is launched for the first time and there are no profiles, to enable profile migration code through the nsiprofilemigrator interface. legal values are 1 and 0. optional - default is 0 note: the application author is responsible for implementing the nsiprofilemigrator interface; if an implementation is not found no migration will be performed. example: enableprofilemigrator=1 the [crash reporting] section using crash reporting in a xulrunner application ...
Mozprocess - Archive of obsolete content
sshandler utilizes a contained subclass of subprocess.popen, process, which does the brunt of the process management. basic usage: process = processhandler(['command', '-line', 'arguments'], cwd=none, # working directory for cmd; defaults to none env={}, # environment to use for the process; defaults to os.environ ) exit_code = process.waitforfinish(timeout=60) # seconds see an example in https://github.com/mozilla/mozbase/b...profilepath.py processhandler may be subclassed to handle process timeouts (by overriding the ontimeout() method), process completion (by overriding onfinish()), and to process the command output (by overriding processoutputline()). todo document improvements over subprocess.popen.kill ...
xbDesignMode.js - Archive of obsolete content
you may not use this file except in compliance with * the license. you may obtain a copy of the license at * http://www.mozilla.org/mpl/ * * software distributed under the license is distributed on an "as is" basis, * without warranty of any kind, either express or implied. see the license * for the specific language governing rights and limitations under the * license. * * the original code is netscape cross browser design mode code. * * the initial developer of the original code is * netscape communications corporation. * portions created by the initial developer are copyright (c) 2003 * the initial developer. all rights reserved. * * contributor(s): doron rosenberg <doron@netscape.com> (original author) * * * * ***** end license block ***** */ /* xbdesignmode ...
2006-10-26 - Archive of obsolete content
nd followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup. firefox killer features suggestion john describes his suggestions for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. bug in firefox when import passwords from seamonkey a possible bug find - perhaps a version error instead? there should be a 'changes' faq a user suggests that a faq page be made for changes, since the same two questions keep coming up. nsialertsservice unde...
2006-10-27 - Archive of obsolete content
nd followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup. firefox killer features suggestion john describes his suggestions for "killer features" for firefox. debug minefield on intel mac an inqury about how to debug minefield on an intel mac. rebuild firefox after modifying source code an inqury about how to rebuild the code after making a minor change - the user is unfamiliar with how to use the command prompt. bug in firefox when import passwords from seamonkey a possible bug find - perhaps a version error instead? there should be a 'changes' faq a user suggests that a faq page be made for changes, since the same two questions keep coming up. nsialertsservice unde...
2006-11-03 - Archive of obsolete content
" within the status bar of the browser without logging into google. request to add option for removal of firefox profiles during setup or uninstall a user suggests an option to remove profiles during setup or uninstall. does firefox provide any classes/objects or events to windows wmi ? a user asks if firefox provides any classes/objects or events to windows wmi. no replies yet. source code for the nsinstall contained in moztools a user asks for advice about building nsinstall on windows. no replies yet. picking an alternate search engine for a particular search large discussion about how the search engine could be imporved. firing pageshow/pagehide when users change tabs discussion about using events that could be fired when the user changes a tab. ff 1.5 hiding a use...
2006-11-04 - Archive of obsolete content
ing "adsense earning" within the status bar of the browser without logging into google. to add option for removal of firefox profiles during setup or uninstall a user suggests an option to remove profiles during setup or uninstall. firefox provide any classes/objects or events to windows wmi ? a user asks if firefox provides any classes/objects or events to windows wmi. no replies yet. code for the nsinstall contained in moztools a user asks for advice about building nsinstall on windows. no replies yet. an alternate search engine for a particular search large discussion about how the search engine could be imporved. pageshow/pagehide when users change tabs discussion about using events that could be fired when the user changes a tab. 1.5 hiding a user adds their "two c...
2006-11-17 - Archive of obsolete content
one this week. discussions mozilla access to http? to snipurl? user is looking for advice how to access http or snipurl. no replies as of yet. firefox 2.0 - window.focus() user questions where the change in behaviour in window.focus() is a bug or was intented. firefox 2.0 javascript popup issue user seeks advice about a line of javascript code that worked in firefox 1.5.0.x, but not in firefox 2.0 balloon help user inquires if anyone can explain how to disable the balloon help in firefox 2.0. two questions: (1) launching a separate intance of firefox.exe, and (2) programmatically closing a window user has two questions about using adobe flex builder debugger in firefox 2.0. meetings n...
2006-10-06 - Archive of obsolete content
red before release can be issued. hence, they are looking for a mac user to test out the new features by building a mac.rdf file with all of the various .mac account properties mentioned in the document here. discussions is thunderbird using a valid w3c coding? peter lairo requested someone who are knowledgeable in w3c standards to confirm if the use of <blockquote type="cite"> is valid w3c code. q & a q: walt experienced an unusual behaviour in his build and wanted to perform an experiment to figure out the problem, but he couldn't find the mozilla.org's config file. a: robert helmer pointed out the mozilla.org's config file could be found here and to look for -->mozconfig<---------------------------------------- -->end mozconfig<---------------------------------------- updated...
2006-10-27 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - october 21-27, 2006 announcements none for this week. discussions effect of eudora/thunderbird re-write joes is voicing a concern about the recent announcement regarding the eudora/thunderbird rewrite: "is thunderbird destined to become a hybrid of the existing code and eudora?". jonathan pritchard has clarified that announcement does not mean thunderbird will be changing direction, just certain areas of development that are of interest to the eudora developers will have more attention paid to them. calling tb with a specific message to be displayed there's a new question by guenter about calling tb from an external program (eg. firefox) to display a message. meetings none for this week. ...
2006-11-03 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - october 28 - november 03, 2006 announcements none for this week. discussions what is the 'lastmodifieddate' item used for in tb? there are some code example given and also further discussion on lastmodifieddate. tb storage-idea tb is planning to change from mbox-format storage to database-based storage. however, user wonder both storage method could exist in tb at the same time without crashing. suggestion made for e-mail popup it suggested that the e-mail popup duration should depends on number of messages and examples of this idea is provided. xul overlay question -- how to replace an existing element? no respond thus far. links in tb is not sent to firefox directly cédric corazza provided a code solution for this problem. ...
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - november 4-10, 2006 announcements none for this week. discussions violation of smtp protocol in thunderbird hector reports two bugs: thunderbird ignores the smtp protocol state machine by ignoring the 501 response codes. this has been filed as bug 360118. thunderbird doesn't seem to have an option to set the client domain name (elho/helo). this is already addressed in bug 244030. interfacing with thunderbird mark bannister is looking for directions on interfacing thunderbird with their project management database. guenter has provided some sample code using the 'mailto:' method. meetings calendar project weekly status meeting - 2006/11/08 17:00 utc (meeting notes) calendar project weekly qa chat - 2006/11/09 16:30 utc (meeti...
2006-10-06 - Archive of obsolete content
ch (for sunbird 0.3) and mozilla_1_8_branch. sunbird/lightning localization update you need to update your localization if you want your locale to ship with lightning 0.3 or sunbird 0.3. mozillatranslator 5.13 rfes new version of mozillatranslator will be relaesed in a few weeks. calendar localization update rc1 for sunbird 0.3 is out now and ready for testing. l10n locked down - ff2 rc2 code freeze 9/29/2006 at 9am pdt the l10n repository is locked down. discussions status update fx2 status update for firefox 2. meetings none for this week. authors paul yanchun gu (gpaul) aditya nanda kuswanto(vipers101) ...
2006-10-13 - Archive of obsolete content
ary: mozilla.dev.l10n - october 13, 2006 announcements seamonkey 1.0.5 he-il seamonkey 1.0.5 in hebrew was released a while ago firefox 2 rc2 is out firefox 2 rc2 is out, to download click here sunbird_0_3_release tag being created sunbird_0_3_release tag being created seamonkey 1.1 localization freeze and beta upcoming there are no open blockers left. l10n freeze on seamonkey 1.1 code is imminent in the next days, as well as beta release. do early testing using code from this link. discussions mozillatranslator 5.13 rfes mozillatranslator 5.13 is ready to be released in a few weeks. author is declaring rfe (request for enhancement). a few bugs have been listed. meetings none for this week. authors paul yanchun gu (gpaul) aditya nanda kuswanto(vipers101) ...
2006-10-06 - Archive of obsolete content
1.8.0.8 schedule. dbaron and chris ilias respond with relative dates but still no schedule. rc2 status schrep asks for any final things standing in the way of rc2. rc2 starts spinning and en-us builds are annoucned. beltzner says that (as per bon echo status meeting) that rc2 is going to be re-spun to fix some final bugs that were regressed and patches that were just landed. reminder - ff2 rc2 code freeze 9/29/2006 at 9am pdt schrep started a discussion of bugs that need to be fixed for the ff2 rc2 code freeze to go ahead. meetings weekly status meeting - 10/02/2006 - (last meeting notes) bon echo status meeting - 10/03/2006 - (last meeting notes) ...
2006-11-10 - Archive of obsolete content
lags...o track bugs that are not strictly blockers, but are wanted as soon as possible" benjamin smedberg announced new rules for patches to toolkit from now on unit test must be provided with all patches. other important notes are contained in the link above firefox and thunderbird 1.5.0.8 were released firefox and thunderbird 1.5.0.8 were released on november 7, 2006 blocker nomination and code freeze for 1.5.0.9/2.0.0.1 blocker nomination is due on november 10. code freeze for these versions is on november 26 version numbering changes paul reed announced changes to the way version numbers are done for pre-releases. discussion version numbering changes some discussion about paul's announcement of version number changes meetings november 6 project status meeting (notes) novembe...
2006-11-17 - Archive of obsolete content
24. configure regeneration back up, but another outage tonight... preed reports that the machine with autoconf is back up. but there is another outage scheduled so the tinderboxen will be down early. mozilla scheduled downtime - 11/14/2006, 9:30pm - 1:00am pst a number of machines are going to go down. a full list can be found here mozilla/configure regeneration down preed says that the machine that does autoconf went down during a power outage. preed and it are working on it. ...
2006-12-01 - Archive of obsolete content
announcements governance topics mitchell baker announces that topics have been posted in the governance group. windows dde shell integration removal robert strong announces that a long standing bug in firefox's use of the windows dde shell integration code has been uncovered during vist os integration testing. firefox's use of this code has been removed but the windows dde shell integration code has been kept so that 3rd party apps depending on this code can stay working. firefox 1.5.0.9/2.0.0.1 update - we need help! jay patael calls for help getting the next update ff 1.5.x and 2.x. he requests blocker bug owners get their patches in asap and since check approval will be granted daily that they be ready to check their patches in as soon as they are approved. automatic configu...
2006-11-10 - Archive of obsolete content
in specified url's? james leigh points out that resources are available at o'reily, in the creating applications with mozilla section. benjamin smedberg has been "working on some xptcall refactoring which will allow us to expose xptcall via a frozen api (and c linkage)". he is looking for xptcall port maintainers to submit patches to bug 349002. matthew gertner wants to know if anyone has written code to paste images from the clipboard on platforms other than windows? as of the end of the week, there is no reply. harry is looking for help with create thread in javascript using nsithread. he wants to know how to create new threads using javascript for background download operations. neil deakin points out that "downloads and other network operations are always done in another thread so you shou...
2006-11-17 - Archive of obsolete content
special characters inquiry of how to use special characters in spidermonkey. ...
2006-11-10 - Archive of obsolete content
zilla.dev.tech.layout - november 4 - november 10, 2006 announcements none this week. discussions how to know the full height and width of a webpage discussion on how to determine the full height and width of a web page when embedding a browser into an application. using window.innerheight and window.scrollmaxy should resolve this issue. block images discussion on how where to change source code so that images could be blocked in mozilla. this can be defined within the nsicontentpolicy. applying site- and page-specific settings during layout discussion on the best possible solution for integrating firefox 3 with the ability to apply site- and page-specific user settings during layout. the idea of using a single sheet and the per-site selectors that dbaron implemented would allow for a q...
2006-09-30 - Archive of obsolete content
rt.com/firefox/xpcom/ is misleading as it uses the standalone glue (-dxpcom_glue) for components, which is not recommended. developers should use this sample instead: http://developer.mozilla.org/en/docs/xpcom_glue discussions dynamic load overlay a short discussion about the possibilities of loading and unloading xul overlay runtime reading binary data from file discusses about the code to read binary data from file how to build xpcom component on mac os x discusses about the make file code used to build xpcom components on mac os x successfully meetings none during this week. ...
NPN_DestroyStream - Archive of obsolete content
alues: npres_done (most common): stream completed normally; all data was sent by the plug-in to the browser. npres_user_break: plug-in is terminating the stream due to a user request. npres_network_err: stream failed due to network problems. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description the plug-in calls the npn_destroystream() function to close and delete a stream. this stream can be either a stream that the browser created and passed to the plug-in in npp_newstream(), or a stream created by the plug-in through a call to npn_newstream(). see also npp_destroystream() npn_newstream() npp_newstream() npstream npp ...
NPN_GetAuthenticationInfo - Archive of obsolete content
http password. if the function succeed, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the password may have internal null bytes and may not be null-terminated. plen out parameter. the length of the returned password buffer. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description plugin which implement their own http networking stack (such as the java plugin) may want to use the standard http auth prompts and password managed of the browser. this function allows the plugin to ask the browser for http authentication information for a domain. unless the plugin has special networking needs, it is recommended to use the stan...
NPN_GetURL - Archive of obsolete content
ing. if the target is null, the browser creates a new stream and delivers the data to the current instance regardless of the mime type of the url. in general, if a url works in the location box of the browser, it works here, except for the _self target. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_geturl() is used to load a url into the current window or another target or stream. plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. this is especially useful for enabling an existing application to operate on the web. for http urls, the browser resolves this method a...
NPN_GetURLNotify - Archive of obsolete content
e of the target window or frame, or one of several special target names. for values, see npn_geturl(). notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify() call, which passes this value (see description below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_geturlnotify() works just like npn_geturl(), with one exception: npn_geturlnotify() notifies the plug-in instance upon successful or unsuccessful completion of the request by calling the plug-in's npp_urlnotify() function and passing it the notifydata value. npn_geturlnotify() typically handles the url request asynchronously. it returns i...
NPN_GetValueForURL - Archive of obsolete content
ng the buffer. note: the value may have internal null bytes and may not be null-terminated. when multiple cookies are returned for a given url, the format of the return value is: cookie1=value1;cookie2=value2;cookie3=value3 len out parameter. the length of the returned value buffer. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description this entry point is designed to allow plugins which implement their own http stacks to form requests to the web server in the same way the browser does. see also npn_setvalueforurl, npn_getauthenticationinfo ...
NPN NewStream - Archive of obsolete content
he following parameters: instance pointer to current plug-in instance. type mime type of the stream. target name of the target window or frame, or one of several special target names. for values, see npn_geturl. stream stream to be created by the browser. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_newstream creates a new stream of data produced by the plug-in and consumed by the browser. the mime parameter is the mime type of the plug-in to create. a plug-in can create another instance of itself by specifying its own mime type and a new target name in a call to npn_newstream. the stream is returned in the stream parameter. the plug-in...
NPN_PluginThreadAsyncCall - Archive of obsolete content
t ensure that the function pointer remains callable and the user data is not deallocated until the browser executes the call. there are inherent race conditions between calling this function and termination of the plug-in instance. the browser might not execute calls successfully registered with this api call during plug-in termination. plug-ins should perform appropriate synchronization with the code in their npp_destroy() routine to ensure correct execution and avoid memory leaks. calling npn_pluginthreadasynccall() on the "browser main thread" or the "plug-in thread" is legal; the call to npn_pluginthreadasynccall() returns immediately. after control returns to the browser, it is free to call the function with its argument from this thread. see also npp out-of-process plugins ...
NPN_PostURL - Archive of obsolete content
ted for a protocol that requires a header. file a boolean value that specifies whether to post a file. values: true: post the file whose path is specified in buf, then delete the file. false: post the raw data in buf. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_posturl works similarly to npn_geturl, but in reverse. npn_geturl reads data from the url and either displays it in the target window or delivers it to the plug-in. npn_posturl writes data from a file or buffer to the url and either displays the server's response in the target window or delivers it to the plug-in. if the target paramete...
NPN_PostURLNotify - Archive of obsolete content
h is specified in buf, then delete the file. false: post the raw data in buf. notifydata plug-in-private value for associating the request with the subsequent npp_urlnotify call, which returns this value (see description below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npn_posturlnotify functions identically to npn_posturl, with these exceptions: npn_posturlnotify supports specifying headers when posting a memory buffer. npn_posturlnotify calls npp_urlnotify upon successful or unsuccessful completion of the request. for more information, see npn_posturl. npn_posturlnotify is typically asynchronous: it re...
NPN_ReloadPlugins - Archive of obsolete content
if true, all pages are reloaded once the plugins are reloaded; otherwise, they aren't. description npn_reloadplugins() reads the plugins directory for the current platform and reinstalls all of the plug-ins it finds there. normally, if you add or remove any plug-ins, the browser does not see them until you restart gecko. ...
NPN_SetValueForURL - Archive of obsolete content
type of information to be changed. the only supported type is npnurlvcookie. url the url for which to change information. value the new associated information for the url. note: the value may have internal null bytes and may not be null-terminated. len the length of the value buffer. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description this entry point is designed to allow plugins to affect the cookies sent by the browser back to the server. see also npn_getvalueforurl, npn_getauthenticationinfo ...
NPN_UserAgent - Archive of obsolete content
meter: instance pointer to the current plug-in instance. returns a pointer to a buffer that contains the user agent field of the browser. description the user agent is the part of the http header that identifies the browser during transfers. you can use this information to verify that the expected browser is in use, or you can use it in combination with npn_version() to supply different code for different versions of the same browser. see also npn_status() npn_version() gecko user agent string reference ...
NPP_Destroy - Archive of obsolete content
psaveddata **save); parameters the function has the following parameters: instance pointer to the plug-in instance to delete. **save state or other information to save for reuse by a new instance of this plug-in at the same url. passed to npp_new. returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description npp_destroy releases the instance data and resources associated with a plug-in. the browser calls this function when a plug-in instance is deleted, typically because the user has left the page containing the instance, closed the window, or quit the browser. you should delete any private instance-specific information stored in the plug-in's ins...
NPP_DestroyStream - Archive of obsolete content
canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. npres_network_err: stream failed due to problems with network, disk i/o, lack of memory, or other problems. returns if successful, the plug-in should return nperr_no_error. if unsuccessful, the plug-in should return an error code. for possible values, see error codes. description the browser calls the npp_destroystream function when a data stream sent to the plug-in is finished, either because it has completed successfully or terminated abnormally. after this, the browser deletes the npstream object. you should delete any private data allocated in stream->pdata at this time, and should not make any further references ...
NPP_GetValue - Archive of obsolete content
meters the function has the following parameters: instance pointer to the plugin instance from which the value should come. variable variable for which the browser (caller) would like a value. the full list is in the npapi headers. value value for the requested variable. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description npp_getvalue retrieves instance variables. see also npp_setvalue, npn_getvalue, npn_setvalue ...
NPP_New - Archive of obsolete content
aved pointer to data saved by npp_destroy for a previous instance of this plug-in at the same url. if non-null, the browser passes ownership of the npsaveddata object back to the plug-in. the plug-in is responsible for freeing the memory for the npsaveddata and the buffer it contains. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description npp_new creates a new instance of a plug-in. it is called after np_initialize and is passed the mime type, embedded or full-screen display mode, and, for embedded plug-ins, information about html embed arguments. a new instance pointer (npp instance) is created by the plug-in, which is valid until the instance is destroyed with npp_destroy. ...
NPP_NewStream - Archive of obsolete content
seek: stream data randomly accessible by the plug-in as needed, through calls to npn_requestread. implementation note: some plugins, notably silverlight, do not set this outparam, and rely on the outparam being initialized to a default np_normal value. returns if successful, the function should return nperr_no_error. if unsuccessful, the function should return one of the nperror error codes. this will cause the browser to destroy the stream without calling npp_destroystream. description npp_newstream notifies the plug-in when a new stream is created. the npstream* pointer is valid until the stream is destroyed. the plug-in can store plug-in-private data associated with the stream in stream->pdata. the mime type of the stream is provided by the type parameter. the data in the s...
NPP_SetWindow - Archive of obsolete content
lug-in instance. must be embedded or full-screen. window pointer to the window into which the instance draws. the window structure contains a window handle and values for top left corner, width, height, and clipping rectangle (see note on unix below). returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description the browser calls npp_setwindow after creating the instance to allow drawing to begin. subsequent calls to npp_setwindow indicate changes in size or position; these calls pass the same npwindow object each time, but with different values. if the window handle is set to null, the window is destroyed. in this case, the plug-in must not perform a...
NPSavedData - Archive of obsolete content
t the browser saves after the instance is deleted. this information can be returned to another instance of the same plug-in if the user returns to the web page that contains it. you can use the plug-in's npp_destroy() function to allocate an npsaveddata object using the npn_memalloc() function, fill in the fields, and return it to the browser as an output parameter. see instance destruction for a code example that shows how to use npsaveddata. if the user revisits a web page that contains a plug-in, the browser returns the npsaveddata to the new instance of the plug-in in a call to npp_new(). after this, the plug-in is responsible for keeping or deleting the objects as necessary. see also npp_new() npp_destroy() ...
NP_GetMIMEDescription - Archive of obsolete content
vfs/gnome-vfs-utils.h> // const char* gnome_vfs_mime_get_description (const char *mime_type); const char* desc = gnome_vfs_mime_get_description ("audio/ogg"); if you use gnome gio (gio-2.0), you can get the mime type description too. #include <gio/gio.h> const char* desc = g_content_type_get_description("audio/ogg"); javascript inside a web page, you can retrieve these informations with this code: var mimetype = navigator.mimetypes['application/basic-example-plugin']; if (mimetype) { alert(mimetype.type + ':' + mimetype.suffixes + ':' + mimetype.description); } ...
NP_GetValue - Archive of obsolete content
is null because no instance has been created. variable plug-in information the call gets. values: nppvpluginnamestring: gets the name of the plug-in nppvplugindescriptionstring: gets the description string of the plug-in value plug-in name, returned by the function. returns if successful, the function returns nperr_no_error. if unsuccessful, the function returns an error code. for possible values, see error codes. description none. see also npp_setvalue ...
NP_Initialize - Archive of obsolete content
i summary provides global initialization for a plug-in. syntax windows #include <npapi.h> nperror winapi np_initialize(npnetscapefuncs *anpnfuncs) unix #include <npapi.h> nperror np_initialize(npnetscapefuncs *anpnfuncs, nppluginfuncs *anppfuncs) returns if successful, the function returns nperr_no_error. if unsuccessful, the plug-in is not loaded and the function returns an error code. for possible values, see error codes. description the browser calls this function only once: when a plug-in is loaded, before the first instance is created. this is the first function that the browser calls. np_initialize tells the plug-in that the browser has loaded it and provides global initialization. allocate any memory or resources shared by all instances of your plug-in at this time. ...
The First Install Problem - Archive of obsolete content
lies with the writing of plugin directory information into the registry along with a plid, we can then use the object tag to invoke plugins based on their "classid" (their respective plid, which is a uri, which works well with the w3c spec). for example, in our case, a prospective invocation might look like: <object classid="@mycompany.com/myapplication,version=5.01" data="myfile.typ" codebase="http://myurl.com/myplugin/myplugin.xpi" type="application/x-myapp"></object> the use of both "type" and "classid" attributes here offers the following user benefit: if there is another mimetype handler for application/x-myapp, only myapplication gets invoked. the resolution of a mimetype handler is no longer arbitrary. if the "data" file myfile.typ doesn't contain enough reso...
Getting Started - Archive of obsolete content
t for beginners to rss (i.e., those with no or very little prior rss experience). however, those experienced with rss may also find this useful as an aid in filling in any missing information about rss that they were not aware of, or as a refresher guide. this tutorial assumes that you have some experience with html (or xml) and that you are comfortable with the basics ofmarkup . in other words, code like this doesn't bother you: this is some markup with <b>bold</b> tags. if you are comfortable with that, you should have no problem learning rss. note: if you are not a web developer and do not want to become one, then this tutorial is not for you. you need to be comfortable with creatingmarkup to be able to effectively use this tutorial. what do you need before you start? to get the mo...
SAX - Archive of obsolete content
a parsing api. sax was the first widely adopted api for xml in java, and later implemented in several other programming language environments. starting with firefox 2, a sax parser is available to xul applications and extensions. for more information, please see sax homepage. quick start the sax parser functionality is available through the xml reader component. to create one, use the following code: var xmlreader = components.classes["@mozilla.org/saxparser/xmlreader;1"] .createinstance(components.interfaces.nsisaxxmlreader); after you created the sax parser, you need to set the handlers for the events you're interested in and fire off the parsing process. all functionality is available through the nsisaxxmlreader interface. set the handlers handlers are user-...
.htaccess ( hypertext access ) - Archive of obsolete content
es less. common application url redirects & rewrite: htaccess files are often used to redirect traffic to a web page to another or from traffic to a directory to another even between domains is possible. it's a fast and efficient way of redirecting traffic, because the redirect happens before the pages are served. redirects can be made on a temporary basis or permanently by supplying the status codes. redirect 301 / http://example.com/ # redirect the traffic to the directory to example.com , permanent redirect redirect 302 / http://example.com/ # redirect the traffic to the directory to example.com , temporary redirect blocking : htaccess also facilitates blocking traffic based on ip and ip range, also, use to block bad bots, rippers, and referrers; often used to restrict acc...
TCP/IP Security - Archive of obsolete content
. this is accomplished by encrypting data using a cryptographic algorithm and a secret key—a value known only to the two parties exchanging data. the data can only be decrypted by someone who has the secret key. integrity. ssl can determine if data has been changed (intentionally or unintentionally) during transit. the integrity of data can be assured by generating a message authentication code (mac) value, which is a keyed cryptographic checksum of the data. if the data is altered and the mac is recalculated, the old and new macs will differ. peer authentication. each ssl endpoint can confirm the identity of the other ssl endpoint with which it wishes to communicate, ensuring that the network traffic and data is being sent from the expected host. ssl authentication is typically per...
Common Firefox theme issues and solutions - Archive of obsolete content
hreads on mozillazine for solutions to this issue: http://forums.mozillazine.org/viewtopic.php?f=18&t=2131121 http://forums.mozillazine.org/viewtopic.php?f=18&t=1953371&start=60 windows 7 aero not going into full screen mode properly on win7 with aero glass support firefox doesn't always go to full screen mode from a normal window properly. the resolution to this issue is to add the following code to your browser.css file somewhere below where the main-window is made transparent to support aero glass. @media all and (-moz-windows-compositor) { /* make transition to fullscreen mode seamlessly in firefox 10+ */ #main-window[infullscreen="true"] { -moz-appearance: none; background-color: -moz-dialog!important; } } for more information about this issue please see bug 732757 and...
Theme changes in Firefox 2 - Archive of obsolete content
oppable="false"] menulist#name[droppable="false"] > .menulist-editable-box menulist#name[droppable="false"] > .menulist-editable-box > html|*.textbox-input menulist#name[droppable="false"] > .menulist-dropmarker menulist#name[droppable="false"] > menupopup this file styles addbookmark2.xul. bookmarks/bookmarksproperties.css this is a new file in firefox 2, and should contain the same css code as you added to addbookmark.css. this file styles bookmarksproperties.xul. note: this css may be moved out into a separate file that will be referenced by both files in the future. browser.css the following styles used in firefox 1.5 themes are no longer used in firefox 2 and should be removed from your theme: #bookmarks-button:active #copy-button:active #cut-button:active #downloads-b...
Settings - Archive of obsolete content
able properties do not display non-enumerable javascript properties. show variables filter box enabling this option adds a "filter variables" search box to the variables pane, so that you can filter the displayed list of variables. show original sources enabling this option will make the debugger use source maps, if they are available, to display the original source for code which has been combined, minified, or even compiled to javascript from a language like coffeescript. defaults to true. automatically black box minified sources new in firefox 33. automatically black box sources whose url ends with ".min.js". defaults to true. ...
Using SSH to connect to CVS - Archive of obsolete content
generating an ssh key first, install ssh. most linux, bsd, and osx distributions come with it installed already. ...
References - Archive of obsolete content
ard-compliant browsers, part 1 from makiko itoh preparing for standard-compliant browsers, part 2 from makiko itoh javascript best practices lists 15 of the most frequent coding practices which create problems for javascript and dhtml-driven webpages. the webpage explains and proposes with small examples the best coding practices and most recommendable ways of developing problem-free javascript code. from matt kruse debugging html and css is a well designed website explaining well the how, why and where of html validation, css validation and debugging tools. we highly recommend this site. it is also available in french. from dan. <- previous section: summary of changes ...
Using Web Standards in your Web Pages - Archive of obsolete content
ort current standards while accommodating old browsers." -web standards project this article provides an overview of the process for upgrading the content of your web pages to conform to the world wide web consortium (w3c) web standards. the first 2 sections address exclusively validation issues, benefits of validation, deprecated elements, deprecated attributes. how to upgrade a webpage markup code to pass validation and how to implement css are addressed by providing recommendations, tutorials and references. the other sections address dom and dhtml coding practices which are at odds with the w3c web standards and suggest replacements. every proposed w3c web standards replacement in this article is working without a problem in modern browsers like msie 7, firefox 2, opera 9, safari 3, kon...
-ms-scrollbar-3dlight-color - Archive of obsolete content
( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? )where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-3dlight-color property for a <textarea> element. code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/scrollbarcolor.htm <!doctype html> <html> <head> <title>scrollbar-3dlight-color</title> <style> .blue3dlight { -ms-scrollbar-3dlight-color: blue; scrollbar-3dlight-color: blue; /* use the standard when available. */ } </style> </head> <body> <textarea class="blue3dlight">the top and left ...
-ms-scrollbar-darkshadow-color - Archive of obsolete content
hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? )where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-darkshadow-color property for a <textarea> element. ...
-moz-windows-compositor - Archive of obsolete content
see bug 1396066 for more details. ...
:-moz-system-metric(images-in-menus) - Archive of obsolete content
see bug 1396066 for more details. ...
:-moz-system-metric(mac-graphite-theme) - Archive of obsolete content
see bug 1396066 for more details. examples demo ...
:-moz-system-metric(scrollbar-end-backward) - Archive of obsolete content
see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(scrollbar-end-forward) - Archive of obsolete content
see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(scrollbar-start-backward) - Archive of obsolete content
see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(scrollbar-start-forward) - Archive of obsolete content
see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(scrollbar-thumb-proportional) - Archive of obsolete content
see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(touch-enabled) - Archive of obsolete content
see bug 1396066 for more details. use the -moz-touch-enabled media query instead. specifications not part of any specification. ...
:-moz-system-metric(windows-default-theme) - Archive of obsolete content
sing one of the following themes in windows: luna, royale, zune, or aero (i.e., vista basic, vista standard, or aero glass). this will exclude windows classic themes as well as third-party themes. this selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. example html content <p id="defaultthemes"> this paragraph should have a green background with luna/royale/zune/aero windows themes and red with other themes. </p> <p id="nondefaultthemes"> this paragraph should have a green background with windows classic or third-party themes and red with other themes. </p> <p id="notsupported">theme detection i...
:-moz-system-metric() - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-mac-graphite-theme - Archive of obsolete content
see bug 1396066 for more details. the -moz-mac-graphite-theme gecko-only css media feature can be used to apply styles based on whether the user has the mac os x "graphite" theme enabled. ...
-moz-scrollbar-end-backward - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-scrollbar-end-forward - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-scrollbar-start-backward - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-scrollbar-start-forward - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-scrollbar-thumb-proportional - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-windows-accent-color-in-titlebar - Archive of obsolete content
see bug 1396066 for more details. the -moz-windows-accent-color-in-titlebar gecko-only css media feature can be used to apply styles based on whether accent colors are enabled in microsoft windows titlebars. syntax <integer> in recent windows versions (e.g., 10), if accent colors are enabled in window titlebars, this is 1. otherwise it's 0. ...
-moz-windows-classic - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-windows-default-theme - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-windows-glass - Archive of obsolete content
see bug 1396066 for more details. ...
-moz-windows-theme - Archive of obsolete content
note: since firefox 58, this media feature is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. the -moz-windows-theme gecko-only css media feature is useful for customizing application skins and other chrome code to work well with the user's windows theme. syntax the -moz-windows-theme feature is specified as a keyword value that indicates which windows theme is currently being used. values aero luna-blue luna-olive luna-silver royale generic zune media: media/visual accepts min/max prefixes: no ...
Using JavaScript Generators in Firefox - Archive of obsolete content
you can opt in in html as follows: <script type="text/javascript;version=1.7" src="myscript.js"></script> then your myscript.js file might look like this: // need to stash the generator in a global variable. var generator; // simple event listener function to pass the received event to the generator. ...
ArrayBuffer.transfer() - Archive of obsolete content
this is not the exact equivalent of this api because browsers that natively support it are be able to internally use the c++ function realloc() which extends the length of the memory and only copies it to a new location as-needed as opposed to the following pollyf...
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
tion parameter lists (firefox 52) ecmascript 2018 spread in object literals and rest parameters (firefox 55) for await...of (firefox 57) global_objects/sharedarraybuffer (firefox 57, with flags) global_objects/promise/finally (firefox 58) global_objects/regexp/dotall (not yet implemented; in other browsers) regexp lookbehind assertions (not yet implemented; in other browsers) regexp unicode property escapes (not yet implemented; in other browsers) regexp named capture groups (not yet implemented; in other browsers) ecmascript 2019 array.flat() (firefox 62) array.flatmap() (firefox 62) object.fromentries() (firefox 63) string.trimstart() and string.trimend() (firefox 61) optional catch binding (firefox 58) function.tostring() revision (firefox 54) symbol.description (fire...
Expression closures - Archive of obsolete content
the function. description this addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical lambda notation. javascript 1.7 and older: function(x) { return x * x; } javascript 1.8: function(x) x * x this syntax allows you to leave off the braces and 'return' statement - making them implicit. there is no added benefit to writing code in this manner, other than having it be syntactically shorter. examples a shorthand for binding event listeners: document.addeventlistener('click', function() false, true); using this notation with some of the array functions from javascript 1.6: elems.some(function(elem) elem.type == 'text'); ...
Date.getVarDate() - Archive of obsolete content
warning: this method is supported in internet explorer only. the getvardate method returns a vt_date value from a date object. syntax dateobj.getvardate() parameters the required dateobj reference is a date object. return value returns a vt_date value. remarks the getvardate() method is used when javascript code interacts with com objects, activex objects, or other objects that accept and return date values in vt_date format. these include objects in visual basic and visual basic scripting edition (vbscript). the actual format of the returned value depends on regional settings. requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, and int...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
with the asynchronous operation. remarks call this function in the callback function for the asynchronous operation after the call to debug.mstraceasyncoperationcompleted. note: some debugging tools do not display the information sent to the debugger. asyncoperationid must correspond to the operation name previously returned from debug.mstraceasyncoperationstarting. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of asy...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
ation completes. asyncoperationid must correspond to the operation id previously returned from debug.mstraceasyncoperationstarting. the possible values for status include: debug.ms_async_op_status_success debug.ms_async_op_status_canceled debug.ms_async_op_status_error note: some debugging tools do not display the information sent to the debugger. example the following code provides an example of tracing an asynchronous call for a windows 8.x store app. function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of asy...
Enumerator.atEnd - Archive of obsolete content
enumerator.atend method returns a boolean value indicating if the enumerator is at the end of the collection. syntax myenum.atend() remarks the required myenum reference is any enumerator object. the atend method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined. otherwise, it returns false. ...
Enumerator - Archive of obsolete content
collections differ from arrays in that the members of a collection are not directly accessible. instead of using indexes, as you would with arrays, you can move the current item pointer only to the first or next element of a collection. the enumerator object provides a way to access any member of a collection and behaves similarly to the for...each statement in vbscript. ...
VBArray.dimensions - Archive of obsolete content
osoft extension and is only supported in internet explorer. the vbarray.dimensions method returns the number of dimensions in a vbarray. syntax array.dimensions( ) remarks the required array is a vbarray object. example the dimensions method provides a way to retrieve the number of dimensions in a specified vbarray. the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- function createvbarray()...
VBArray.getItem - Archive of obsolete content
m method returns the item at the specified location. syntax safearray.getitem(dimension1[, dimension2, ...], dimensionn) parameters safearray a vbarray object. dimension1, ..., dimensionn specifies the exact location of the desired element of the vbarray. n equals the number of dimensions in the vbarray. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that iterates the visual basic safe array and prints out the contents of each element. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, ...
VBArray.toArray - Archive of obsolete content
hree dimensions and three elements in each dimension is converted into a javascript array as follows: suppose the vbarray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9). after translation, the javascript array contains: 1, 2, 3, 4, 5, 6, 7, 8, 9. there is currently no way to convert a javascript array into a vbarray. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that converts the visual basic safe array to a javascript array. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) ...
VBArray.ubound - Archive of obsolete content
of the vbarray for which the higher bound index is wanted. if omitted, ubound behaves as if a 1 was passed. remarks if the vbarray is empty, the ubound method returns undefined. if dim is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that determines the number of dimensions in the safe array and the upper bound of each dimension. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- function createvbarray()...
VBArray - Archive of obsolete content
e done by retrieving the value from an existing activex or other object. vbarrays can have multiple dimensions. the indices of each dimension can be different. the dimensions method retrieves the number of dimensions in the array; the lbound and ubound methods retrieve the range of indices used by each dimension. example the following example consists of three parts. the first part is vbscript code to create a visual basic safe array. the second part is javascript code that converts the visual basic safe array to a javascript array. both of these parts go into the <head> section of an html page. the third part is the javascript code that goes in the <body> section to run the other two parts. <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) ...
@cc_on - Archive of obsolete content
syntax @cc_on remarks the @cc_on statement activates conditional compilation within comments in a script. it is not common to use conditional compilation variables in scripts written for asp or asp.net pages or command-line programs because the capabilities of the compilers can be determined by using other methods. when you write a script for a web page, always put conditional compilation code in comments. this enables hosts that do not support conditional compilation to ignore it. it is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do not support conditional compilation will accept your script as valid syntax: an @if or @set statement outside of a comment also activates conditional compilation. example the following example illustrates ...
@if - Archive of obsolete content
tement is typically used to determine which text among several options should be used for text output. it is not common to use conditional compilation variables in scripts written for asp or asp.net pages or command-line programs. this is because the capabilities of the compilers can be determined by using other methods. when you write a script for a web page, always add conditional compilation code in comments. this enables hosts that do not support conditional compilation to ignore it. example the following example illustrates the use of the @if...@elif...@else...@end statement. /*@cc_on @*/ /*@ document.write("javascript version: " + @_jscript_version + "."); document.write("<br />"); @if (@_win32) document.write("running on a 32-bit version of windows."); @elif...
@set - Archive of obsolete content
ust be preceded by an "@" character at all times. term zero or more unary operators followed by a constant, conditional compilation variable, or parenthesized expression. remarks numeric and boolean variables are supported for conditional compilation. strings are not. variables created using @set are generally used in conditional compilation statements, but can be used anywhere in javascript code. examples of variable declarations look like this: @set @myvar1 = 12 @set @myvar2 = (@myvar1 * 20) @set @myvar3 = @_jscript_version the following operators are supported in parenthesized expressions: ! ~ * / % + - << >> >>> < <= > >= == != === !== & ^ | && | | if a variable is used before it has been defined, its value is nan. nan can be c...
New in JavaScript 1.1 - Archive of obsolete content
f void other new features <noscript> liveconnect. communication between java and javascript. changed functionality in javascript 1.1 "object deletion". you can remove an object by setting its object reference to null. constructor and prototype properties on objects added. eval() is now a method of every object (was previously a built-in function); it evaluates a string of javascript code in the context of the specified object. math.random() now works on every platform. tostring(): added radix parameter, which specifies the base to use for representing numeric values. isnan() now works on every platform (not only unix anymore) parsefloat() and parseint() now return nan on all platforms, if the first character of the specified string cannot be converted to a number; in previous...
New in JavaScript 1.8.5 - Archive of obsolete content
rray of all enumerable and non-enumerable properties on an object. bug 518663 object.preventextensions() prevents any extensions of an object. bug 492849 object.isextensible() determines if extending of an object is allowed. bug 492849 object.seal() prevents other code from deleting properties of an object. bug 492845 object.issealed() determines if an object is sealed. bug 492845 object.freeze() freezes an object: other code can't delete or change any properties. bug 492844 object.isfrozen() determines if an object was frozen. ...
ECMAScript 5 support in Mozilla - Archive of obsolete content
n javascript 1.8.1 (gecko 1.9.1, firefox 3.5) native json support object.getprototypeof() method. string.trim() method, which trims whitespace from both ends of the string. gecko 1.9.1.4 updated the implementation of json.stringify() to be compliant with ecmascript 5. improvements laid out by ecmascript 5 have been made in the parsing algorithm that prevents evaluating xhtml as javascript code in certain circumstances. added in javascript 1.6 (gecko 1.8, firefox 1.5) new array methods offering several improved methods for manipulating arrays -- have been part of javascript since javascript 1.6. now they've been standardized as part of ecmascript 5. ...
Object.prototype.eval() - Archive of obsolete content
syntax obj.eval(string) parameters string any string representing a javascript expression, statement, or sequence of statements. the expression can include variables and properties of existing objects. description the eval method can no longer be used as a method of an object. ...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
ript engine will revert to throwing typeerrors. examples simple test of __nosuchmethod__ var o = { __nosuchmethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz(); // output // foo (1, 2, 3) // bar (4, 5) // baz () using __nosuchmethod__ to simulate multiple inheritance an example of code that implements a primitive form of multiple inheritance is shown below. // doesn't work with multiple inheritance objects as parents function nomethod(name, args) { var parents = this.__parents_; // go through all parents for (var i = 0; i < parents.length; i++) { // if we find a function on the parent, we call it if (typeof parents[i][name] == 'function') { return parents[...
Object.prototype.watch() - Archive of obsolete content
t is still in effect. to remove a watchpoint, use the unwatch() method. by default, the watch method is inherited by every object descended from object. the javascript debugger has functionality similar to that provided by this method, as well as other debugging options. for information on the debugger, see venkman. in firefox, handler is only called from assignments in script, not from native code. for example, window.watch('location', myhandler) will not call myhandler if the user clicks a link to an anchor within the current document. however, window.location += '#myanchor' will call myhandler. note: calling watch() on an object for a specific property overrides any previous handler attached for that property. examples using watch and unwatch const o = { p: 1 }; o.watch('p', (id, ...
arguments.caller - Archive of obsolete content
tion that invoked the currently executing function. this property has been removed and no longer works. description this property is not available anymore, but you can still use function.caller. function whocalled() { if (whocalled.caller == null) console.log('i was called from the global scope.'); else console.log(whocalled.caller + ' called me!'); } examples the following code was used to check the value of arguments.caller in a function, but doesn't work anymore. function whocalled() { if (arguments.caller == null) console.log('i was called from the global scope.'); else console.log(arguments.caller + ' called me!'); } specifications not part of any standard. implemented in javascript 1.1 and removed in bug 7224 due to potentially vulnerable for ...
handler.enumerate() - Archive of obsolete content
rator object. description the handler.enumerate method is a trap for for...in statements. interceptions this trap can intercept these operations: property enumeration / for...in: for (var name in proxy) {...} reflect.enumerate() invariants if the following invariants are violated, the proxy will throw a typeerror: the enumerate method must return an object. examples the following code traps for...in statements. var p = new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant. var p = new proxy({}, { enumerate(target) { return 1; } }); for (var x in p) {...
Archived JavaScript Reference - Archive of obsolete content
object.prototype.__nosuchmethod__the __nosuchmethod__ property used to reference a function to be executed when a non-existent method is called on an object, but this function is no longer available.object.prototype.__parent__the __parent__ property used to point to an object's context, but it has been removed.object.prototype.eval()the object.eval() method used to evaluate a string of javascript code in the context of an object, however, this method has been removed.object.prototype.unwatch()the unwatch() method removes a watchpoint set with the watch() method.object.prototype.watch()the watch() method watches for a property to be assigned a value and runs a function when that occurs.object.unobserve()the object.unobserve() method was used to remove observers set by object.observe(), but has ...
LiveConnect Reference - Archive of obsolete content
jsexception the public class jsexception extends runtimeexception, and is thrown when javascript returns an error. jsobject the public class jsobject extends object. ...
JavaPackage - Archive of obsolete content
a javapackage are its properties, you cannot use a for...in statement to enumerate them as you can enumerate the properties of other objects. ...
Packages - Archive of obsolete content
the support for this object was removed in gecko 16, see liveconnect for details. ...
ParallelArray - Archive of obsolete content
the goal of parallelarray was to enable data-parallelism in web applications. the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary. to ensure that your code executes in parallel, it is suggested that the functions should be limited to the parallelizable subset of js that firefox supports. syntax new parallelarray() new parallelarray([element0, element1, ...]) new parallelarray(arraylength, elementalfunction) parallelarray instances properties length reflects the number of elements in the parallelarray. methods map reduce scan scatter filter flatten partition get examples using map in parallel var p = new parallelarray([0, 1, 2, 3, 4]); var m = p.map(function (v) { ...
background-size - Archive of obsolete content
> 40% in some european countries). user:jürgen jeka 2009-08-04 <hr> is there anyway to have the -moz-border-image only apply if -moz-background-size is not supported? i'm guessing not, just asking because having both rules in for 3.6 creates a strange effect: -moz-border-image gets inherited by every element on the page user:robertc 2009-08-08 -moz-border-image should not inherit. some example code? user:jürgen jeka 2009-08-09 ok, here's a page with both rules - the css is derived from the code on the page here, this is what it looks like in 3.6a2pre on linux, the background image appears on the whole page, and then again behind the main content. here's a slightly more complex example (screenshot), and the same page without the -moz-border-image image rule (screenshot). user:robertc 2009-0...
XForms Group Element - Archive of obsolete content
elevant, then the rendering approach used to signify non-relevance is applied to the entire content of the group. representations the group element doesn't have visual presentation. example <group ref="address"> <label>shipping address</label> <input ref="line_1"> <label>address line 1</label> </input> <input ref="line_2"> <label>address line 2</label> </input> <input ref="postcode"> <label>postcode</label> </input> </group> ...
Using XForms and PHP - Archive of obsolete content
as xml, for example application/xhtml+xml. to do that, you need to use the header() php function: <?php header("content-type: application/xhtml+xml; charset=utf-8"); ... ?> but remember this (quote from php documentation): remember that header() must be called before any actual output is sent, either by normal html tags, blank lines in a file, or from php. it is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. the same problem exists when using a single php/html file. parsing submitted data depending on the submission type, you might get different data formats on the server side. to really use the power of xforms (/xml) you would probably submit xml. th...
Describing microformats in JavaScript - Archive of obsolete content
the type property indicates the type of address represented by the object (work, home, and so forth). since the plural property is true, multiple types can be specified. this allows an address to be marked as being, for example, a work address for receiving parcels. the street-address property is plural as we...
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
have used bare pseudo-classes, or bare class-pseudo-class combinations, are at risk of seeing hover styles applied to more than just their links. the most reliable fix is to add the anchor element to the selectors, like this: a:hover {color: red;} a.nav:hover {color: red;} in an attempt to avoid causing problems for legacy documents, browsers based on mozilla 1.0 and later (netscape 7+) include code that causes bare pseudo-classes to be restricted only to links if the document is rendered in "quirks" mode. in browsers based on the engine found in mozilla 1.3b and later, this quirk is extended to cover selectors that combine a bare class selector with the :hover pseudo-class (see bug 169078 for details). named anchor problems in addition to the effects described previously, there are two ot...
Mozilla's DOCTYPE sniffing - Archive of obsolete content
solete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this page describes behavior of the old html parser in firefox 3.6 and older. it has been replaced by a new html 5 parser in firefox 4 and newer. this document describes how mozilla uses the doctype declaration to determine strict mode vs. quirks mode. the code that makes this determination is currently in determineparsemode() in nsparser.cpp. see bug 1312 and bug 55264 for some of the history of the mode determination. see bug 153032 for the creation of the almost-standards mode around mozilla 1.0. the goals that led to choosing this behavior were the following: almost all existing text/html pages on the web that need to be in quirks mode to be disp...
Game monetization - Game development
th an unknown publisher for more money. publishers taking your games for revenue share, and/or licensing may require implementing their own apis, which could take extra work, so consider that in your rates too. branding you can sell rights to use your game for branding, or do it yourself. in the first case it's almost like non-exclusive licensing, but the client will usually buy rights for the code and implement their own graphics. in the second case it's like a freelance deal, but you're reusing the code and adding graphics provided by the client, sometimes implementing them as they instruct you. as an example if you've got a game where a player taps items of food, you could change the food to the client's products to give them advertising. prices in this model vary greatly depending on th...
Game promotion - Game development
you and your game. having a booth gives you the possibility to interact with your fans directly — besides the promotion part you can also test new builds of your game on regular people and fix any bugs (or incorporate any feedback) they uncover. you can't imagine what people may come up with when playing your game, and what obvious issues you've missed while spending hours polishing it. promo codes if you're selling the game, then create the ability to distribute promo codes allowing people to access your game for free (or at least a demo or time-limited version), and send them all over the place — to press, youtubers, as competition prizes, etc. if the game reaches certain people you'll get a free advert to thousands of players. it can boost interest in your game more than anything els...
Bounding volume collision detection with THREE.js - Game development
point vs. box and sphere box vs. box and sphere sphere vs. box and sphere using boxhelper as an alternative to using raw box3 and sphere objects, three.js has a useful object to make handling bounding boxes easier: boxhelper (previously boundingboxhelper, which has been deprecated). this helper takes a mesh and calculates a bounding box volume for it (including its child mes...
Mobile touch controls - Game development
w, it is better to make the field of activity bigger without covering half of the screen with button images. for example, tapping on the right side of the screen will fire the weapon: this.buttonshoot = this.add.button(this.world.width*0.5, 0, 'button-alpha', null, this); this.buttonshoot.oninputdown.add(this.goshootpressed, this); this.buttonshoot.oninputup.add(this.goshootreleased, this); the code above will create a new button using a transparent image that covers the right half of the screen. you can assign functions on input down and input up separately if you'd like to perform more complicated actions, but in this game touching the right side of the screen will simply fire the bullets to the right — this is all we need in this case. moving the player could be managed by creating the...
Implementing game control mechanisms - Game development
() { // ... if(this.game.input.mousepointer.isdown) { // do something } // ... } this will be executed whenever the mouse button is pressed, and it will be checked against the input's isdown boolean variable on every frame of the game. that should give you some understanding of the project structure. we'll be playing mostly with the mainmenu.js and game.js files, and we'll explain the code inside the create() and update() methods in much more detail in later articles. pure javascript demo there's also a small online demo with full source code available on github where the basic support for the control mechanisms described in the articles is implemented in pure javascript. it will be explained in the given articles themselves below, but you can play with it already, and use the co...
Crisp pixel art look with image-rendering - Game development
d; image-rendering: crisp-edges; } and some javascript to set up the canvas and load the image: // get canvas context var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image = new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note: you can check out the original code on github (and a live example.) ...
Visual JS GE - Game development
server_instance/build_from_editor_to_visual_js_file.js. this is a node.js app for local use. if you use editor.js to visually create game objects, you must start the build_from_editor_to_visual_js_file.js when you have finished. this tool will create visual.js in the starter/ directory along with all your game objects. it takes data from the system folder lib/visual_scripts/ and generates your code. resource js objects used for adding images for animation purposes. this is done using server_instance/res.js. you need to put your images in a folder, for example test_res/ , inside project_instance/res/. next, run the command server_instance/node res.js. after this has finished processing, restart the web page by entering the following in the console: resource.test_res. resource obj...
Game development
hnologies such as html, css, and javascript. the learning area is a good place to go to get started with the basics. port native games to the web if you are a native developer (for example writing games in c++), and you are interested in how you can port your games over to the web, you should learn more about our emscripten tool — this is an llvm to javascript compiler, which takes llvm bytecode (e.g. generated from c/c++ using clang, or from another language) and compiles that into asm.js, which can be run on the web. to get started, see: about emscripten for an introduction including high-level details. download and install for installing the toolchain. emscripten tutorial for a tutorial to teach you how to get started. examples for a list of web game examples, see our exa...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
ajax, which initially stood for asynchronous javascript and xml, is a programming practice of building complex, dynamic webpages using a technology known as xmlhttprequest. ajax allows you to update parts of the dom of an html page instead without the need for a full page refresh. ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). with interactive websites and modern web standards, ajax is gradually being replaced by functions within javascript frameworks and the official fetch api standard. ...
API - MDN Web Docs Glossary: Definitions of Web-related terms
on programming interface) is a set of features and rules that exist inside a software program (the application) enabling interaction with it through software - as opposed to a human user interface. the api can be seen as a simple contract (the interface) between the application offering it and other items, such as third party software or hardware. in web development, an api is generally a set of code features (e.g. methods, properties, events, and urls) that a developer can use in their apps for interacting with components of a user's web browser, or other software/hardware on the user's computer, or third party websites and services. for example: the getusermedia api can be used to grab audio and video from a user's webcam, which can then be used in any way the developer likes, for examp...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
onous javascript and xml) programming technique—now usually simply "ajax", even though json is usually used rather than xml in modern applications—is a mechanism that requests relatively small amounts of data from the server using http, with the result being returned when available rather than immediately. software design asynchronous software design expands upon the concept by building code that allows a program to ask that a task be performed alongside the original task (or tasks), without stopping to wait for the task to complete. when the secondary task is completed, the original task is notified using an agreed-upon mechanism so that it knows the work is done, and that the result, if any, is available. there are a number of programming techniques for implementing asynchronous ...
Block (scripting) - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, a block is a collection of related statements enclosed in braces ("{}"). for example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code inside the block if the condition is true, or skip the whole block if the condition is false. learn more learn about it javascript block statement ...
Block - MDN Web Docs Glossary: Definitions of Web-related terms
...
Boot2Gecko - MDN Web Docs Glossary: Definitions of Web-related terms
boot2gecko (b2g) is the engineering codename for firefox os and refers to builds that haven't yet received official firefox os branding. (firefox os was also often called boot2gecko before the project had an official name.) ...
Bootstrap - MDN Web Docs Glossary: Definitions of Web-related terms
bootstrap is a free, open source html, css, and javascript framework for quickly building responsive websites. initially, bootstrap was called twitter blueprint and was developed by a team working at twitter. it supports responsive design and features predefined design templates that you can use out of the box, or customize for your needs with your code. you don't need to worry about compatibility with other browsers either, as bootstrap is compatible with all modern browsers and newer versions of internet explorer. ...
CMS - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge content management system on wikipedia ...
CORS-safelisted request header - MDN Web Docs Glossary: Definitions of Web-related terms
listed request header: for accept-language and content-language: can only have values consisting of 0-9, a-z, a-z, space or *,-.;=. for accept and content-type: can't contain a cors-unsafe request header byte: 0x00-0x1f (except 0x09 (ht)), "():<>?@[\]{}, and 0x7f (del). for content-type: needs to have a mime type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain. for any header: the value’s length can't be greater than 128. learn more cors-safelisted response header forbidden header name request header ...
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
the same-origin security policy forbids cross-origin access to resources. but cors gives web servers the ability to say they want to opt into allowing cross-origin access to their resources. learn more general knowledge cross-origin resource sharing (cors) on mdn cross-origin resource sharing on wikipedia cors headers access-control-allow-origin indicates whether the response can be shared. ...
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
cr = carriage return (\r, 0x0d in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. lf = line feed (\n, 0x0a in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line. a cr immediately followed by a lf (crlf, \r\n, or 0x0d0a) moves the cursor down to the next line and then to the beginning of the line. ...
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
ion to complete some kind of routine or action. here is a quick example: function greeting(name) { alert('hello ' + name); } function processuserinput(callback) { var name = prompt('please enter your name.'); callback(name); } processuserinput(greeting); the above example is a synchronous callback, as it is executed immediately. note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. a good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. this structure is used in many modern web apis, such as fetch(). learn more general knowledge callback on wikipedia ...
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
st compilers work either ahead-of-time (aot) or just-in-time (jit). as a programmer, you usually invoke aot compilers from a command line or your ide. the most famous, "gcc" is one example. jit compilers are usually transparent to you, used for performance. for instance in the browser: firefox' spidermonkey javascript engine has a jit built-in that will compile javascript in a website to machine code while you're viewing it so it runs faster. projects like webassembly work on making this even better. learn more general knowledge compiler on wikipedia the gnu compiler collection (gcc) learning resources base cs introduction on compilers a big list of learning material on stackoverflow ...
Cross-site scripting - MDN Web Docs Glossary: Definitions of Web-related terms
according to the open web application security project, xss was the seventh most common web app vulnerability in 2017. these attacks succeed if the web app does not employ enough validation or encoding. the user's browser cannot detect the malicious script is untrustworthy, and so gives it access to any cookies, session tokens, or other sensitive site-specific information, or lets the malicious script rewrite the html content. ...
Cryptanalysis - MDN Web Docs Glossary: Definitions of Web-related terms
cryptanalysis creates techniques to break ciphers, in particular by methods more efficient than a brute-force search. in addition to traditional methods like frequency analysis and index of coincidence, cryptanalysis includes more recent methods, like linear cryptanalysis or differential cryptanalysis, that can break more advanced ciphers. ...
Cryptographic hash function - MDN Web Docs Glossary: Definitions of Web-related terms
a cryptographic hash function, also sometimes called a digest function, is a cryptographic primitive transforming a message of arbitrary size into a message of fixed size, called a digest. cryptographic hash functions are used for authentication, digital signatures, and message authentication codes. to be used for cryptography, a hash function must have these qualities: quick to compute (because they are generated frequently) not invertible (each digest could come from a very large number of messages, and only brute-force can generate a message that leads to a given digest) tamper-resistant (any change to a message leads to a different digest) collision-resistant (it should be impossible to find two different messages that produce the same digest) cryptographic hash functions ...
DHTML - MDN Web Docs Glossary: Definitions of Web-related terms
dhtml aggregates the combined functionality of html, css, the dom, and javascript. ...
DOM (Document Object Model) - MDN Web Docs Glossary: Definitions of Web-related terms
the dom (document object model) is an api that represents and interacts with any html or xml document. the dom is a document model loaded in the browser and representing the document as a node tree, where each node represents part of the document (e.g. an element, text string, or comment). the dom is one of the most-used apis on the web because it allows code running in a browser to access and interact with every node in the document. nodes can be created, moved and changed. event listeners can be added to nodes and triggered on occurrence of a given event. dom was not originally specified—it came about when browsers began implementing javascript. this legacy dom is sometimes called dom 0. today, the whatwg maintains the dom living standard. ...
Element - MDN Web Docs Glossary: Definitions of Web-related terms
an element is a part of a webpage. in xml and html, an element may contain a data item or a chunk of text or an image, or perhaps nothing. a typical element includes an opening tag with some attributes, enclosed text content, and a closing tag. elements and tags are not the same things. tags begin or end an element in source code, whereas elements are part of the dom, the document model for displaying the page in the browser. ...
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. ...
Entity - MDN Web Docs Glossary: Definitions of Web-related terms
an html entity is a piece of text ("string") that begins with an ampersand (&) and ends with a semicolon (;) . entities are frequently used to display reserved characters (which would otherwise be interpreted as html code), and invisible characters (like non-breaking spaces). you can also use them in place of other characters that are difficult to type with a standard keyboard. many characters have memorable entities. for example, the entity for the copyright symbol (©) is &copy;. for less memorable characters, such as &#8212; or &#x2014;, you can use a reference chart or decoder tool. reserved characters some special characters are reserved for use in html, meaning that your browser will parse them as html code. for example, if you use the less-than (<) sign, the browser inter...
Exception - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript syntax errors are a very common source of exceptions. ...
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
assign a function to a variable javascript const foo = function() { console.log("foobar"); } // invoke it using the variable foo(); we assigned an anonymous function in a variable, then we used that variable to invoke the function by adding parentheses () at the end. even if your function was named, you can use the variable name to invoke it. naming it will be helpful when debugging your code. but it won't affect the way we invoke it. example | pass a function as an argument javascript function sayhello() { return "hello, "; } function greeting(hellomessage, name) { console.log(hellomessage() + name); } // pass `sayhello` as an argument to `greeting` function greeting(sayhello, "javascript!"); we are passing our sayhello() function as an argument to the greeting() function,...
Fork - MDN Web Docs Glossary: Definitions of Web-related terms
forks are often seen in free and open source software development. ...
Function - MDN Web Docs Glossary: Definitions of Web-related terms
when a function is called, arguments are passed to the function as input, and the function can optionally return a value. a function in javascript is also an object. a function name is an identifier included as part of a function declaration or function expression. the function name's scope depends on whether the function name is a declaration or expression. different types of functions an anonymous function is a function without a function name. ...
GPL - MDN Web Docs Glossary: Definitions of Web-related terms
the (gnu) gpl (general public license) is a copyleft free software license published by the free software foundation. users of a gpl-licensed program are granted the freedom to use it, read the source code, modify it and redistribute the changes they made, provided they redistribute the program (modified or unmodified) under the same license. learn more faq on gnu licenses gnu gpl on wikipedia gpl license text ...
Git - MDN Web Docs Glossary: Definitions of Web-related terms
what sets it apart from previous scm systems is the ability to do common operations (branching, committing, etc.) on your local development machine, without having to change the master repository or even having write access to it. ...
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
a global object is an object that always exists in the global scope. in javascript, there's always a global object defined. in a web browser, when scripts create global variables, they're created as members of the global object. (in node.js this is not the case.) the global object's interface depends on the execution context in which the script is running. for example: in a web browser, any code which the script doesn't specifically start up as a background task has a window as its global object. this is the vast majority of javascript code on the web. code running in a worker has a workerglobalscope object as its global object. scripts running under node.js have an object called global as their global object. window object in the browser the window object is the global object in th...
Global scope - MDN Web Docs Glossary: Definitions of Web-related terms
in a programming environment, the global scope is the scope that contains, and is visible in, all other scopes. in client-side javascript, the global scope is generally the web page inside which all the code is being executed. learn more learn about it introduction to variable scope in javascript scope on wikipedia ...
HTML - MDN Web Docs Glossary: Definitions of Web-related terms
any text, for instance <img>. ...
HTTP/2 - MDN Web Docs Glossary: Definitions of Web-related terms
tp network protocol. the primary goals for http/2 are to reduce latency by enabling full request and response multiplexing, minimize protocol overhead via efficient compression of http header fields, and add support for request prioritization and server push. http/2 does not modify the application semantics of http in any way. all the core concepts found in http 1.1, such as http methods, status codes, uris, and header fields, remain in place. instead, http/2 modifies how the data is formatted (framed) and transported between the client and server, both of which manage the entire process, and hides application complexity within the new framing layer. as a result, all existing applications can be delivered without modification. ...
High-level programming language - MDN Web Docs Glossary: Definitions of Web-related terms
-level programming languages, it may use natural language elements, or may automate (or even entirely hide) significant areas of computing systems, making the process of developing simpler and more understandable relative to a lower-level language. the amount of abstraction provided defines how "high-level" a programming language is. the idea of a language automatically translatable into machine code, but nearer to human logic, was introduced in computer science in the 1950s, especially thanks to the work of john backus (ibm), to whom it owes the first high-level language to have been widely circulated: fortran. for this innovation backus received the turing prize. ...
I18N - MDN Web Docs Glossary: Definitions of Web-related terms
best practice that enables products or services to be readily adapted to any target culture. internationalization is the design and development of a product, application or document content that enables easy localization for target audiences that vary in culture, region, or language. ...
IDE - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge ide on wikipedia ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
an idl (interface description language) is a generic language used to specified objects' interfaces apart from any specific programming language. content versus idl attributes in html, most attributes have two faces: the content attribute and the idl (interface definition language) attribute. the content attribute is the attribute as you set it from the content (the html code) and you can set it or get it via element.setattribute() or element.getattribute(). the content attribute is always a string even when the expected value should be an integer. for example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setattribute("maxlength", "42") on that element. the idl attribute is also known as a javascript property. these are the attributes yo...
ITU - MDN Web Docs Glossary: Definitions of Web-related terms
the international telecommunication union (itu) is the organization authorized by the united nations to establish standards and rules for telecommunication, including telegraph, radio, telephony and the internet. from defining rules for ensuring transmissions get to where they need to go to and creating the "sos" alert signal used in morse code, the itu has long played a key role in how we use technology to exchange information and ideas. in the internet age, the itu's role of establishing standards for video and audio data formats used for streaming, teleconferencing, and other purposes. for example, the itu and the moving picture experts group (mpeg) worked together to develop and publish, as well as to maintain, the various mpeg specifications, such as mpeg-2 (itu h.262), avc (itu ...
Internationalization - MDN Web Docs Glossary: Definitions of Web-related terms
...
Java - MDN Web Docs Glossary: Definitions of Web-related terms
java is a compiled, object-oriented, highly portable programming language. java is statically typed and features a similar syntax to c. it comes with a large library of readily usable functions, the java software development kit (sdk). programs are compiled only once ahead of time into a proprietary byte code and package format that runs inside the java virtual machine (jvm). the jvm is available across many platforms, which allows java programs to run almost everywhere without the need to be compiled or packaged again. this makes it a preferred language in many large enterprises with heterogenous landscapes, but may be perceived "heavy". learn more general knowledge java on wikipedia ...
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
e the browser. ...
Latency - MDN Web Docs Glossary: Definitions of Web-related terms
ested resource to reach its destination. low latency is good, meaning there is little or no delay. high latency is bad, meaning it takes a long time for the requested resource to reach its destination. latency can be a factor in any kind of data flow, but is most commonly discussed in terms of network latency (the time it takes for a packet of data to travel from source to destination) and media codec latency (the time it takes for the source data to be encoded or decoded and reach the consumer of the resulting data). learn more understanding latency ...
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
controller could handle this directly without needing to update the model. mvc on the web as a web developer, this pattern will probably be quite familiar even if you've never consciously used it before. your data model is probably contained in some kind of database (be it a traditional server-side database like mysql, or a client-side solution such as indexeddb [en-us].) your app's controlling code is probably written in html/javascript, and your user interface is probably written using html/css/whatever else you like. this sounds very much like mvc, but mvc makes these components follow a more rigid pattern. in the early days of the web, mvc architecture was mostly implemented on the server-side, with the client requesting updates via forms or links, and receiving updated views back to di...
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
point to a new value, but the previous value is still held in memory. hence the need for garbage collection.) a mutable object is an object whose state can be modified after it is created. immutables are the objects whose state cannot be changed once the object is created. strings and numbers are immutable. lets understand this with an example: var immutablestring = "hello"; // in the above code, a new object with string value is created. immutablestring = immutablestring + "world"; // we are now appending "world" to the existing value. on appending the "immutablestring" with a string value, following events occur: existing value of "immutablestring" is retrieved "world" is appended to the existing value of "immutablestring" the resultant value is then allocated to a new block o...
Netscape Navigator - MDN Web Docs Glossary: Definitions of Web-related terms
netscape helped make the web graphical rather than a text-only experience. many browsing features became standard after netscape introduced them. netscape could display a webpage while loading, used javascript for forms and interactive content, and stored session information in cookies. ...
Parser - MDN Web Docs Glossary: Definitions of Web-related terms
more generally, it's a piece of software that parses text and transforms its content to another representation. ...
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a polyfill could be used to mimic the functionality of an html canvas element on microsoft internet explorer 7 using a silverlight plugin or mimic support for css rem units, or text-shadow, or whatever you want. the reason why polyfills are not used exclusively is for better functionality and better performance. native implementations of apis can do more and are faster than polyfills. for example, the object.create polyfill only contains the functionalities that are possible in a non-native implementation of object.create. ...
Polymorphism - MDN Web Docs Glossary: Definitions of Web-related terms
polymorphism is the presentation of one interface for multiple data types. for example, integers, floats, and doubles are implicitly polymorphic: regardless of their different types, they can all be added, subtracted, multiplied, and so on. in the case of oop, by making the class responsible for its code as well as its own data, polymorphism can be achieved in that each class has its own function that (once called) behaves properly for any object. learn more general knowledge polymorphism on wikipedia ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
um += 2; } // another function trying to do the same thing function addtwo_v2(foo) { foo += 2; } // calling our first function while passing our primitive as an argument addtwo(foo); // getting the current primitive value console.log(foo); // 5 // trying again with our second function... addtwo_v2(foo); console.log(foo); // 5 did you expect it to be 7 instead of 5? if so, read how this code runs: for both the addtwo and addtwo_v2 functions calls, javascript looks up the value for the identifier foo. it correctly finds our variable instantiated with our first statement after finding it, the expression is evaluated, foo is replaced by 5 and the javascript engine passes that value to the functions as an argument before executing the statements inside the functions' bodies, javascr...
Progressive Enhancement - MDN Web Docs Glossary: Definitions of Web-related terms
feature detection is generally used to determine whether browsers can handle more modern functionality, while polyfills are often used to add missing features with javascript. special notice should be taken of accessibility. ...
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
the act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. a recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion). examples recursive function calls itself until condition met the following python code defines a function that takes a number, prints it, and then calls itself again with the number's value -1. it keeps going until the number is equal to 0, in which case it stops. def recurse(x): if x > 0: print(x) recurse(x - 1) recurse(10) the output will look like this: 10 9 8 7 6 5 4 3 2 1 0 learn more general knowledge recursion (computer science) on wikipedia more details about recursion in javascript ...
Repo - MDN Web Docs Glossary: Definitions of Web-related terms
in a revision control system like git or svn, a repo (i.e. "repository") is a place that hosts an application's code source, together with various metadata. learn more repository on wikipedia ...
SDP - MDN Web Docs Glossary: Definitions of Web-related terms
here is a typical sdp message: v=0 o=alice 2890844526 2890844526 in ip4 host.anywhere.com s= c=in ip4 host.anywhere.com t=0 0 m=audio 49170 rtp/avp 0 a=rtpmap:0 pcmu/8000 m=video 51372 rtp/avp 31 a=rtpmap:31 h261/90000 m=video 53000 rtp/avp 32 a=rtpmap:32 mpv/90000 sdp is never used alone, but by protocols like rtp and rtsp. sdp is also as component of webrtc, which uses sdp as a way of describing a session. ...
SVN - MDN Web Docs Glossary: Definitions of Web-related terms
although svn can also handle binary files, we do not recommend that you use it for such files. ...
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions. ...
Server - MDN Web Docs Glossary: Definitions of Web-related terms
computer on a network, usually powerful and housed in a data center. a software server (often running on a hardware server) is a program that provides services to client programs or a user interface to human clients. services are provided generally over local area networks or wide area networks such as the internet. a client program and server program traditionally connect by passing messages encoded using a protocol over an api. for example: an internet-connected web server is sending a html file to your browser software so that you can read this page local area network server for file, name, mail, print, and fax minicomputers, mainframes, and super computers at data centers learn more general knowledge introduction to servers server (computing) on wikipedia ...
Shim - MDN Web Docs Glossary: Definitions of Web-related terms
this differs from a polyfill, which implements a new api that is not supported by the stock browser as shipped. ...
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
led on an object called myobject. the method is installed on the prototype of myobject (thus it is an instance method) as opposed to being a static method. the name of the method is myfunction. the method accepts one parameter, which is called value and is not further defined. signatures in java in java, signatures are used to identify methods and classes at the level of the virtual machine code. you have to declare types of variables in your code in order to be able to run the java code. java is strictly typed and will check any parameters at compilation time if they are correct. public static void main(string[] args) the public keyword is an access modifier and indicates that this method can be called by any object. the static keyword indicates that this method is a class method a...
Sloppy mode - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge "strict mode" in chapter 7 ("javascript syntax") in the book speaking javascript. ...
Statement - MDN Web Docs Glossary: Definitions of Web-related terms
every program consists of a sequence of statements. ...
Syntax error - MDN Web Docs Glossary: Definitions of Web-related terms
for example, if you leave off a closing brace (}) when defining a javascript function, you trigger a syntax error. ...
Synthetic monitoring - MDN Web Docs Glossary: Definitions of Web-related terms
however, it doesn't necessarily reflect what users are experiencing. ...
TLD - MDN Web Docs Glossary: Definitions of Web-related terms
ship, or nationality of a website. consider an example internet address: https://developer.mozilla.org here org is the tld; mozilla.org is the second-level domain name; and developer is a subdomain name. all together, these constitute a fully-qualified domain name; the addition of https:// makes this a complete url. iana today distinguishes the following groups of top-level domains: country-code top-level domains (cctld) two-character domains established for countries or territories. example: .us for united states. internationalized country code top-level domains (idn cctld) cctlds in non-latin character sets (e.g., arabic or chinese). generic top-level domains (gtld) top-level domains with three or more characters. unsponsored top-level domains domains that operate directly under...
Type conversion - MDN Web Docs Glossary: Definitions of Web-related terms
type conversion (or typecasting) means transfer of data from one data type to another. implicit conversion happens when the compiler automatically assigns data types, but the source code can also explicitly require a conversion to take place. for example, given the instruction 5+2.0, the floating point 2.0 is implicitly typecasted into an integer, but given the instruction number("0x11"), the string "0x11" is explicitly typecasted as the number 17. ...
Validator - MDN Web Docs Glossary: Definitions of Web-related terms
validators can be created for any format or language, but in our context we speak of tools that check html, css, and xml. ...
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
developers should wait to include the unprefixed property until browser behavior is standardized. browser vendors are working to stop using vendor prefixes for experimental features. ...
WebIDL - MDN Web Docs Glossary: Definitions of Web-related terms
webidl is the interface description language used to describe the data types, interfaces, methods, properties, and other components which make up a web application programming interface (api). it uses a somewhat stylized syntax which is independent of any specific programming language, so that the underlying code which is used to build each api can be written in whatever language is most appropriate, while still being possible to map the api's components to javascript-compatible constructs. webidl is used in nearly every api specification for the web, and due to its standard format and syntax, the programmers who create web browsers can more easily ensure that their browsers are compatible with one another, regardless of how they choose to write the code to implement the api. learn m...
Whitespace - MDN Web Docs Glossary: Definitions of Web-related terms
d cr, and u+0020 space. in the form of text, they are treated as normal space characters and sequential whitespaces are collapsed as a single space in many cases (this behavior can be changed by the white-space css property. they are also used as a separator of an element name and its parameters, class names, and so on. in javascript ecmascript® 2015 language specification specifies several unicode codepoints as white space: u+0009 character tabulation <tab>, u+000b line tabulation <vt>, u+000c form feed <ff>, u+0020 space <sp>, u+00a0 no-break space <nbsp>, u+feff zero width no-break space <zwnbsp> and other category “zs” any other unicode “separator, space” code point <usp>. these characters are usually unnecessary for the functionality of the code. ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
xml inclusions (xinclude) is a w3c recommendation to allow inclusion of xml more different sources in a more convenient fashion than xml external entities. when used in conjunction with xpointer (firefox supports a subset of it, and is used in the code sample below), xinclude can also target just specific portions of a document for inclusion. firefox does not support it natively, but the following function aims to allow its use with documents passed into it. code sample the following code aims to let <xi:include> and <xi:fallback> tags (the two elements in the language) with all of the attributes of <xi:include> be included in an xml document so as to be resolvable into a single xml document. (note that this has not been thoroughly tested for all circumstances and may not necessaril...
XLink - MDN Web Docs Glossary: Definitions of Web-related terms
s a plain xml document with xlinks and attempts to click on the relevant points in the xml tree. for those who may have found xlink 1.0 cumbersome for regular links, xlink 1.1 drops the need to specify xlink:type="simple" for simple links. xlink is used in svg, mathml, and other important standards. specification xlink 1.0 xlink 1.1 (currently a working draft) see also xml in mozilla code snippets:getattributens - a wrapper for dealing with some browsers not supporting this dom method code snippets:xml:base function - a rough attempt to find a full xlink-based on an xlink:href attribute (or <xi:include href=>) and its or an ancestor's xml:base. ...
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
eable, that is either a get or a head method. a response to a post or patch request can also be cached if freshness is indicated and the content-location header is set, but this is rarely implemented. (for example, firefox does not support it per https://bugzilla.mozilla.org/show_bug.cgi?id=109553.) other methods, like put or delete are not cacheable and their result cannot be cached. the status code of the response is known by the application caching, and it is considered cacheable. the following status code are cacheable: 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501. there are specific headers in the response, like cache-control, that prevents caching. note that some non-cacheable requests/responses to a specific uri may invalidate previously cached responses on the same uri...
Character - MDN Web Docs Glossary: Definitions of Web-related terms
a character is either a symbol (letters, numbers, punctuation) or non-printing "control" (e.g., carriage return or soft hyphen). utf-8 is the most common character set and includes the graphemes of the most popular human languages. learn more general knowledge character (computing) on wikipedia character encoding on wikipedia ascii on wikipedia utf-8 on wikipedia unicode on wikipedia ...
Character set - MDN Web Docs Glossary: Definitions of Web-related terms
a character set is an encoding system to let computers know how to recognize character, including letters, numbers, punctuation marks, and whitespace. in earlier times, countries developed their own character sets due to their different languages used, such as kanji jis codes (e.g. shift-jis, euc-jp, etc.) for japanese, big5 for traditional chinese, and koi8-r for russian. however, unicode gradually became most acceptable character set for its universal language support. if a character set is used incorrectly (for example, unicode for an acticle encoded in big5), you may see nothing but broken characters, which are called mojibake. ...
Event - MDN Web Docs Glossary: Definitions of Web-related terms
events are assets generated by dom elements, which can be manipulated by a javascript code. learn more technical reference event documentation on mdn general knowledge official website dom events on wikipedia ...
minification - MDN Web Docs Glossary: Definitions of Web-related terms
minification is the process of removing unnecessary or redundant data without affecting how a resource is processed by the browser. minification can include the removal of code comments, white space, and unused code, as well as the shortening of variable and function names. minification is used to improve web performance by reducing file size. it is generally an automated step that occurs at build time. as minification makes code less legible to humans, developer tools have 'prettification' features that can add white space back into the code to make it a bit more legible. ...
Strict mode - MDN Web Docs Glossary: Definitions of Web-related terms
javascript's strict mode is a way to opt in to a restricted variant of javascript, thereby implicitly opting-out of "sloppy mode". strict mode isn't just a subset: it intentionally has different semantics from normal code. strict mode for an entire script is invoked by including the statement "use strict"; before any other statements. ...
Accessibility - Learn web development
would be a good idea to either work through at least the first two modules of the html, css, and javascript topics, or perhaps even better, work through the relevant parts of the accessibility module as you work through the related technology topics. note: if you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you can try out most of the code examples in an online coding program such as jsbin or glitch. guides what is accessibility? this article starts off the module with a good look at what accessibility is — this includes what groups of people we need to consider and why, what tools different people use to interact with the web, and how we can make accessibility part of our web development workflow. html: a good basis for a...
Type, class, and ID selectors - Learn web development
have a single id value applied to them. it can select an element that has the id set on it, and you can precede the id with a type selector to only target the element if both the element and id match. you can see both of these uses in the following example: warning: using the same id multiple times in a document may appear to work for styling purposes, but don't do this. it results in invalid code, and will cause strange behavior in many places. note: as we learned in the lesson on specificity, an id has high specificity and will overrule most other selectors. this can make them difficult to deal with. in most cases it is preferable to add a class to the element rather than use an id, however if using the id is the only way to target the element — perhaps because you do not have acces...
Styling tables - Learn web development
d-color: #ff33cc; } earlier on you saw the :nth-child selector being used to select specific child elements. it can also be given a formula as a parameter, so it will select a sequence of elements. the formula 2n-1 would select all the odd numbered children (1, 3, 5, etc.) and the formula 2n would select all the even numbered children (2, 4, 6, etc.) we've used the odd and even keywords in our code, which do exactly the same things as the aforementioned formulae. in this case we are giving the odd and even rows different (lurid) colors. we've also added a repeating background tile to all the body rows, which is just a bit of noise (a semi-transparent .png with a bit of visual distortion on it) to provide some texture. lastly, we've given the entire table a solid background color so that b...
CSS building blocks - Learn web development
derstanding of how to create and manage files, as detailed in dealing with files. basic familiarity with html, as discussed in the introduction to html module. an understanding of the basics of css, as discussed in the css first steps module. note: if you are working on a computer/tablet/another device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles, which cover the most essential parts of the css language. along the way you'll come across plenty of exercises to allow you to test your understanding. cascade and inheritance the aim of this lesson is to develop your understanding of some of the most fundamental concepts of cs...
Floats - Learn web development
ould be regarded as a legacy technique. in this article we'll just concentrate on the proper uses of floats. a simple float example let's explore how to use floats. we'll start with a really simple example involving floating a block of text around an element. you can follow along by creating a new index.html file on your computer, filling it with a simple html template, and inserting the below code into it at the appropriate places. at the bottom of the section, you can see a live example of what the final code should look like. first, we'll start off with some simple html — add the following to your html body, removing anything that was inside there before: <h1>simple float example</h1> <div class="box">float</div> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. nulla luc...
Grids - Learn web development
div>five</div> <div>six</div> <div>seven</div> </div> note: the *gap properties used to be prefixed by grid-, but this has been changed in the spec, as the intention is to make them usable in multiple layout methods. the prefixed versions will be maintained as an alias so will be safe to use for some time. to be on the safe side, you could double up and add both properties to make your code more bulletproof. .container { display: grid; grid-template-columns: 2fr 1fr 1fr; grid-gap: 20px; gap: 20px; } repeating track listings you can repeat all, or a section of, your track listing using repeat notation. change your track listing to the following: .container { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px; } you will now get 3 1fr tracks...
Multiple-column layout - Learn web development
to learn how to create multiple-column layout on webpages, such as you might find in a newspaper. a basic example we will now explore how to use multiple-column layout, often referred to as multicol. you can follow along by downloading the multicol starting point file and adding the css into the appropriate places. at the bottom of the section you can see a live example of what the final code should look like. our starting point contains some very simple html; a wrapper with a class of container inside which is a heading and some paragraphs. the <div> with a class of container will become our multicol container. we switch on multicol by using one of two properties column-count or column-width. the column-count property will create as many columns as the value you give it, so if you ...
CSS layout - Learn web development
es before starting this module, you should already: have basic familiarity with html, as discussed in the introduction to html module. be comfortable with css fundamentals, as discussed in introduction to css. understand how to style boxes. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides these articles will provide instruction on the fundamental layout tools and techniques available in css. at the end of the lessons is an assessment to help you check your understanding of layout methods, by laying out a webpage. introduction to css layout this article will recap some of the css layout features we've alrea...
How CSS works - Learn web development
ug and maintain your css because the dom is where your css and the document's content meet up. when you start working with browser devtools you will be navigating the dom as you select items in order to see which rules apply. a real dom representation rather than a long, boring explanation, let's look at an example to see how a real html snippet is converted into a dom. take the following html code: <p> let's use: <span>cascading</span> <span>style</span> <span>sheets</span> </p> in the dom, the node corresponding to our <p> element is a parent. its children are a text node and the three nodes corresponding to our <span> elements. the span nodes are also parents, with text nodes as their children: p ├─ "let's use:" ├─ span | └─ "cascading" ├─ span | └─ "sty...
CSS first steps - Learn web development
) a basic work environment set up as detailed in installing basic software, and an understanding of how to create and manage files, as detailed in dealing with files. basic familiarity with html, as discussed in the introduction to html module. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles, which will take you through all the basic theory of css, and provide opportunities for you to test out some skills. what is css? css (cascading style sheets) allows you to create great-looking web pages, but how does it work under the hood? this article explains what css is, wi...
CSS FAQ - Learn web development
Learn › CSS › Howto › CSS FAQ
o bad that other browsers started to implement -webkit- prefixed aliases to improve web compatibility, as specified in the compatibility living standard. in fact most browsers now do not use css prefixes when implementing experimental features, instead implementing those features only on nightly browser versions or similar. if you need to use prefixes in your work, you are advised to write your code in a way that uses the prefixed versions first, but then includes a non-prefixed standard version afterwards so it can automatically override the prefixed versions where supported. for example: -ms-transform: rotate(90deg); -webkit-transform: rotate(90deg); transform: rotate(90deg); note: for more information on dealing with prefixed properties, see handling common html and css problems — ha...
create fancy boxes - Learn web development
let's do some fancy boxes. before we start getting into the practical side of it, make sure you are familiar with the css box model. it's also a good idea, but not a prerequisite, to be familiar with some css layout basics. ...
Styling text - Learn web development
r goal. get started prerequisites before starting this module, you should already have basic familiarity with html, as discussed in the introduction to html module, and be comfortable with css fundamentals, as discussed in introduction to css. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin, codepen or glitch. guides this module contains the following articles, which will teach you all of the essentials behind styling html text content. fundamental text and font styling in this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment a...
How do you make sure your website works properly? - Learn web development
g from a shortterm system overload. the server has some sort of problem. try again in a little while. as beginners checking our (simple) website, we'll deal most often with 200, 304, 403, and 404. fixing the 404 so what went wrong? at first glance, the image we asked for seems to be in the right place... but the network tool reported a "404". it turns out that we made a typo in our html code: unicorn_pics.png rather than unicorn_pic.png. so correct the typo in your code editor by changing the image's src attribute: save, push to the server, and reload the page in your browser: there you go! let's look at the http statuses again: 200 for / and for unicorn_pic.png means that we succeeded in reloading the page and the image. 304 for basic.css means that this file has not chang...
How can we design for all types of users? - Learn web development
rovide alternatives to multimedia content. subtitling/close-captioning you should include captions in your video to cater to visitors who can't hear the audio. some users have hearing challenges, lack functioning speakers, or work in a noisy environment (like on the train). transcript subtitles only work if somebody watches the video. many users don't have time, or lack the proper plugin or codec. additionally, search engines rely mainly on text to index your contents. for all these reasons, please provide a text transcript of the video/audio file. image compression some users may choose to display images, but still have limited bandwidth available, especially in developing countries and on mobile devices. if you want a successful website, please compress your images. there are variou...
How do you host your website on Google App Engine? - Learn web development
that it can take whatever form you like. the app.yaml file is a configuration file that tells app engine how to map urls to your static files. you don't need to edit it. publishing your application now that we've got our project made and sample app files collected together, let's publish our app. open google cloud shell. drag and drop the sample-app folder into the left pane of the code editor. run the following in the command line to select your project: gcloud config set project gaesamplesite then run the following command to go to your app's directory: cd sample-app you are now ready to deploy your application, i.e. upload your app to app engine: gcloud app deploy enter a number to choose the region where you want your application located. enter y to confirm.
How much does it cost to do something on the Web? - Learn web development
e and find out how much each step can cost. summary when launching a website, you may spend nothing, or your costs may go through the roof. in this article we discuss how much everything costs, and how you get what you pay (or don't pay). software text editors you likely have a text editor: such as, notepad on windows, gedit on linux, textedit on mac. you'll have an easier time writing code if you choose an editor that color-codes, checks your syntax, and assists you with code structure. many editors are free, for example atom, brackets, bluefish, textwrangler, eclipse, netbeans, and visual studio code. some, like sublime text, you can test as long as you like, but you're encouraged to pay. some, like phpstorm, can cost between a few dozen and 200 dollars, depending on the plan you...
How do I start to design my website? - Learn web development
hnical side. musicians will never make any music unless they first have an idea of what they want to play—and the same is true for painters, writers, and web developers. technique comes second. technique is obviously critical. musicians must master their instrument. but good musicians can never produce good music without an idea. therefore, before jumping into the technical side—for example, code and tools—you must first step back and decide in detail what you want to do. an hour's discussion with friends is a good start, but inadequate. you must sit down and structure your ideas to get a clear view of what path you must take to make your ideas a reality. to do this, you need only pen and paper and some time to answer at least the following questions. note: there are countless ways t...
What is a URL? - Learn web development
re some extra parts and some extra rules regarding urls, but they are not relevant for regular users or web developers. don't worry about this, you don't need to know them to build and use fully functional urls. you might think of a url like a regular postal mail address: the protocol represents the postal service you want to use, the domain name is the city or town, and the port is like the zip code; the path represents the building where your mail should be delivered; the parameters represent extra information such as the number of the apartment in the building; and, finally, the anchor represents the actual person to whom you've addressed your mail. how to use urls any url can be typed right inside the browser's address bar to get to the resource behind it. but this is only the tip of th...
What is a Domain Name? - Learn web development
on the other hand, let's see if i could register afunkydomainname.org: $ whois afunkydomainname.org not found as you can see, the domain does not exist in the whois database (at the time of writing), so we could ask to register it.
Common questions - Learn web development
through the roof. in this article we discuss how much everything costs and what you get for what you pay (or don't pay). what text editors are available? in this article we highlight some things to think about when choosing and installing a text editor for web development. what are browser developer tools? every browser features a set of devtools for debugging html, css, and other web code. this article explains how to use the basic functions of your browser's devtools. how do you make sure your website works properly? so you've published your website online — very good! but are you sure it works properly? this article provides some basic troubleshooting steps. how do you set up a local testing server? this article explains how to set up a simple local testing ser...
Example 1 - Learn web development
this is the first example of code that explains how to build a custom form widget. basic state html <div class="select"> <span class="value">cherry</span> <ul class="optlist hidden"> <li class="option">cherry</li> <li class="option">lemon</li> <li class="option">banana</li> <li class="option">strawberry</li> <li class="option">apple</li> </ul> </div> css /* --------------- */ /* required styles */ /* --------------- */ .select { position: relative; display : inline-block; } .select.active, .select:focus { box-shadow: 0 0 3px 1px #227755; outline: none; } .select .optlist { position: absolute; top : 100%; left : 0; } .select .optlist.hidden { max-height: 0; visibility: hidden; } /* ------------ */ /* fancy styles */ /* -------...
Example 3 - Learn web development
); }); }); select.addeventlistener('click', function (event) { toggleoptlist(select); }, false); select.addeventlistener('focus', function (event) { activeselect(select, selectlist); }); select.addeventlistener('blur', function (event) { deactivateselect(select); }); select.addeventlistener('keyup', function (event) { if (event.keycode === 27) { deactivateselect(select); } }); }); }); result ...
Example 4 - Learn web development
elect.previouselementsibling.tabindex = -1; updatevalue(select, selectedindex); optionlist.foreach(function (option, index) { option.addeventlistener('click', function (event) { updatevalue(select, index); }); }); select.addeventlistener('keyup', function (event) { var length = optionlist.length, index = getindex(select); if (event.keycode === 27) { deactivateselect(select); } if (event.keycode === 40 && index < length - 1) { index++; } if (event.keycode === 38 && index > 0) { index--; } updatevalue(select, index); }); }); }); result ...
Example 5 - Learn web development
(event) { toggleoptlist(select); }); select.addeventlistener('focus', function (event) { activeselect(select, selectlist); }); select.addeventlistener('blur', function (event) { deactivateselect(select); }); select.addeventlistener('keyup', function (event) { var length = optionlist.length, index = getindex(select); if (event.keycode === 27) { deactivateselect(select); } if (event.keycode === 40 && index < length - 1) { index++; } if (event.keycode === 38 && index > 0) { index--; } updatevalue(select, index); }); }); }); result ...
Other form controls - Learn web development
n drag to increase/decrease the size of the text area. the following screenshots show default, focused, and disabled <textarea> elements in firefox 71 and safari 13 on macos, and edge 18, yandex 14, firefox 71 and chrome 79 on windows 10. note: you can find a slightly more interesting example of text area usage in the example we put together in the first article of the series (see the source code also). controlling multi-line rendering <textarea> accepts three attributes to control its rendering across several lines: cols specifies the visible width (columns) of the text control, measured in average character widths. this is effectively the starting width, as it can be changed by resizing the <textarea>, and overriden using css. the default value if none is specified is 20. rows ...
Example - Learn web development
this is the example code for the article your first html form. a simple form html content <form action="/my-handling-form-page" method="post"> <div> <label for="name">name:</label> <input type="text" id="name" name="user_name"> </div> <div> <label for="mail">e-mail:</label> <input type="email" id="mail" name="user_email"> </div> <div> <label for="msg">message:</label> <textarea id="msg" name="user_message"></textarea> </div> <div class="button"> <button type="submit">send your message</button> </div> </form> css content form { /* just to center the form on the page */ margin: 0 auto; width: 400px; /* to see the limits of the form */ padding: 1em; border: 1px solid #ccc; border-radius: 1em; } div + div { margin-top: ...
Web forms — Working with user data - Learn web development
trying to mix bits of it into the html, css, and javascript topic areas — form elements are more complex than most other html elements, and they also require a close marriage of related css and javascript techniques to get the most out of them. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. introductory guides your first form the first article in our series provides your very first experience of creating a web form, including designing a simple form, implementing it using the right html elements, adding some very simple styling via css, and how data is sent to a server. how to structure a web form with the basics ...
Front-end web developer - Learn web development
n. if you are not sure if front-end web development is for you, and/or you want a gentle introduction before starting a longer and more complete course, work through our getting started with the web module first. getting help we have tried to make learning front-end web development as comfortable as possible, but you will probably still get stuck because you don't understand something, or some code is just not working. don't panic. we all get stuck, whether we are beginner or professional web developers. the learning and getting help article provides you with a series of tips for looking up information and helping yourself. if you are still stuck, feel free to post a question on our discourse forum. let's get started. good luck! the learning pathway getting started time to complete: 1.
Add a hitmap on top of an image - Learn web development
"", provided you furnish appropriate alt text in the <area> elements later on. you will need a special usemap attribute. come up with a unique name, containing no spaces, for your image map. then assign that name (preceded by a hash) as the value for the usemap attribute: <img src="image-map.png" alt="" usemap="#example-map-1" /> step 2: activate your hotspots in this step, put all your code inside a <map> element. <map> only needs one attribute, the same map name as you used in your usemap attribute above: <map name="example-map-1"> </map> inside the <map> element, we need <area> elements. an <area> element corresponds to a single hotspot. to keep keyboard navigation intuitive, make sure the source order of <area> elements corresponds to the visual order of hotspots. <area> elem...
Tips for authoring fast-loading HTML pages - Learn web development
n stop rendering while javascript is still loading. otherwise, the browser will not render anything that is after the script tags that do not have these attributes. note: even though these attributes do help a lot the first time a page is loaded, you should use them but not assume they will work in all browsers. if you already follow all javascript best practices, there is no need to change your code. example page structure · <html> · <head> · <link> ... css files required for page appearance. minimize the number of files for performance while keeping unrelated css in separate files for maintenance. · <script> ... javascript files for functions required during the loading of the page, but not any interaction related javascript that can only run after page lo...
Multimedia and Embedding - Learn web development
before starting this module, you should have a reasonable understanding of the basics of html, as previously covered in introduction to html. if you've not worked through this module (or something similar), work through it first, then come back! note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles which will take you through all the fundamentals of embedding multimedia on webpages. images in html there are other types of multimedia to consider, but it is logical to start with the humble <img> element used to embed a simple image in a webpage. in this article we'll look at...
HTML Tables - Learn web development
Learn › HTML › Tables
have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should already have covered the basics of html — see introduction to html. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles: html table basics this article gets you started with html tables, covering the very basics such as rows and cells, headings, making cells span multiple columns and rows, and how to group together all the cells in a column for styling purposes. html table advanced features and ...
Client-side web APIs - Learn web development
icult to write client-side javascript examples without them. for this tutorial, we will assume that you are knowledgable about the core javascript language, and we will explore common web apis in a bit more detail. basic knowledge of html and css would also be useful. note: if you are working on a device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides introduction to web apis first up, we'll start by looking at apis from a high level — what are they, how do they work, how do you use them in your code, and how are they structured? we'll also take a look at what the different main classes of apis are, and what kind of uses they have. manipulating documents when writin...
JavaScript First Steps - Learn web development
iliarity with html and css. you are advised to work through the following modules before starting on javascript: getting started with the web (which includes a really basic javascript introduction). introduction to html. introduction to css. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides what is javascript? welcome to the mdn beginner's javascript course! in this first article we will look at javascript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with javascript's purpose. a first splash into javascript now you've learned some...
Introducing JavaScript objects - Learn web development
odules before starting on javascript. you should also have some familiarity with javascript basics before looking at javascript objects in detail. before attempting this module, work through javascript first steps and javascript building blocks. note: if you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides object basics in the first article looking at javascript objects, we'll look at fundamental javascript object syntax, and revisit some javascript features we've already looked at earlier on in the course, reiterating the fact that many of the features you've already dealt with are in fact objects. object-oriented javascri...
HTML performance features - Learn web development
complications can occur when, for example, the file size of a <video> embed is too large, or when a webpage is not optimized for mobile devices. this module intends to walk you through the key html performance features that can drastically improve the quality of your webpage. prerequisites: basic computer literacy, basic software installed, and basic knowledge of client-side web technologies. ...
Multimedia: Images - Learn web development
fore resource intensive on the browser's main thread. jpeg2000 — once to be successor to jpeg but only supported in safari. doesn't support progressive display either. in the future browsers might add support for even more advanced formats like high efficiency image file format (heif) or av1 still image file format (avif). given the narrow support for jpeg-xr and jpeg2000, and also taking decode costs into the equation, the only serious contender for jpeg today is webp. which is why you could consider offering your images in that flavor, too, for the browsers that support it. this can be done via the <picture> element with the help of a <source> element equipped with a type attribute. if all of this sounds a bit complicated or feels like too much work for your team then there is also on...
Perceived performance - Learn web development
tricks to help improve performance: minimize initial load to improve perceived performance, minimize the original page load. in other words, first download everything you're going to actually show, but only the stuff you are actually using, then download the rest. if you're downloading all the assets in the end, the weight of all your assets hasn't improved -- in fact, you may need to add some code -- but because the download of non-immediately necessary assets are delayed in a manner that is not perceptible the the user, the user will feel like the download was faster. to minimize the assets required for initial load, separate interactive functionality from content so that required content -- the text, styles, and images visible at initial load -- can be loaded first. delay, or lazy loa...
JavaScript performance - Learn web development
ed. some features requiring complex javascript can be done with a few lines of javascript. requiring a library for other features may improve developer experience, but is all that javascript required? is there a lighter weight or home spun solutions? some features may not be necessary, and though they may add some bling, is the cost of the feature in terms of performance worth it? remove unused code split the javascript into smaller files code-split javascript into critical and non-critical parts. module bundlers like webpack support code-splitting. optimize these smaller files minification reduces the number of characters in your file, thereby reducing the number of bytes or weight of your javascript. gzipping compresses the file further, and should be used even if you don't minify. b...
Web performance - Learn web development
...
Properly configuring server MIME types - Learn web development
ollowing reasons: loss of control if the browser ignores the reported mime type, web administrators and authors no longer have control over how their content is to be processed. for example, a web site oriented for web developers might wish to send certain example html documents as either text/html or text/plain in order to have the documents either processed and displayed as html or as source code. if the browser guesses the mime type, this option is no longer available to the author. security some content types, such as executable programs, are inherently unsafe. for this reason these mime types are usually restricted in terms of what actions a web browser will take when given content of that type. an executable program should not be executed on the user's computer and at most should ca...
Routing in Ember - Learn web development
y the "index"/default, "active", and "completed" routes. summary congratulations! you've finished this tutorial! there is a lot more to be implemented before what we've covered here has parity with the original todomvc app, such as editing, deleting, and persisting todos across page reloads. to see our finished ember implementation, checkout the finished app folder in the repository for the code of this tutorial or see the live deployed version here. study the code to learn more about ember, and also check out the next article, which provides links to more resources and some troubleshooting advice. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react ...
React resources - Learn web development
dered. for this app, we could have for example written a dedicated form.css file to house the styles of those respective components, then imported the styles into their respective modules like this: import form from './form'; import './form.css' this approach makes it easy to identify and manage the css that belongs to a specific component. however, it also fragments your stylesheet across your codebase, and this fragmentation might not be worthwhile. for larger applications with hundreds of unique views and lots of moving parts, it makes sense to limit the amount of irrelevant code that's sent to your user. you'll likely have app-wide styles and specific component styles that built on top of those. you can read more about component stylesheets in the create-react-app docs. react devtools ...
Using Vue computed properties - Learn web development
to use vue’s computed properties. computed properties work similarly to methods, but only re-run when one of their dependencies changes. in our case, this would only re-run when the todoitems array changes. to create a computed property, we need to add a computed property to our component object, much like the methods property we've used previously. adding a summary counter add the following code to your app component object, below the methods property. the list summary method will get the number of finished todoitems, and return a string reporting this. computed: { listsummary() { const numberfinisheditems = this.todoitems.filter(item =>item.done).length return `${numberfinisheditems} out of ${this.todoitems.length} items completed` } } now we can add {{listsummary}} direct...
Rendering a list of Vue components - Learn web development
chance for a slight refactor there's one little bit of refactoring we can do here. instead of generating the id for the checkboxes inside your todoitem component, we can turn the id into a prop. while this isn't strictly necessary, it makes it easier for us to manage since we already need to create a u...
Vue resources - Learn web development
objective: to learn where to go to find further information on vue, to continue your learning. further resources here’s where you should go to learn more about vue: vue docs — the main vue site. contains comprehensive documentation, including examples, cookbooks, and reference material. this is the best place to start learning vue in depth. vue github repo — the vue code itself. this is where you can report issues and/or contribute directly to the vue codebase. studying the vue source code can help you better understand how the framework works, and write better code. vue forum — the official forum for getting help with vue. vue cli docs — documentation for the vue cli. this contains information on customizing and extending the output you are generating via ...
Styling Vue components with CSS - Learn web development
nclude external css files and apply them globally to your app. let's look at how this is done. to start with, create a file called reset.css in the src/assets directory. files in this folder get processed by webpack. this means we can use css pre-processors (like scss) or post-processors (like postcss). while this tutorial will not be using such tools, it's good to know that when including such code in the assets folder it will be processed automatically. add the following contents to the reset.css file: /*reset.css*/ /* resets */ *, *::before, *::after { box-sizing: border-box; } *:focus { outline: 3px dashed #228bec; } html { font: 62.5% / 1.15 sans-serif; } h1, h2 { margin-bottom: 0; } ul { list-style: none; padding: 0; } button { border: none; margin: 0; padding: 0; ...
Understanding client-side web development tools - Learn web development
articles in the series we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. we'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on netlify. in this article we'll introduce the case study, set up our development environment, and set up our code transformation tools. 5. deploying our app in the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process. ...
Web APIs: Mozilla-specific documents
...
omni.ja (formerly omni.jar)
st file. /chrome/ user interface files for the application /chrome/localized.manifest manifest of localized content; referenced by the main chrome manifest file. /chrome/nonlocalized.manifest manifest of non-localized content; referenced by the main chrome manifest file. /components/ xpcom components the application relies upon. /defaults/ default preference files. /modules javascript code modules. /res/ miscellaneous resource files. ...
Accessibility/LiveRegionDevGuide
developer's guide lays out general guidelines that assistive technology (at) developers can use in developing live region support. this guide was written from an atk/at-spi point of view as part of the orca live region support project. however, many of the concepts were also used during the development of firevox, an at using iaccessible2. sometimes the very best guide for some developers is the code itself. please refer to the liveregions and gecko python modules in orca for a real world example. for more information about live regions, please read the aria properties spec or the live region report to learn about aria live region markup and the live region api support document for the latest firefox api with regards to live regions. as always, we're open to questions and suggestions for chan...
Software accessibility: Where are we today?
e to make it accessible. these companies were often reluctant for various reasons including the large amount of time required to do so. on a positive note, recent federal purchasing rules such as section 508 have caused many companies to pay attention and implement msaa support. enter open source software microsoft was on the right track with microsoft active accessibility, but because the source code to most popular desktop applications which are used in large corporations is not publicly available, they were never made fully accessible. in open source, however, making the necessary modifications to make them accessible is very possible. open source software is an ideal way to the needs of disabled users, because accessibility can be fully integrated into the core designs, rather than tacked ...
A bird's-eye view of the Mozilla framework
uch as clicking a link in the contents panel of the help viewer window shown below. the article focuses on the architecture of the overall framework supporting the mozilla application suite, not the architecture of the individual applications themselves. prerequisites this article assumes you have access to mozilla sources and are familiar with the directory structure of the source tree. the code samples in the article are based on mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.9a1) gecko/20051104 seamonkey/1.1a from a new source tree checked out 11/04/05. the build id is 2005110409. thehelp viewer files referenced in the article are located in /seamonkey/extensions/help/ this article also assumes you are familiar with the javascript and c++ programming languages, object-oriented ...
Building Mozilla
in this article, we list documents that will guide you in building firefox or other projects based upon mozilla code. build instructions building on windows with msys building on windows using the msvc toolkit building on fedora core 5 compiling mozilla with mingw compiling mozilla with clang on windows seamonkey building a seamonkey package ...
Building SpiderMonkey with UBSan
from the question of whether cpu overflow flags are set) vptr, a check that requires rtti, which is disabled by default in spidermonkey 4. when you hit a bug and want a stack trace, run under gdb with a breakpoint at the end of __ubsan::diag::~diag(). the stack trace should show a function such as __ubsan_handle_load_invalid_value or __ubsan_handle_type_mismatch being called by the buggy c++ code. (for automated testing outside of gdb, you can instead build with -fsanitize=undefined-trap -fsanitize-undefined-trap-on-error, but then you lose ubsan's diagnostics and the ability to continue past errors.) known bugs. please file new bugs with e.g. [-fsanitize=float-cast-overflow] in the status whiteboard. ...
C++ portability guide
...
Cookies in Mozilla
suggestions as to needed documentation can be directed to mike connor. creating a cookie log steps to create and attach a cookie log in order to aid in triaging a bug in cookies. cookies preferences in mozilla documentation on what the preferences used by the cookies code actually do. original document information author(s): mike connor last updated date: march 15, 2004 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
Creating a Login Manager storage module
ions, refer to the article using nsiloginmanager. overriding the built-in login manager storage consists of two tasks: implement the nsiloginmanagerstorage interface. register that interface in a specific category. some work has already been done to integrate the login manager with the mac os x keychain (bug 106400) and gnome keyring manager (bug 309807). you should start with the existing code if you want to implement that in your extension. to see some debugging output in the console set signon.debug to true using about:config. sample javascript implementation the following code snippet is a javascript component that implements a dummy nsiloginmanagerstorage interface. see how_to_build_an_xpcom_component_in_javascript for more details about javascript components. const cc = compon...
Debugging a hang on OS X (Archived)
warning: the content of this article may be out of date. this article contains historical information about older versions of os x. see how to report a hung firefox instead. if you find a hang in an application, it is very useful for the developer to know where in the code this hang happens, especially if he or she can't reproduce it. below are steps you can use to attach so-called "samples" to bug reports. creating the sample on mac os x 10.5 (xcode < 4.2) when the application is still hung, open up spin control.app (it’s in your <tt>/developer/applications/performance tools/</tt> folder; if it is missing, install the latest computer hardware understanding development (chud) tools from apple). by default, sampling of any hanging application will begin automatically. aft...
HTTP logging
this saves a log of http-related information from your browser run into a file that you can examine (or upload to bugzilla if a developer has asked you for a log). note: the web console also offers the ability to peek at http transactions within firefox. http logging generally provides more detailed logging. using about:networking this is available starting with firefox 52. this is the best and easiest way to do http logging. at any point during while your browser is running, you can turn logging on and off. this allows you to capture only the "interesting" part of the browser's behavior (i.e. ...
Articles for new developers
understand. to help you find the most critical stuff as quickly as possible, we've created this list of the articles you'll find most useful as you get yourself oriented and make your first contributions to the project. also, before you go any further, we'd like to welcome you to the mozilla community of developers! we look forward to your input! contributing to the mozilla code base this page should guide you through the initial steps of contributing to mozilla. welcome, we're delighted to see you! :) ...
Makefiles - Best practices and suggestions
laundry list makefiles should remove all content that it will generate. prefer library rules whenever possible or create library rules that are missing. dependency builds - a second invocation of make within a sandbox should always be a nop. hardcoded values - avoid them like the plague. use variable assignments, autogen paths and dynamic file gathering. platform specific - avoid this logic whenever possible. code as little platform specific logic within a makefile as possible, a conditional and compiler flags at most should be needed. for ex use defines within sources to shift platform logic into your source code. if a unit test is platform specific write your makefile so it can be used on all platforms but only do w...
Callgraph
given the knowledge that evil() does evil things, one could then determine foo() also does evil things. the callgraph project uses gcc and treehydra to generate information about function and method calls at compile time, and aggregates it into a sqlite database. ...
Interface Compatibility
to write binary xpcom components which were compatible with multiple versions of firefox. beginning with mozilla 2 (firefox 4), this will no longer be supported: all @status markings have been removed, and extensions that use binary components will need to recompile for each major version they wish to support. js-ctypes is the recommended way for extensions to call into os or third-party native code. you should strongly consider migrating existing code to use js-ctypes instead of binary components. if necessary, it is possible for an extension to support multiple versions by shipping multiple shared libraries (dlls) in the same extension package, and selecting the correct version using versioning flags in its chrome.manifest file. jsapi, nspr, nss, and other libraries which are currently s...
Commenting IDL for better documentation
the documentation team has tools that convert comments from the doxygen format into the standard reference article format we use here on mdn, with certain limitations. this article will help you understand how you can format your comments to help ensure that the conversion process can be automated as much as possible in order to ensure that your interface gets properly documented. happily, following these recommendations will also help ensure your comments are extremely human-readable, too. don't worry! you don't need to write perfect documentation. that is why mozilla has a couple of writers on-staff as well as a horde of happy volunteers. ...
Multiple Firefox profiles
ase" channel. however, for those more adventurous, you can try one of the other three channels to see what is coming in firefox and play around with emerging features. the beta channel contains the features that are expected to be in the next release of firefox and are in final stages of testing. aurora contains experimental features, which are not yet at beta quality. nightly contains the latest code from firefox developers and is the least stable channel. third-party tools in addition to the built-in profile manager and the external profile manager, there are a few third-party tools that make working with multiple profiles easy. this list is by no means exhaustive. please add any helpful tools you discover to the list! mac os x multifirefox by dave martorana profile management de...
Frame script environment
stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. sendsyncmessage() send a synchronous message to chrome. dump() print a message to the console. atob() base64 decode. btoa() base64 encode. components the usual components object. in particular, note that a frame script accesses the dom window using content, not window: // frame script var links = content.document.getelementsbytagname("a"); all the frame scripts running in a tab share this global. however, any top-level variables defined by a script are not stored on the global:...
Limitations of frame scripts
andler in the chrome process is the xul <browser> receiving the message, and you can get the chrome window from that (note: i'm not really sure how...). nsiaboutmodule by default, custom about: pages registered using nsiaboutmodule are loaded in the chrome process. this means that you can't access their content from the content process (via xhr, for example). you can change this default in the code you use to register the about: uri. see about: and chrome: uris. javascript code modules (jsms) in multiprocess firefox, a jsm loaded into the content process does not share any state with the same jsm loaded into the chrome process. see the entry in the limitations on chrome scripts page. ...
Frame script environment
stop listening to events from content. addmessagelistener() listen to messages from chrome. removemessagelistener() stop listening to messages from chrome. sendasyncmessage() send an asynchronous message to chrome. sendsyncmessage() send a synchronous message to chrome. dump() print a message to the console. atob() base64 decode. btoa() base64 encode. components the usual components object. in particular, note that a frame script accesses the dom window using content, not window: // frame script var links = content.document.getelementsbytagname("a"); all of the frame scripts running in a tab share this global. however, any top-level variables defined by a script are not stored on the glob...
Limitations of frame scripts
stered by the add-on transparently available in the content process. to avoid the shim: if you need to access the content of your about page from the content process, you need to register the nsiaboutmodule in the content process as well as the chrome process. by default, about: pages (except for a small whitelist) are loaded in the chrome process when browsed to from the awesomebar. javascript code modules (jsms) in multiprocess firefox, a jsm loaded into the content process does not share any state with the same jsm loaded into the chrome process. see the entry in the limitations on chrome scripts page. ...
Message manager
message managers provide a way for chrome-privileged javascript code to communicate across process boundaries. they are particularly useful for allowing chrome code, including the browser's code and extension's code, to access web content while the browser is running web content in a separate process. these guides explain how to use message managers in multiprocess firefox. note that none of this requires multiprocess firefox: everything described here will work with single-process firefox, so the same code will work on both variants. guides message manager overview frame script loading and lifetime communicating with frame scripts performance best practices frame script environment limitations of frame scripts process scripts api reference...
Multiprocess Firefox
some elements of multiprocess firefox have been retained for compatibility. this page is an informal index of leftovers, mostly revolving around the message manager and the related cross process object wrappers. message manager a complete guide to the objects used to communicate between chrome code and web content. cross process object wrappers cross process object wrappers are a migration aid, giving chrome code synchronous access to web content. limitations of chrome scripts practices that will no longer work in chrome code, and how to update them. limitation...
Firefox UI considerations for web developers
x96 pixels in size, using a <link> element whose rel attribute is a reference to a file containing an icon of a supported type. <link rel="apple-touch-icon" sizes="128x128" href="touch-icon-128x128.png"> <link rel="apple-touch-icon" sizes="46x46" href="touch-icon-46x46.png"> <link rel="apple-touch-icon" sizes="256x256" href="touch-icon-256x256.png"> <link rel="icon" href="favicon.ico"> in this code, the 128x128 pixel icon will be used by firefox, as it's the smallest icon which is larger than the 96-pixel size it requires. note: only "rich" icons (apple-touch-icon and fluid-icon) support the sizes attribute. you can't specify the size for rel="icon" using the sizes attribute. examples consider again the example top sites box shown at the top of the page, repeated below: let's look a...
HTMLIFrameElement.getStructuredData()
is successful, the request.result is a json object representation of all microdata contained on the page loaded in the browser. parameters none. ...
mozbrowserloadend
the mozbrowserloadend event is fired when the browser <iframe> has finished loading all its assets, or has failed to load. ...
Browser API
browser api concepts and usage the browser api consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-level browser window to the embedded content. this means that window.top, window.parent, window.frameelement, etc. should not reflect the frame hierarchy. ...
Chrome-only API reference
Mozilla › Gecko › Chrome › API
this page lists apis that only run in gecko chrome code (and sometimes in other privileged circumstances). note: most of the apis exposed to the web in general are also usable in chrome code: see web apis for a list of these. browser apithe html browser api is an extension of the html <iframe> element that allows web apps to implement browsers or browser-like applications. it currently works in (privileged) chrome code on firefox desktop (version 47 and above).chromeworkerif you're developing privileged code, and would like to create a worker that can use js-ctypes to perform calls to native code, you can do so by using chromeworker instead of the standard worker object. it works exactly like a standard worker, except that it has access to js-ctypes via a global ctypes object availab...
CSS -moz-bool-pref() @supports function
lable to gecko chrome and ua stylesheets to check if a boolean preference is enabled. syntax -moz-bool-pref( <string> ) parameters <string> the preference name returns evaluates to true if the preference is enabled, false otherwise. example warning: this will only work when loaded from a gecko chrome stylesheet. html <div id="pref-test"> this will have a green background if the <code>test</code> preference is enabled. </div> css @supports -moz-bool-pref("test") { #pref-test { background: green; } } @supports not -moz-bool-pref("test") { #pref-test { background: red; } } result ...
-moz-window-dragging
the property was added in firefox 35 to solve intermittent problems related to firefox windows not being moveable when busy (bug 944836). initial value drag applies to all elements that create native windows, e.g. ...
overflow-clip-box
lip-box: content-box; /* two values */ overflow-clip-box: padding-box content-box; overflow-clip-box: content-box content-box; /* global values */ overflow-clip-box: inherit; overflow-clip-box: initial; overflow-clip-box: unset; note: on gecko, by default, padding-box is used everywhere, but <input type="text"> and similar use the value content-box. prior to firefox 29, this behavior was hardcoded; since then it uses this property that can be used elsewhere too. note that this property is activated by default only in the ua stylesheet and chrome contexts. initial valuepadding-boxapplies toall elementsinheritednomediavisualcomputed valueas specifiedanimation typediscretecanonical orderthe unique non-ambiguous order defined by the formal grammar syntax values padding-box this keywor...
Chrome-only Events reference
ua widgets). mozbeforepaintgecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized. ...
Gecko Chrome
this page contains information specific to chrome code running in gecko. chrome-only api referencethis page lists apis that only run in gecko chrome code (and sometimes in other privileged circumstances.)chrome-only css referencethis page lists css properties that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua stylesheets.) chrome-only events referencethis page lists events that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua widgets). ...
Embedding Tips
ination of state_stop | state_is_network state flags. you may also use the progress listener to query the request supplied in onstatechange for more information. for example, if you wanted to check the server response headers, you might check onstatechange for state_start | state_is_request flags, and from the nsirequest argument qi fornsihttpchanne and call methods on that to determine response codes and other information from the server. it is left as an exercise to make this sample synchronous, i.e. wait for persistence to complete before returning. hint, add a native message processing loop after the call to saveuri that terminates when onstatechange indicates persistence has finished.. how do i print a page? query the web browser object for nsiwebbrowserprint. call the nsiwebbrowserpr...
Roll your own browser: An embedding how-to
); pretty self-explanatory. the apath parameter will be passed to ns_initxpcom. ns_initembedding() must be called from the main thread of your application, otherwise it won't work. do you have any simple examples of embedding mozilla? there are many examples of products already using gecko for embedding. here's a partial list. the sections marked 'mozilla examples' refer to clients and sample code to be found within the mozilla source tree. linux external projects sashxb: ibm uses mozilla to implement part of their sash development/desktop environment. part of the gnome effort. activestate's komodo: development environment, based on mozilla's xul. (screenshot) light: very simple non-bloated gtk+ interface, familiar netscape 4.x keyboard shortcuts, context menus, etc. (screenshot) x...
Gecko SDK
ctions (under include/) import libraries or shared libraries (under lib/) static utility libraries (under lib/) various tools (under bin/) for more information about safely linking xpcom components using the xpcom "glue" library, see xpcom glue. using the mozilla build system with the sdk it's possible to use the mozilla build system with the sdk. this can be done by downloading the source code for firefox and using the --with-libxul-sdk option to configure. resources static xpidl.exe (non-official) if you are looking for a static linked xpidl.exe, you can download here. mac intel gecko 1.8 sdk the official mac 1.8 sdk is a ppc version. this is an unofficial intel build. ...
Gecko
n's user interface. gecko is used in many applications, including a few browsers such as firefox and seamonkey (for a complete list, please refer to wikipedia's article on gecko). products using the same version of gecko have identical support for web standards. documentation chrome this page contains information specific to browser chrome (not google chrome) code running in gecko. gecko faq frequently asked questions about gecko. gecko dom reference reference to the dom. gecko event reference reference to events used within gecko and mozilla applications; for web-standard dom events, see the dom event reference. introduction to layout in mozilla tech talk on layout. embedding mozilla using gecko in y...
Geckoview-Junit Tests
are specified in a text file. each test must be listed on its own line. for example: <class1>#<test1> <class2> <class3>#<test2> <class3>#<test3> to run the tests specified in the file: mozilla-central$ mach geckoview-junit --test-filters-file <path-to-filter-file> disabling one failing test there is no manifest listing the geckoview junit tests. to disable a single test, edit the source code and insert junit's @ignore annotation before the existing @test annotation. for example: import org.junit.ignore ... @runwith(testrunner.class) public class testsomethings { @ignore @test public void testsomething() { ... tests can also be conditionally skipped using junit's assume or assumethat methods. for example: import org.junit.assume.assumethat ... @test fun contentcrashi...
Getting from Content to Layout
ed in relation to the location in the content tree that is being modified and either the relevant frames are created/destroyed or the logic moves up to the parent frame. to give a trivial example of when this might be necessary, consider: "<span>foo <div></div> bar</span>". separate frames are created for the pre and post-div parts of the <span>. if the <div> is removed, the frame construction code merges those frames by examining the parent frame, destroying the two frames created for the <span>, and creating one unified frame for the text content. examples of this type of code are in wipecontainingblock. this code tries hard to avoid unnecessary frame tree modifications and is rather complicated as a result. ...
How to add a build-time test
sets up the right variables, then the rules.mk file will do lots of magic and most of the heavy lifting. a simple example of adding a test is in . note that the following variables are supplied by the rules.mk file: cppsrcs, simple_programs, run_test_program. xpcshell tests here are the simple guidelines for adding an xpcshell test to the build system. for now, enclose your test-related code (in the makefile) with ifdef enable_tests run the test program from the "check" target in the makefile. (example to run the testcookie program) in the test program: if the test fails, exit with a non-zero status and/or print the string "fail" to stdout if the test passes, exit with a zero status and don't print the string "fail" (bonus points for printing "pass" :) ) writ...
How to get a stacktrace for a bug report
ce, and alternative ways to get a stacktrace if you can't get a crash id. requirements you need a binary build of firefox from mozilla.org. seamonkey and thunderbird also support crash reporting. mozilla's crash report server currently only has debug information for mozilla builds and thus the crash reporter cannot work if you use a build from a linux distribution or if you compile from source code. in these cases you will need to use one of the alternative methods listed below. note: when filing a crash report, it is important to know whether the crash occurs with firefox safe mode. this helps engineers determine whether a particular extension or plugin is the cause of the crash. how to get a crash id with the mozilla crash reporter 1. crash and submit a report to the syst...
How to get a stacktrace with WinDbg
visual c++ or visual studio. ...
IME handling guide
ected result form the list in the drop down menu (in the following screenshot, the clause with the thicker underline is called "selected clause"). basically, composition string and each clause style is rendered by gecko. and the drop down menu is created by ime. each clause is represented with selection in the editor. from chrome script, you can check it with nsiselectioncontroller. in native code, you can access it with either nsiselectioncontroller or mozilla::selectiontype (the latter is recommended because of type safer). and editor sets these ime selections from mozilla::textrangetype which are sent by mozilla::widgetcompositionevent as mozilla::textrangearray. following table explains the mapping between them. selection types of each clause of composition string or caret ...
Creating a New Protocol
protocol names start with p, and protocol files must be named pprotocolname.ipdl. ipdl protocols should be in the mozilla namespace or a sub-namespace. to hook up the file to the build, you need to add your ipdl file to ipdl_sources in the nearest moz.build file. see dom/ipc/moz.build for an example. ...
IPC Protocol Definition Language (IPDL)
all messages for multi-process plugins and tabs in firefox are declared in the ipdl language. ...
JavaScript Tips
var uniquename = { _privatemember: 3, publicmember: "a string", init: function() { this.dosomething(this.anothermember); }, dosomething: function(aparam) { alert(aparam); } }; xpconnect don't use object methods and properties more than you have to. it is often faster to store the result in a temporary variable. don't call methods that you don't have to. for instance, windowmanager.getenumerator(atype).hasmoreelements() may be replaced with windowmanager.getmostrecentwindow(atype) != null for a single window. ...
Addon
ainst platformversion a platform version to test against findupdates() starts an update check for this add-on. this will perform asynchronously and deliver results to the given listener. void findupdates( in updatelistener listener, in integer reason, in string appversion, in string platformversion ) parameters listener an updatelistener for the update process reason a reason code for performing the update appversion an application version to check for updates for platformversion a platform version to check for updates for optional methods uninstall() uninstalls this add-on. if possible the uninstall will happen immediately, otherwise it will wait until the next application restart. this method must be defined if an add-on has the permission perm_can_uninstall. v...
AddonInstall
ed. iconurl string the icon of the add-on being installed. releasenotesuri nsiuri the uri of release notes for this install. type string the type of the add-on being installed. state integer the state of the installation. error integer if an error has been encountered during the download or install this will hold the error code. sourceuri nsiuri the uri that the add-on is being installed from. file nsifile the file that the add-on is being installed from. this may be null if the add-on is coming from the internet and has yet to be downloaded. progress integer the progress of any necessary downloads. maxprogress integer the expected size of any necessary downloa...
Add-on Manager
main addonmanager api. all of its functions are asynchronous, meaning that a callback function must be passed to receive the addon instances. the callback may well only be called after the api function returns. for example: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getalladdons(function(aaddons) { // here aaddons is an array of addon objects }); // this code will execute before the code inside the callback notifications about changes to installed add-ons are dispatched to any registered addonlisteners. they must be registered through the addaddonlistener() method. installing new add-ons new add-ons can be installed by using the getinstallforfile() or getinstallforurl() methods on the addonmanager object. these will pass an addoninstall instance t...
Add-on Repository
en the search is completed. results passed to the searchcallback object only include add-ons that are compatible with the current application and are not already installed or in the process of being installed. addonrepository can only process one search at a time. a new search will immediately fail if the addonrepository is already handling another search request. ...
Assert.jsm
the assert.jsm javascript code module implements the commonjs unit testing specification version 1.1, which provides a basic, standardized interface for performing in-code logical assertions with optional, customizable error reporting. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://testing-common/assert.jsm"); the assert class offers methods for performing common logical assertions. method overview undefined ok(value, message); undefined equal(actual, expected, message); undefined notequal(actual, expected, message); undefined deepequal(actual, expected, message); undefined notdeepequal(actual, expected, message); undefined strictequal(actual, expected, message); ...
Dict.jsm
introduced in firefox 5, this is now obsolete and has been removed in firefox 40: use es2015 map. the dict.jsm javascript code module offers routines for managing dictionaries of key/value pairs. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/dict.jsm"); creating a dictionary you can create a new, empty dictionary by simply calling the dict() constructor: var newdict = new dict(); if you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someobj = {}; var newdict = new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type. note: you can actually specify non-strings as keys; these are converted to string...
DownloadLastDir.jsm
the downloadlastdir.jsm javascript code module lets you retrieve the path of the last directory into which a download occurred. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloadlastdir.jsm"); if you are using addon sdk, you can import the code module as: let { cu } = require("chrome"); let downloadlastdir = cu.import("resource://gre/modules/downloadlastdir.jsm").downloadlastdir; once you've imported the module, you can then use the downloadlastdir object it exports. using the downloadlastdir object to determine or set the path into which the last download occurred: // file is an nsifile var file = downloadlastdir.file; downloadlastdir.file = file; you can also set and retrieve this information...
Download
lly. target read only downloadtarget target of this download. totalbytes read only number when hasprogress is true, this indicates the total number of bytes to be transferred before the download finishes; this value can be zero if the file is empty. note: this property's value may not match the actual final size of the downloaded file if the download is encoded during the network transfer. you can use the downloadtarget.size property to get the actual size of the completely-downloaded file once the download has succeeded. when hasprogress is false, this property is always zero. trytokeeppartialdata boolean indicates whether any partially downloaded data should be retained, to use when restarting a failed or canceled downloa...
DownloadError
a downloaderror object provides detailed information about a download failure. properties attribute type description result read only nsresult the result code associated with this error. becausesourcefailed read only boolean indicates an error occurred while reading from the remote location. becausetargetfailed read only boolean indicates an error occurred while writing to the local target. inherits properties from error. ...
DownloadTarget
ero value even if the target file no longer exists, if the value is available in download metadata. if that metadata is no longer available and the file has been deleted, then this value is zero. for single-file downloads, this property's value will always match the actual size of the file on disk, while the download.totalbytes property, when available, may indicate the size of the data as encoded for transfer instead. for downloads of multiple files, such as downloading a web page and its required media to disk, the meaning of this property is undefined. it currently indicates the size of the main file (such as the html document) rather than the sum of all of the files' sizes, but you must not rely upon this behavior, as it is subject to change. this is a dynamic property, whic...
Downloads.jsm
the downloads.jsm javascript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloads.jsm"); method overview promise<download> createdownload(object aproperties); promise<void> fetch(asource, atarget, [optional] object aoptions); promise<downloadlist> getlist(atype); promise<downloadsummary> getsummary(atype); constants constant description public work on downloads that were not started from a private browsing window. pr...
Geometry.jsm
the geometry.jsm javascript code module provides routines for performing common geometry operations on points and rectangles. it exports two classes: point and rect. to use these routines, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/geometry.jsm"); once you've imported the module, you can then use the point and rect classes. note: although this module is usable from mobile, and is present in firefox 4, it's currently not used in firefox 4 and attempting to use it may produce unreliable results there. ...
ISO8601DateUtils.jsm
the iso8601dateutils.jsm javascript code module provides methods that make it easy to convert javascript date objects into iso 8601 format date strings and back. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/iso8601dateutils.jsm"); once you've imported the module, you can then use the iso8601dateutils object it exports. using the iso 8601 date utilities to convert a date string into a date object, simply use: dateobj = iso8601dateutils.parse(datestring); to convert a date object into a date string: datestring = iso8601dateutils.create(dateobj); method overview string create(adate); date parse(adatestring); methods create creates an iso 8601 format date string, e.g. "2010-05-15t13:45:00z", from a jav...
Log.jsm
this module is still under development. until stabilized, expect frequent updates, including different interfaces and behavior in different versions of the platform. progress is tracked in bugzilla using dependencies of bug 451283. the log.jsm javascript code module (formerly named log4moz.js) provides a log4j style api for logging log messages to various endpoints, such as the browser console or a file on disk. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/log.jsm"); basic usage components.utils.import("resource://gre/modules/log.jsm"); // get a logger, give it a name unique to this chunk of code. // use dots to create a hierarchy, this way you can later change // the log level of sets of loggers und...
OS.File.Info
.stat() promise.then( function onsuccess(info) { if ("unixowner" in info) { // info.unixowner holds the owner of the file } else { // information is not available on this platform } } ); evolution of this example bug 802534 will introduce the ability to check whether field unixowner appears in os.file.info.prototype, which will make it possible to write faster code. global object os.file.info methods object tomsg(in os.file.info value) os.file.tomsg convert an instance of os.file.info to a form that can be serialized and transmitted between threads or processes. object tomsg( in os.file.info value ) arguments returns an object with the same fields as value but that may be serialized and transmitted between threads or processes. ...
PromiseUtils.jsm
this method was previously implemented as promise.defer(), which is obsolete since gecko 30. and promiseutils.defer uses dom promise instead of promise.jsm's promise. deferred defer(); parameters none. return value a new object, containing the new promise in the promise property, and the methods to change its state in the resolve and reject properties. ...
Services.jsm
the services.jsm javascript code module offers a wide assortment of lazy getters that simplify the process of obtaining references to commonly used services. to use it, you first need to import the code module into your javascript scope: const {services} = chromeutils.import("resource://gre/modules/services.jsm"); then you can obtain references to services by simply accessing them from the services object exported by the code module. for example, to obtain a reference to the preferences service: var prefsservice = services.prefs; provided service getters service accessor service interface service name androidbridge nsiandroidbridge 1 appinfo nsixulappinfo nsixulruntime application information service appshell nsiappshellserv...
Task.jsm
tasks are built upon generator functions and promises. the task.spawn() function takes a generator function and starts running it as a task. every time the task yields a promise, it waits until the promise is resolved. ...
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). to use timer.jsm, first import it: components.utils.import("resource://gre/modules/timer.jsm"); then call settimeout and cleartimeout just as you would in a dom window, for example: let timeoutid = settimeout(function() { console.log("hello!"); }, 500); cleartimeout(timeoutid); similarly, you can use setinterval and clearinterval like so: let intervalid = setinterval(function() { console.log("happening every 500ms!"); }, 500); clearinterval(intervalid); ...
Encodings for localization files
when creating a localization for mozilla products, it’s important to be aware of the encoding of the files that you generate. in general, files in the mozilla repositories are utf-8 encoded. there are a few exceptions, though. installer the windows installer can’t handle utf-8, but only the codepages provided by windows. this is tricky to hook up in the build process, so here it goes: file encoding notes toolkit/installer/windows/charset.mk ascii the win_installer_charset variable must be set to an encoding which matches toolkit/installer/windows/install.it charset= parameter. see the table below for appropriate values. toolkit/installer/windows/install.it a windows codepage. this must match the charset= parameter in this file, and the ...
L10n Checks
ndows: $ hg clone http://hg.mozilla.org/users/akalla_aviary.pl/silme-patched/ $ cd silme-patched/ $ python setup.py install running it mercurial source (source) mode l10n checks gathers the directories to compare from an ini file, usually found in $app/locales/l10n.ini. you pass both the path to the ini file and the parent directory of the localizations as first arguments, followed by the locale codes of the locales you want to compare. if you want to test the localization for de, run: check-l10n-completeness browser/locales/l10n.ini ../l10n/ de add-ons (xpi) mode l10n checks gathers the locales to compare from the chrome.manifest file inside the xpi file. you pass the path to the xpi file (optionally) followed by the locale codes of the locales you want to compare. if you want to test the l...
Translation phase
add-ons l10n for add-ons is handled by at least two other organizations/services called babelzilla and adofex. they both have created comprehensive programs and l10n tools for localizing any and all third-party add-ons for mozilla applications. visit their websites to learn how to get involved. babelzilla adofex tool-independent localization are you a command-line master? do you prefer unicode text editors to any other applications on earth? do you have a pet cat (computer-assisted translation) tool, like omegat? then you may not be interested in using any of the tools listed above for your localizations. if that is the case, then this section is for you! for localizers who prefer localizing without a specialized tool the workflows for localizing mozilla applications and mozilla websi...
SVN for Localizers
at you understand the mozilla svn repository layout (in particular the layout for mozilla.com), let's get some files into your hands to start localizing! the first thing you need to do is copy the mozilla repository you want to work on to your computer. enter the following command in your command-line tool: svn checkout https://svn.mozilla.org/projects/mozilla.com/trunk/locales/[your locale code] mozilla-l10n-[your-localecode] this command creates the mozilla-l10n-[your-localecode] directory on your computer and copies into it all of the files from https://svn.mozilla.org/projects/moz...om/trunk/locales/[your locale code]. note: the directory you create will be located inside the directory that you're currently in with your console (or cygwin console). also, we use https instead of ht...
Localization sign-off reviews
s revision, the sign-off criteria will be significantly less comprehensive than a technical review. here is some of the criteria we use to perform sign-off reviews: increased amount of untranslated strings we look for previously translated strings changing to untranslated strings in the new revision. this is a common problem with some tools. encoding some tools add bom to utf-8 encoded files, and some change the encoding altogether. mistakenly localized code we look for changes in localized code that should not have been localized or wasn't localized in the previous revision. search plugin changes this greatly impacts productization. we look for these changes and file bugs when they're found in a new revision. further indications of tool-originated corrupti...
Localization technical reviews
l review process, see bug 421893. no utf-7 in the intl.properties file firefox no longer has a utf-7 parser. there should not be any utf-7 encodings in the file toolkit/chrome/global/intl.properties. for more info about utf-7 in firefox, see bug 441876. more intl.properties checkpoints, cont we also check the plural rule for the locale, that the general.useragent.locale is set to the locale code, that accept-lang shows the locale code(s) (like ab, ab-cd,...) and is followed by en and en-us, and finally that intl.menuitems.insertseparatorbeforeaccesskeys = true, where "true" should be left untranslated. inspect firefox-l10n.js we ensure that there are no odd preferences, or #filter substitutions for general.useragent.locale. most locales should have the following: #filter substitutio...
Creating localizable web content
ear, use play on words or colloquialisms. 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. e.g.: a new page is announced with only 100 words but it is actually content added to an existing page in english. happens for things like faq, or video pages for example. for video, use the code to display the video in an overlayed video player on the page instead of linking to a video section in english. per-locale customizations check if there are alternative links for localized pages (e.g., links to mdn, addons.mozilla.org, or other external resources, are there translated equivalents we can use). if there are alternatives, use them by adding the $lang; parameter in the urls eval...
Web Localizability
hould start thinking about making your web app localizable as soon as possible. you will make localizer's life easier, for which they will be grateful. you will have quality content, localized and adapted to the needs of the local market. extending you web app to support new languages will be easy. the content will be easier to maintain and update. you will end up writing more semanticly-correct code, which is good for your seo. by reviewing your content and code for l12y, you will find and fix bugs in your original language too. ...
Fonts for Mozilla's MathML engine
this wiki page describes how users can install and use such math fonts with mozilla's mathml engine. note that most of these instructions may as well apply to other web rendering engines. installation instructions windows install the latin modern math and stix fonts as follows: download latinmodern-math-1959.zip. open the zip archive, move inside the latinmodern-math-1959 directory and then inside the otf directory. you will find a latinmodern-math font file. open the latinmodern-math font file and click the install button. download stixv2.0.2.zip. open the zip archive, move inside the /stixv2.0.0/fonts/otf/ directory. ...
MathML In Action
gzilla to report the discrepancies. bugzilla has a big memory for these things, and besides, how would your problems be fixed if they are not reported?! getting involved is part of your contribution towards enriching gecko with an elegant standards-compliant mathml renderer. your feedback can be manifested by putting mathml content on the web, reporting bugs in bugzilla, and, if you can help with code, inspecting/improving the current code, and/or picking up an item in the todo list. ...
Updates
t! documentation is now available on mdc and wiki.mozilla.org. feel free to complete and improve it! may 8, 2007 mozilla ceo speaks out on the future of firefox: the complete 8,000 word interview. interview to the apc magazine where mitchell baker mentions roger sidje's work on mathml. june 5, 2002 mozilla 1.0 released "by virtue of embedding gecko, mozilla 1.0 and products based on mozilla code support more web standards, more deeply, more consistently across more platforms than any others. mozilla 1.0 features full support for html 4.0, xml 1.0, resource description framework (rdf), cascading style sheets level 1 (css1), and the w3c document object model level 1 (dom1) [...] as well as support for display of mathematical equations using mathml." december 7, 2001 status report octobe...
MathML Demo: <mo> - operator, fence, separator, or accent
following table contains instances of all arrows found on the swp arrows panel. the symbols occur in the context of a simple expression. in general, the lspace and rspace around arrows should be similar to the spacing around relations. there is an issue with the markup of "long" latex arrows in mathml. there are entities from these arrows, &xlarr; &xlarr; &xrarr; etc. but they have no standard unicodes. they can be viewed as stretched versions of short arrows. \longleftarrow can be scripted as <mo>&xlarr;</mo> or as <mo stretchy="true" minsize="1.8">&larr;</mo>. a ↑ b ← c a ⇑ b ⇐ c a ↓ b → c a ⇓ b ⇒ c a ↕ b ↔ c a ⇕ b ⇔ c a ↗ b ↦ c a ↘ b ↩ c ...
MathML Demo: <mspace> - space
mathml demo: <mspace> - space the background color of <mspace> elements has been set to yellow for easier viewing. you can set the width ∑ x y height ∫ x y and depth [ x y ] of mspace elements (click the math text to view the numeric values that are set). interactive sizing html content <p> use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects. <br /> height <a class="control" href="javascript:upheight();" title="increase height">+</a>/ <a class="control" href="javascript:downheight();" title="decrease height">-</a> width <a class="control" href="javascript:upwidth();" title="increase width">+</a>/ <a class="control" href="javascript:downwidth();" title="decrease width">-</a> depth <a class="control...
MathML Demo: <mtable> - tables and matrices
d ⁢ d ⁢ d ] . a table with align="axis2" to anchor the table externally w.r.t. the axis of the second row ---... ab α β abx yab γ δ ab ...--- , but this is subject to variances due to style changes, e.g., from the scriptlevel. ---... ab α β abx yab γ δ ab ...--- . anyway, this is buggy in mozilla because what you see above is a fallback to the rendering code used for the baseline case (see below). a table with align="baseline -1" to anchor the table externally w.r.t. the baseline of the last row ---... d+p ( α β γ δ ) ...--- , neat isn't it? this would be pretty hard to obtain otherwise. contrast it with the following which has align="bottom" ---... d+p ( α β γ δ ) ...--- , and with this one which has align="center -1"...
Mozilla Web Services Security Model
please do not depend on anything in it being correct for security.) to prevent the browser from being used as a tool for web sites to obtain priveleges that belong to the browser's user (such as being behind a firewall or getting the benefits of the user's cookies), web browsers restrict what web pages can do when accessing things in other domains. these restrictions apply to web services. however, web services can be designed to be accessed from other domains, or even from any domain. ...
Mozilla external string guide
these classes were removed a long time ago. the only remaining string classes are the "internal" ones, which are documented xpcom guide internal strings. ...
Mozilla Quirks Mode Behavior
pported on table only in quirks mode (bug 41893). proposed to remove: bug 725646. in quirks mode, when tables have a border style of inset or outset, the border color is based on the background color of the table or of the nearest ancestor with non-transparent background. [this may have been an accurate description when written in june 2001, but it no longer appears correct. i don't follow the code in nscssrenderingborders well enough to tell, though.] in quirks mode a fixed width specified on a table cell resets the nowrap attribute. if the nowrap attribute is present the cell width will never be smaller than the specified fixed width (bug 277232). in quirks mode, tables with no rows/rowgroups have zero height even when a height is specified (bug 241161). something about the overhanging...
mozilla::MonitorAutoEnter
er. to use mozilla::monitorautoenter, declare and initialize it with a reference to a mozilla::monitor. the mozilla::monitorautoenter constructor will enter() the underlying mozilla::monitor automatically. when the mozilla::monitorautoenter goes out of scope, its destructor will exit() the underlying mozilla::monitorautoenter. important: when a mozilla::monitorautoenter is live on the stack, your code is guaranteed to own the underlying mozilla::monitor. constructors monitorautoenter( in mozilla::monitor& monitor; ); this parameter is a reference so as to guarantee that your code has already properly constructed the mozilla::monitor. methods wait() nsresult wait( in printervaltime interval = pr_interval_no_timeout ); wait on the underlying monitor until it is notifyed. notify() nsres...
Build Metrics
lower is better. static constructors are undesirable because their initialization imposes an unavoidable time penalty every time firefox is started. installer size size in bytes of the firefox installer. lower is better here, especially on space-restricted platforms like android. ...
BloatView
} mytype::~mytype() { moz_count_dtor(mytype); ... } ...
Investigating leaks using DMD heap scan mode
these entries and place it into three categories: strong reference known to the cycle collector, weak reference, or something else! the goal is to eventually shrink down the “something else” category until there are only as many things in it as there are unknown references to the leaking object, and then you have your leaker. to place an entry into one of the categories, you must look at the code locations given in the stack trace, and see if you can tell what the object is based on that, then compare that to what find_roots.py told you. for instance, one of the strong references in the cc log is from a head element to its child via mattrsandchildren, and that sounds a lot like this, so we can mark it as being a strong known reference. this is an iterative process, where you first go th...
GPU performance
ormance work with gpus is harder than with cpus because of the asynchronous and massively parallel architecture. tools pix - can do timing of direct3d calls. works reasonably well with firefox. see also debugging with pix. nvidia perfhud - last i checked required a special build to be used. nvidia parallel nsight - haven't tried. amd gpu shaderanalyzer - will compile a shader and show the machine code and give static pipeline estimations. not that useful for firefox because all of our shaders are pretty simple. amd gpu perfstudio - i had trouble getting this to work, and can't remember whether i actually did or not. intel graphics performance analyzers - haven't tried. apitrace - open source, works ok. pvrtrace - doesn't seem to emit traces on android/nexus s. looks like it's designed for x11-...
JS::PerfMeasurement
note: at present, js::perfmeasurement is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. the js::perfmeasurement class, found in jsperf.h, lets you take detailed performance measurements of your code. it is a stopwatch profiler -- that is, it counts events that occur while code of interest is running; it does not do call traces or sampling. the current implementation can measure eleven different types of low-level hardware and software events: events that can be measured bitmask passed to constructor counter variable what it measures perfmeasurement::cpu_cycles .cpu_cycles raw cpu clock cycles ::instructions .instructions total instructions execut...
Memory Profiler
t keep tracks of how objects are allocated. developers have to infer how an object might be allocated and freed by himself/herself. another common approach is to plot the allocations or the memory usages along the timeline. this gives some intuition of how and when a bulk of objects are allocated. however, it still relies on developers' wisdom, and sometimes chances, to dig out the problematical code snippet. this memory profiler is designed to solve the inconveniences and limitations. the goal is to identify the memory eager codes directly. the profiler is designed at the very beginning to support not only javascript but also native codes. naturally, not only javascript objects but also native allocations are tracked. the profile while recording is stored in memory in a very compact format...
dtrace
od starting command for profiling wakeups is the following. sudo dtrace -n 'mach_kernel::wakeup { @[ustack()] = count(); }' -p $firefox_pid > $output_file let's break that down further. the -n option combined with the mach_kernel::wakeup selects a probe point. mach_kernel is the module name and wakeup is the probe name. you can see a complete list of probes by running sudo dtrace -l. the code between the braces is run when the probe point is hit. the above code counts unique stack traces when wakeups occur; ustack is short for "user 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...
Phishing: a short definition
as text messages are widely supported, however, even nist no longer recommends sms verification. the ss7 telephony system is vulnerable, making eavesdropping, or rerouting text messages quite trivial. one-time password algorithms a better way to use phones as second factor, are one-time password (otp) protocols, like totp and hotp. at service registration, the provider will often generate a qr code to be read by an otp app. this qr code is nothing more than a random, secret key, that is stored on the user’s phone. after verifying username and password, the user is prompted to open the otp app and enter the corresponding 6-digit code, representing a hashed version of the secret key and a nonce - potentially time-based. otp is the most widely supported second factor schemes and can be used...
javascript.options.strict
this preference controls whether javascript warnings are logged to the javascript console. example : <html> <head> <title>sample</title> </head> <body> <label id="name">enter you first name</label> <p id ="sample"></p> <script> "use strict" name1= "john" ; // this will cause and an error as variable not declared . var name2= "peter"; document.getelementbyid("sample").innerhtml = name1; </script> </body> </html> possible values and their effects: true: show javascript errors and warnings. false: show javascript errors only. ...
ui.SpellCheckerUnderline
...
ui.textSelectBackground
ui.textselectbackground saves the color in which the background of a text selection in the user interface or in content will be styled. ...
ui.textSelectForeground
ui.textselectforeground saves the color in which the text of a text selection in the user interface or the content will be styled. ...
Preference reference
lipboardevents.enabled lets websites get notifications if the user copies, pastes, or cuts something from a web page, and it lets them know which part of the page had been selected. the emitting of the oncopy, oncut and onpaste events are controlled by this preference. javascript.options.showinconsolethe preference javascript.options.showinconsole controls whether errors or warnings in chrome code are shown in the error console.javascript.options.stricttechnical review completed.mail.tabs.drawintitlebarstarting in thunderbird 17.0, the tabs are drawn in the title bar. the old behavior can be restored by setting the preference mail.tabs.drawintitlebar to false.nglayout.debug.disable xul fastloadthe preference nglayout.debug.disable_xul_fastload controls whether or not xul fastload is used.n...
Preferences system
that display and operate appropriately on various platforms (windows, macos x and gnome). the system is implemented through a few xul elements and attributes. reference information about them is available below: preferences system documentation: introduction: getting started | examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes use code for a typical preferences window may look like this: <prefwindow id="apppreferences" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <prefpane id="pane1" label="&pane1.title;"> <preferences> <preference id="pref1" name="pref.name" type="bool"/> </preferences> .. ui elements that refer to the preferences above, e.g.: <checkbox id="check1" ...
Patches and pushes
e which is linked within the xml file as an uri id. upload your plugins icon image to data kitchen to obtain its uri id and add to the xml file within the image tag. in list.txt, add the search plugin's xml filename (without extensions) on a new line and save. note that if your team selects a local version of an already default plugin (e.g., wikipedia), the xml filename should include the locale code (e.g., wikipedia-es). create a patch of the searchplugins directory by entering the following command in your command-line tool, where mypatch.diff is where you give your patch a name: $ hg add mozilla/browser/searchplugins/ $ hg diff mozilla/browser/searchplugins/ > mypatch.diff attach your patch file to the bug by clicking the "add an attachment" link. once attached and labeled as a patch,...
Profile Manager
not found in firefox's built-in version. downloading binaries you can download profile manager builds from https://ftp.mozilla.org/pub/mozilla.org/utilities/profilemanager/1.0/ note: there is no installer; just extract the files from the archive. system requirements: mac: an intel processor, i386 or x86_64 linux: any version capable of running firefox 4.0 windows: xp or later source code you can download the source as well: hg clone http://hg.mozilla.org/automation/profilemanager/ instructions for building can be found in build.txt. reporting bugs profile manager bugs should be reported in bugzilla, under testing -> profilemanager. starting profile manager to start profile manager, just launch profilemanager.exe (on windows) or profilemanager-bin (on linux and mac). by de...
Firefox Sync
of how sync is implemented or wish to interact with it. general the always prolific richard newman has written a couple of notes about bookmark syncing (first, second) and has a blog where he talks about the various challenges syncing this kind of data. servers documentation for the various servers, including information on how to host your own. android searchfox has links to the main sync code and the storage layer. there are also some notes in a google document (that we really must move to its own wiki page) there's also information available to help debug and diagnose android sync issues. ios there is some in-tree documentation and there are some extensive comments here and here. desktop notes on how to file a good bug for desktop sync. there are some notes on how to run our tp...
Installing JSHydra
building jshydra jshydra requires, as part of its build process, spidermonkey. by default, the configure script will obtain a known working copy of spidermonkey; it is possible via the --moz-src and --moz-obj configure arguments to tell jshydra to use existing copies of the source and build. ...
JSHydra
in its back-end, it uses the parse tree created by the spidermonkey engine. all analysis is performed by running javascripts. documentation installing jshydra download, installation and dependency info for jshydra community view jshydra forums... ...
L20n HTML Bindings
her circles.", masculine: "{{ $user.name }} has invited you to his circles.", *unknown: "{{ $user.name }} has invited you to their circles." }> based on the context data defined above, this will produce: jane has invited you to her circles. monolingual mode l20n can also operate in the so-called monolingual mode, when there is only one locale available. it doesn't have any specific locale code (internally, it's called i-default in compliance to rfc 2277). there is no language negotiation nor locale fallback possible in the monolingual mode. l20n simply always uses this one default locale. the monolingual mode may be useful when you first start a new project, when you want to test something quickly or when using server-side language negotiation. in order to enable the monolingual mode...
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: communications protocols - smtp, pop3, imap, nntp message management, including search and filtering message composition address book the mailnews code lives in the mailnews/ directory of comm-central. asynctestutils extended framework the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird. see mailnews automated testing for a description of the other testing mechanisms. leak and bloat tests this page describes how to perform tests that measure memory leaks and bloat for mailnews and its sub-components. mailnews automated testing ...
Midas editor module security preferences
is means that the corresponding buttons on the mozilla rich text editing demo page will not work. to enable these functions, you must modify your browser preferences. warning: changing these preferences can leave your browser insecure, especially if you grant permission to untrusted sites. only change these settings as needed to try the demo above and to test your own add-on or firefox-internal code, and be sure to restore the default settings when you're done! changing the preferences in firefox quit firefox. if you have quick launch running (on windows, this is an icon in the toolbar), quit that too. find your firefox profile directory. open the user.js file from that directory in a text editor. if there's no user.js file, create one. add these lines to user.js: user_pref("capabi...
Nonblocking IO In NSPR
>pr_accept()</tt> or <tt>pr_acceptread()</tt> on a blocking, listening socket may be a recycled socket previously used in a <tt>pr_transmitfile()</tt> call. since <tt>pr_transmitfile()</tt> only operates in blocking mode, this recycled socket can only be reused in blocking mode, hence the above constraint. because these constraints only apply to nt, it is advised that you test your cross-platform code that uses nonblocking io on nt early in the development cycle. these constraints are enforced in the debug nspr library by assertions. differences from blocking io in nonblocking mode, the timeout argument for the io functions is ignored. <tt>pr_acceptread()</tt> and <tt>pr_transmitfile()</tt> only work on blocking sockets. they do not make sense in nonblocking mode. <tt>pr_write()</tt>, <t...
Anonymous Shared Memory
via helper-functions with pr_createprocess. in the second protocol, the parent process is responsible for creating the child process; the parent and child are mutually responsible for passing a filemap string. nspr provides helper functions for extracting data from the prfilemap object. ... see the examples below. both sides should adhere strictly to the protocol for proper operation. the pseudo-code below shows the use of a file-mapped shared memory by a parent and child processes. in the examples, the server creates the file-mapped shared memory, the client attaches to it. first protocol server: fm = pr_openanonfilemap(dirname, size, filemapprot); addr = pr_memmap(fm); attr = pr_newprocessattr(); pr_processattrsetinheritablefilemap( attr, fm, shmname ); pr_createprocess(client); pr_destr...
Dynamic Library Linking
this section describes nspr's programming interface to load, unload and resolve symbols in dynamic libraries. it also provides a method by which to condition symbols of statically linked code so that to other clients it appears as though they are dynamically loaded. library linking types these data types are defined for dynamic library linking: prlibrary prstaticlinktable library linking functions the library linking functions are: pr_setlibrarypath pr_getlibrarypath pr_getlibraryname pr_freelibraryname pr_loadlibrary pr_unloadlibrary pr_findsymbol pr_findsymbolandlibrary finding symbols defined in the main executable program pr_loadlibrary cannot open a handle that references the main executable program. (this is admittedly an omission that should be fixed.) however, it...
I/O Types
this chapter describes the most common nspr types, enumerations, and structures used with the functions described in i/o functions and network addresses. these include the types used for system access, normal file i/o, and socket (network) i/o. types unique to a particular function are described with the function itself. for sample code that illustrates basic i/o operations, see introduction to nspr. directory type file descriptor types file info types network address types types used with socket options functions type used with memory-mapped i/o offset interpretation for seek functions directory type prdir file descriptor types nspr represents i/o objects, such as open files and sockets, by file descriptors of type prfiledesc. this section introduces prfiledesc and related...
Logging
compile the program with debug defined. before running the compiled program, set the environment variable nspr_log_modules to userstuff:5 static void userlogstuff( void ) { prlogmoduleinfo *mylm; printn i; pr_static_assert(5 > 4); /* nspr 4.6.6 or newer */ mylm = pr_newlogmodule( "userstuff" ); pr_assert( myl...
NSPR Types
different platforms treat 64-bit numeric fields in different ways. some systems require emulation of 64-bit fields by using two 32-bit numeric fields bound in a structure. since the types (long long versus struct longlong) are not type compatible, nspr defines macros to manipulate 64-bit numeric fields. these macros are defined in prlong.h. conscientious use of these macros ensures portability of code to all the platforms supported by nspr and still provides optimal behavior on those systems that treat long long values directly. print64 pruint64 floating-point number type the nspr floating-point type is always 64 bits. prfloat64 native os integer types these types are most appropriate for automatic variables. they are guaranteed to be at least 16 bits, though various architectures...
PRBool
use standard c++ bool instead. otherwise, use prbool for variables and parameter types. ...
PRIOMethods
...
PRJobIoDesc
syntax #include <prtpool.h> typedef struct prjobiodesc { prfiledesc *socket; prerrorcode error; printervaltime timeout; } prjobiodesc; ...
PRStatus
type for status code returned by some functions. syntax #include <prtypes.h> typedef enum { pr_failure = -1, pr_success = 0 } prstatus; ...
PR_Accept
...
PR_Available
ion has the following parameter: fd pointer to a prfiledesc object representing a file or socket. returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it returns the value -1. the error code can then be retrieved via pr_geterror. description pr_available works on normal files and sockets. pr_available does not work with pipes on win32 platforms. see also if the number of bytes available for reading is out of the range of a 32-bit integer, use pr_available64. ...
PR_Available64
ion has the following parameter: fd pointer to a prfiledesc object representing a file or socket. returns the function returns one of the following values: if the function completes successfully, it returns the number of bytes that are available for reading. for a normal file, these are the bytes beyond the current file pointer. if the function fails, it returns the value -1. the error code can then be retrieved via pr_geterror. description pr_available64 works on normal files and sockets. pr_available does not work with pipes on win32 platforms. see also if the number of bytes available for reading is within the range of a 32-bit integer, use pr_available. ...
PR_CloseFileMap
closes a file mapping. syntax #include <prio.h> prstatus pr_closefilemap(prfilemap *fmap); parameter the function has the following parameter: fmap the file mapping to be closed. returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success. if the memory region is not successfully unmapped, pr_failure. the error code can be retrieved via pr_geterror. description when a file mapping created with a call to pr_createfilemap is no longer needed, it should be closed with a call to pr_closefilemap. ...
PR_ConnectContinue
_success. if pr_connectcontinue() returns pr_failure, call pr_geterror(): - pr_in_progress_error: the nonblocking connect is still in progress and has not completed yet. the caller should poll the file descriptor for the in_flags pr_poll_write|pr_poll_except and retry pr_connectcontinue later when pr_poll() returns. - other errors: the nonblocking connect has failed with this error code. description continue a nonblocking connect. after a nonblocking connect is initiated with pr_connect() (which fails with pr_in_progress_error), one should call pr_poll() on the socket, with the in_flags pr_poll_write | pr_poll_except. when pr_poll() returns, one calls pr_connectcontinue() on the socket to determine whether the nonblocking connect has completed or is still in progress. repeat ...
PR_CreatePipe
esc pointer. on return, this parameter contains the file descriptor for the read end of the pipe. writepipe a pointer to a prfiledesc pointer. on return, this parameter contains the file descriptor for the write end of the pipe. returns the function returns one of these values: if the pipe is successfully created, pr_success. if the pipe is not successfully created, pr_failure. the error code can be retrieved via pr_geterror. description pr_createpipe creates an anonymous pipe. data written into the write end of the pipe can be read from the read end of the pipe. pipes are useful for interprocess communication between a parent and a child process. when the pipe is no longer needed, both ends should be closed with calls to pr_close. pr_createpipe is currently implemented on unix, l...
PR_Delete
...
PR_GetCurrentThread
syntax #include <prthread.h> prthread* pr_getcurrentthread(void); returns always returns a valid reference to the calling thread--a self-identity. description the currently running thread may discover its own identity by calling pr_getcurrentthread. note: this is the only safe way to establish the identity of a thread. ...
PR_GetError
returns the current thread's last set platform-independent error code. syntax #include <prerror.h> prerrorcode pr_geterror(void) returns the value returned is a 32-bit number. nspr provides no direct interpretation of the number's value. nspr does use pr_seterror to set error numbers defined in error codes. ...
PR_GetOSError
returns the current thread's last set os-specific error code. syntax #include <prerror.h> print32 pr_getoserror(void) returns the value returned is a 32-bit signed number. its interpretation is left to the caller. description used for platform-specific code that requires the underlying os error. for portability, clients should not create dependencies on the values of os-specific error codes. however, this information is preserved, along with a platform neutral error code, on a per thread basis. it is most useful during development. ...
PR_GetUniqueIdentity
ollowing parameter: layer_name the string associated with the creation of a layer's identity. returns the function returns one of the following values: if successful, the prdescidentity for the layer associated with the string specified in the layer named layer_name. if the function cannot allocate enough dynamic memory, it fails and returns the value pr_invalid_io_layer with the error code pr_out_of_memory_error. description a string may be associated with a layer when the layer is created. pr_getuniqueidentity allocates a unique layer identity and associates it with the string. the string can be subsequently passed to pr_createiolayerstub to create a new file descriptor of that layer. call pr_getuniqueidentity only once for any particular layer name. if you're creating a custo...
PR ImportTCPSocket
blocking mode by calling fcntl to set the o_nonblock file status flag on the native file descriptor, and then nspr will call socket functions such as recv, send, and poll on the native file descriptor. the caller must not do anything to the native file descriptor before the pr_importtcpsocket call that will prevent the native file descriptor from working in non-blocking mode. warning in theory, code that uses pr_importtcpsocket may break when nspr's implementation changes. in practice, this is unlikely to happen because nspr's implementation has been stable for years and because of nspr's strong commitment to backward compatibility. using pr_importtcpsocket is much more convenient than writing an nspr i/o layer that wraps your native tcp sockets. of course, it is best if you just use pr_open...
PR_Interrupt
ed between the thread doing the interrupting and the thread being interrupted. when the interrupted thread reaches the prearranged point, it can communicate with its peer to discover the real reason behind the change in plans. the interrupt request remains in the thread's state until it is delivered exactly once or explicitly canceled. the interrupted thread returns pr_failure (-1) with an error code (see pr_geterror) for blocking operations that return a prstatus (such as i/o operations, monitor waits, or waiting on a condition). to check whether the thread was interrupted, compare the result of pr_geterror with pr_pending_interrupt_error. pr_interrupt may itself fail if the target thread is invalid. bugs pr_interrupt has the following limitations and known bugs: there can be a delay f...
PR_MSEC_PER_SEC
a convenience macro to improve code readability as well as to avoid mistakes in counting the number of zeros; represents the number of milliseconds in a second. syntax #include <prtime.h> #define pr_msec_per_sec 1000ul ...
PR_NSEC_PER_MSEC
a convenience macro to improve code readability as well as to avoid mistakes in counting the number of zeros; represents the number of nanoseconds in a millisecond. syntax #include <prtime.h> #define pr_nsec_per_msec 1000000ul ...
PR_NSEC_PER_SEC
a convenience macro to improve code readability as well as to avoid mistakes in counting the number of zeros; represents the number of nanoseconds in a second. syntax #include <prtime.h> #define pr_nsec_per_sec 1000000000ul ...
PR_NewTCPSocket
n call pr_read or pr_recv. to send data, one can call pr_write, pr_writev, pr_send, or pr_transmitfile. pr_acceptread is suitable for use by the server to accept a new client connection and read the client's first request in one function call. a tcp connection can be shut down by pr_shutdown, and the sockets should be closed by pr_close. see also pr_newtcpsocket is deprecated because it is hardcoded to create an ipv4 tcp socket. new code should use pr_opentcpsocket instead, which allows the address family (ipv4 or ipv6) of the new tcp socket to be specified. ...
PR_NewUDPSocket
l suite. udp datagrams may be lost or delivered in duplicates or out of sequence. pr_newudpsocket creates a new udp socket. the socket may be bound to a well-known port number with pr_bind. datagrams can be sent with pr_sendto and received with pr_recvfrom. when the socket is no longer needed, it should be closed with a call to pr_close. see also pr_newudpsocket is deprecated because it is hardcoded to create an ipv4 udp socket. new code should use pr_openudpsocket instead, which allows the address family (ipv4 or ipv6) of the new udp socket to be specified. ...
PR_OpenSemaphore
nsemaphore( const char *name, printn flags, printn mode, pruintn value ); parameters the function has the following parameters: name the name to be given the semaphore. flags how to create or open the semaphore. mode unix style file mode to be used when creating the semaphore. value the initial value assigned to the semaphore. returns a pointer to a prsem structure or null/code> on error. description if the named semaphore doesn't exist and the pr_sem_create flag is specified, the named semaphore is created. the created semaphore needs to be removed from the system with a pr_deletesemaphore call. if pr_sem_create is specified, the third argument is the access permission bits of the new semaphore (same interpretation as the mode argument to pr_open) and the fourth ar...
PR_PopIOLayer
stack from which the specified layer is to be removed. id identity of the layer to be removed from the stack. returns the function returns one of the following values: if the layer is successfully removed from the stack, a pointer to the removed layer. if the layer is not found in the stack or cannot be popped (for example, the bottommost layer), the function returns null with the error code pr_invalid_argument_error. description pr_popiolayer pops the specified layer from the stack. if the object to be removed is found, pr_popiolayer returns a pointer to the removed object the object then becomes the responsibility of the caller. even if the identity indicates the top layer of the stack, the reference returned is not the file descriptor for the stack and that file descriptor rem...
PR_ProcessExit
...
PR_Rename
following parameters: from the old name of the file to be renamed. to the new name of the file. returns one of the following values: if file is successfully renamed, pr_success. if file is not successfully renamed, pr_failure. description pr_rename renames a file from its old name (from) to a new name (to). if a file with the new name already exists, pr_rename fails with the error code pr_file_exists_error. in this case, pr_rename does not overwrite the existing filename. ...
PR_RmDir
see also pr_mkdir ...
PR_STATIC_ASSERT
syntax #include <prlog.h> pr_static_assert ( expression ); parameters the macro has this parameter: expression any valid expression which evaluates at compile-time to true or false. an expression which cannot be evaluated at compile time will cause a compiler error; see pr_assert for a runtime alternative. returns nothing description this macro evaluates the specified expression. when the result is zero (false) program compilation will fail with a compiler error; otherwise compilation completes successfully. the compiler error will include the number of the line for which the compile-time assertion failed. ...
PR_Seek
seek_end. sets the file pointer to the size of the file plus the value of the offset parameter. returns the function returns one of the following values: if the function completes successfully, it returns the resulting file pointer location, measured in bytes from the beginning of the file. if the function fails, the file pointer remains unchanged and the function returns -1. the error code can then be retrieved with pr_geterror. description here's an idiom for obtaining the current location of the file pointer for the file descriptor fd: pr_seek(fd, 0, pr_seek_cur) see also if you need to move the file pointer by a large offset that's out of the range of a 32-bit integer, use pr_seek64. new code should use pr_seek64 so that it can handle files larger than 2 gb. ...
PR_SetLibraryPath
...
PR_USEC_PER_MSEC
a convenience macro to improve code readability as well as to avoid mistakes in counting the number of zeros; represents the number of microseconds in a millisecond. syntax #include <prtime.h> #define pr_usec_per_msec 1000ul ...
PR_USEC_PER_SEC
a convenience macro to improve code readability as well as to avoid mistakes in counting the number of zeros; represents the number of microseconds in a second. syntax #include <prtime.h> #define pr_usec_per_sec 1000000ul ...
PR_Unmap
void *addr, pruint32 len); parameters the function has the following parameters: addr the starting address of the memory region to be unmapped. len the length, in bytes, of the memory region. returns the function returns one of the following values: if the memory region is successfully unmapped, pr_success. if the memory region is not successfully unmapped, pr_failure. the error code can be retrieved via pr_geterror. description pr_memunmap removes the file mapping for the memory region (addr, addr + len). the parameter addr is the return value of an earlier call to pr_memmap. ...
PR_Wait
rred. it is the responsibility of the programmer to evaluate the data and act accordingly. this is usually done by evaluating a boolean expression involving the monitored data. while the boolean expression is false, the thread should wait. the thread should act on the data only when the expression is true. the boolean expression must be evaluated while in the monitor and within a loop. in pseudo-code, the sequence is as follows: pr_entermonitor(&ml); while (!expression) wait; ... act on the state change ... pr_exitmonitor(&ml); a thread can be resumed from a wait for a variety of reasons. the most obvious is that it was notified by another thread. if the value of timeout is not pr_interval_no_timeout, pr_wait resumes execution after the specified interval has expired. if a timeout value...
PR_Writev
en or the write operation fails. therefore, the return value is equal to either the sum of all the buffer lengths (on success) or -1 (on failure). note that if pr_writev returns -1, part of the data may have been written before an error occurred. if the timeout parameter is not pr_interval_no_timeout and all the data cannot be written in the specified interval, pr_writev returns -1 with the error code pr_io_timeout_error. this is the type definition for priovec: typedef struct priovec { char *iov_base; int iov_len; } priovec; the priovec structure has the following fields: iov_base a pointer to the beginning of the buffer. iov_len the size of the buffer. ...
PR_strtod
n by the ieee round-even rule. the string is scanned up to the first unrecognized character. if the value of se is not (char **) null, pr_strtod stores a pointer to the character terminating the scan in *se. if the answer would overflow, a properly signed huge_val (infinity) is returned. if the answer would underflow, a properly signed 0 is returned. in both cases, pr_geterror() returns the error code pr_range_error. if no number can be formed, se is set to s00, and 0 is returned. ...
Process Initialization
d is a user thread of normal priority. pr_init pr_initialize pr_initialized pr_cleanup pr_disableclockinterrupts pr_blockclockinterrupts pr_unblockclockinterrupts pr_setconcurrency pr_processexit pr_abort module initialization initialization can be tricky in a threaded environment, especially initialization that must happen exactly once. pr_callonce ensures that such initialization code is called only once. this facility is recommended in situations where complicated global initialization is required. prcalloncetype prcalloncefn pr_callonce ...
CERT_FindCertByIssuerAndSN
...
Introduction to Network Security Services
eebl_pure32_3_shr.a libfreebl_hybrid_3_shr.a an application should not link against these libraries, because they are dynamically loaded by nss at run time. linking the application against one or the other of these libraries may produce an application program that can only run on one type of cpu (e.g. only on 64-bit cpus, not on 32-bit cpus) or that doesn't use the more efficient 64-bit code on 64-bit cpus, which defeats the purpose of having these shared libraries. on platforms for which these shared libraries exist, nss 3.2 will fail if these shared libs are not present. so, an application must include these files in its distribution of nss shared libraries. these shared libraries should be installed in the same directory where the other nss shared libraries (such as libnss3.so) a...
4.3.1 Release Notes
mozilla/security/jss/. the cvs tag for the jss 4.3.1 release is jss_4_3_1_rtm. source tarballs are available from ftp://ftp.mozilla.org/pub/mozilla.or...-4.3.1.tar.bz2 binary releases are no longer available on mozilla. jss is a jni library we provide the jss4.jar but expect you to build the jss's matching jni shared library. we provide the jss4.jar in case you do not want to obtain your own jce code signing certificate. jss is a jce provider and therefore the jss4.jar must be signed. ftp://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/jss_4_3_1_rtm. documentation documentation for jss 4.3.1 is available as follows: build instructions for jss 4.3.1 javadoc [online] [zipped] read the instructions on using jss. source may be viewed with a browser (via the mxr tool) at http://mxr.mozi...
Build instructions for JSS 4.3.x
recently reported that special build instructions are necessary to succeed building jss on osx. please see howto_successfully_compile_jss_and_nss_for_32_and_64_bits_on_osx_10.6_(10.6.7) for contributed instructions. build jss. cd mozilla/security/jss gmake sign the jss jar. if you're intention is to modify and build the jss source you need to apply for your own jce code-signing certificate if you made no changes and your goal is to build jss you can use the signed binary release of the jss4.jar from ftp.mozilla.org. with your built jss4 jni shared library. next, you should read the instructions on using jss. ...
Using JSS
Mozilla › Projects › NSS › JSS › Using JSS
gather components setup your runtime environment initialize jss in your application gather components you need the jss classes and the nspr, nss, and jss shared libraries. nspr and nss shared libraries jss uses the nspr and nss libraries for i/o and crypto. jss version 3.0 linked statically with nss, so it only required nspr. ...
NSS 3.15.1 release notes
_rsa_with_aes_256_cbc_sha256, tls_ecdhe_ecdsa_with_aes_128_cbc_sha256, tls_ecdhe_rsa_with_aes_128_cbc_sha256, tls_dhe_rsa_with_aes_128_cbc_sha256, tls_rsa_with_aes_128_cbc_sha256, tls_rsa_with_null_sha256 - new tls 1.2 only hmac-sha256 cipher suites. in sslerr.h ssl_error_unsupported_hash_algorithm, ssl_error_digest_failure, ssl_error_incorrect_signature_algorithm - new error codes for tls 1.2. in sslt.h ssl_hmac_sha256 - a new value in the sslmacalgorithm enum type. ssl_signature_algorithms_xtn - a new value in the sslextensiontype enum type. new pkcs #11 mechanisms none. notable changes in nss 3.15.1 bug 856060 - enforce name constraints on the common name in libpkix when no subjectaltname is present. bug 875156 - add const to th...
NSS 3.15.2 release notes
epted for ocsp or crls, consistent with their handling for general certificate signatures. bug 884178 - add pk11_cipherfinal macro bugs fixed in nss 3.15.2 bug 734007 - sizeof() used incorrectly bug 900971 - nssutil_readsecmoddb() leaks memory bug 681839 - allow ssl_handshakenegotiatedextension to be called before the handshake is finished. bug 848384 - deprecate the ssl cipher policy code, as it's no longer relevant. it is no longer necessary to call nss_setdomesticpolicy because all cipher suites are now allowed by default. a complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&target_milestone=3.15.2&product=nss&list_id=7982238 compatibility nss 3.15.2 shar...
NSS 3.16.1 release notes
ecure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_1_rtm/src/ new in nss 3.16.1 new functionality added the "ecc" flag for modutil to select the module used for elliptic curve cryptography (ecc) operations. new functions in pk11pub.h pk11_exportderprivatekeyinfo and pk11_exportprivkeyinfo - exports a private key in a der-encoded asn.1 privatekeyinfo type or a seckeyprivatekeyinfo structure. only rsa private keys are supported now. in secmod.h secmod_internaltopubmechflags - converts from nss-internal to public representation of mechanism flags. new types in sslt.h ssl_padding_xtn - the value of this enum constant changed from the experimental value 35655 to the iana-assigned value 21. . n...
NSS 3.16.2.3 release notes
which was originally made available in nss 3.17.1. new functionality tls_fallback_scsv is a signaling cipher suite value that indicates a handshake is the result of tls version fallback. new macros in ssl.h ssl_enable_fallback_scsv - an ssl socket option that enables tls_fallback_scsv. off by default. in sslerr.h ssl_error_inappropriate_fallback_alert - a new ssl error code. in sslproto.h tls_fallback_scsv - a a signaling cipher suite value that indicates a handshake is the result of tls version fallback. notable changes in nss 3.16.2.3 bug 1057161: check that an imported elliptic curve public key is valid. previously nss would only validate the peer's public key before performing ecdh key agreement. now ec public keys are validated at import t...
NSS 3.17.1 release notes
symbols can and will break in future nss releases. new functionality tls_fallback_scsv is a signaling cipher suite value that indicates a handshake is the result of tls version fallback. new macros in ssl.h ssl_enable_fallback_scsv - an ssl socket option that enables tls_fallback_scsv. off by default. in sslerr.h ssl_error_inappropriate_fallback_alert - a new ssl error code. in sslproto.h tls_fallback_scsv - a a signaling cipher suite value that indicates a handshake is the result of tls version fallback. notable changes in nss 3.17.1 signature algorithms now use sha-256 instead of sha-1 by default. added support for linux on little-endian powerpc64. bugs fixed in nss 3.17.1 this bugzilla query returns all the bugs fixed in nss 3.17.1: htt...
NSS 3.18.1 release notes
tributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_18_1_rtm/src/ new in nss 3.18.1 no new functionality is introduced in this release. this is a patch release to update the list of root ca certificates. notable changes in nss 3.18.1 the following ca certificate had the websites and code signing trust bits restored to their original state to allow more time to develop a better transition strategy for affected sites. the websites and code signing trust bits were turned off in nss 3.18. but when firefox 38 went into beta, there was a huge spike in the number of certificate verification errors attributed to this change. so, to give website administrators more time to update their we...
NSS 3.19.2.3 release notes
s/nss_3_19_2_3_rtm/src/ new in nss 3.19.2.3 new functionality no new functionality is introduced in this release. security fixes in nss 3.19.2.3 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user. acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.19.2.3 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.19.2.3 shared libraries wi...
NSS 3.19.2.4 release notes
oad: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_4_rtm/src/ new in nss 3.19.2.4 new functionality no new functionality has been introduced in this release. security fixes in nss 3.19.2.4 the following security fixes from nss 3.21 have been backported to nss 3.19.2.4: bug 1185033 / cve-2016-1979 - use-after-free during processing of der encoded keys in nss bug 1209546 / cve-2016-1978 - use-after-free in nss during ssl connections in low memory bug 1190248 / cve-2016-1938 - errors in mp_div and mp_exptmod cryptographic functions in nss compatibility nss 3.19.2.4 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.19.2.4 shared li...
NSS 3.19 release notes
api (cert_getimposednameconstraints) has been added that allows one to lookup imposed constraints. it is possible to override the directory (sqlite_lib_dir) in which the nss build system will look for the sqlite library. new functions in cert.h cert_getimposednameconstraints - check if any imposed constraints exist for the given certificate, and if found, return the constraints as encoded certificate extensions. notable changes in nss 3.19 the ssl 3 protocol has been disabled by default. nss now more strictly validates tls extensions and will fail a handshake that contains malformed extensions (bug 753136). in tls 1.2 handshakes, nss advertises support for the sha512 hash algorithm in order to be compatible with tls servers that use certificates with a sha512 signatur...
NSS 3.21.1 release notes
eleases/nss_3_21_1_rtm/src/ new in nss 3.21.1 new functionality no new functionality is introduced in this release. security fixes in nss 3.21.1 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user. acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.21.1 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.21.1 shared libraries withou...
NSS 3.21.2 release notes
er. nss 3.21.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_2_rtm/src/ new in nss 3.21.2 new functionality no new functionality is introduced in this release. security fixes in nss 3.21.2 bug 1293334 / cve-2016-9074 - fixed a timing side channel in the tls cbc code. compatibility nss 3.21.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared libraries will work with nss 3.21.2 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss public functions will remain compatible with future versions of t...
NSS 3.22.2 release notes
ases/nss_3_22_2_rtm/src/ new in nss 3.22.2 new functionality no new functionality is introduced in this release. security fixes in nss 3.22.2 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures. an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user. notable changes in nss 3.22.2 bug 1247990 - the root ca changes from nss 3.23 have been backported. acknowledgements the nss development team would like to thank security researcher francis gabriel for responsibly disclosing the issue in bug 1245528. compatibility nss 3.22.2 shared libraries are backward compatible with all older nss 3.x shared librarie...
NSS 3.26 release notes
s compilation of nss without the libpkix library notable changes in nss 3.26 the following ca certificate was added cn = isrg root x1 sha-256 fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 npn is disabled, and alpn is enabled by default the nss test suite now completes with the experimental tls 1.3 code enabled several test improvements and additions, including a nist known answer test bugs fixed in nss 3.26 this bugzilla query returns all the bugs fixed in nss 3.26: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.26 compatibility nss 3.26 shared libraries are backwards compatible with all older nss 3...
NSS 3.30 release notes
only an ecdsa certificate) is configured. rsa-pss signatures produced by key pairs with a modulus bit length that is not a multiple of 8 are now supported. the pk12util tool now supports importing and exporting data encrypted in the aes based schemes defined in pkcs#5 v2.1. bugs fixed in nss 3.30 this bugzilla query r...
NSS 3.32 release notes
tribution information the hg tag is nss_3_32_rtm. nss 3.32 requires netscape portable runtime (nspr) 4.16, or newer. nss 3.32 source distributions are available on ftp.mozilla.org, for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_32_rtm/src/ notable changes in nss 3.32 various minor improvements and correctness fixes. the code signing trust bit was turned off for all, included root certificates. the websites (tls/ssl) trust bit was turned off for the following root certificates. cn = addtrust class 1 ca root sha-256 fingerprint: 8c:72:09:27:9a:c0:4e:27:5e:16:d0:7f:d3:b7:75:e8:01:54:b5:96:80:46:e3:1f:52:dd:25:76:63:24:e9:a7 cn = swisscom root ca 2 sha-256 fingerprint: f0:9b:12:2c:7...
NSS 3.36 release notes
36 requires nspr 4.19 or newer. nss 3.36 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_rtm/src/ (make a link) new in nss 3.36 new functionality experimental apis for tls session cache handling. notable changes in nss 3.36 replaced existing vectorized chacha20 code with verified hacl* implementation. bugs fixed in nss 3.36 this bugzilla query returns all the bugs fixed in nss 3.36: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.36 compatibility nss 3.36 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older n...
NSS 3.37 release notes
re available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_37_rtm/src/ notable changes in nss 3.37 the tls 1.3 implementation was updated to draft 28. an issue where nss erroneously accepted hrr requests was resolved. this issue was found by oss fuzz. added hacl* poly1305 32-bit the code to support the npn protocol, which had already been disabled in a previous release, has been fully removed. nss allows servers now to register alpn handling callbacks to select a protocol. nss supports opening sql databases in read-only mode. nss now requires the sqlite apis of version 3.5.0 or newer. starting with nss version 3.31, an alternative implementation for rng seeding ...
NSS 3.38 release notes
ed, which can avoid ambiguous output in some scenarios. new functions in secitem.h secitem_makeitem - allocate and make an item with the requested contents new macros in ssl.h ssl_record_size_limit - used to control the tls record size limit extension notable changes in nss 3.38 fixed cve-2018-0495 in bug 1464971. various security fixes in the asn.1 code. nss automatically enables caching for sql database storage on linux, if it is located on a network filesystem that's known to benefit from caching. when repeatedly importing the same certificate into an sql database, the existing nickname will be kept. bugs fixed in nss 3.38 this bugzilla query returns all the bugs fixed in nss 3.38: https://bugzilla.mozilla.org/buglist.cgi?res...
NSS 3.46 release notes
yserv cmds bug 1550636 - upgrade sqlite in nss to a 2019 version bug 1572593 - reset advertised extensions in ssl_constructextensions bug 1415118 - nss build with ./build.sh --enable-libpkix fails bug 1539788 - add length checks for cryptographic primitives (cve-2019-17006) bug 1542077 - mp_set_ulong and mp_set_int should return errors on bad values bug 1572791 - read out-of-bounds in der_decodetimechoice_util from sslexp_delegatecredential bug 1560593 - cleanup.sh script does not set error exit code for tests that "failed with core" bug 1566601 - add wycheproof test vectors for aes-kw bug 1571316 - curve25519_32.c:280: undefined reference to `pr_assert' when building nss 3.45 on armhf-linux bug 1516593 - client to generate new random during renegotiation bug 1563258 - fips.sh fails...
NSS 3.47 release notes
bug 1542207 - limit policy check on signature algorithms to known algorithms bug 1560329 - drbg: add continuous self-test on entropy source bug 1579290 - asan builds should disable lsan while building bug 1385061 - build nspr tests with nss make; add gyp parameters to build/run nspr tests bug 1577359 - build atob and btoa for thunderbird bug 1579036 - confusing...
NSS 3.49.2 release notes
3.49.2 no new functionality is introduced in this release. bugs fixed in nss 3.49.2 bug 1606992 - cache the most recent pbkdf1 password hash, to speed up repeated sdr operations, important with the increased kdf iteration counts. nss 3.49.1 sped up pbkdf2 operations, though pbkdf1 operations are also relevant for older nss databases. bug 1608327 - fix compilation problems with neon-specific code in freebl bug 1608895 - fix a taskcluster issue with python 2 / python 3 this bugzilla query returns all the bugs fixed in nss 3.49: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.49 compatibility nss 3.49.2 shared libraries are backward compatible with all older nss 3.x shared libraries. a program lin...
NSS 3.50 release notes
ased kdf iteration counts. ...
NSS 3.53 release notes
itialize pbe params (asan fix) bug 1618404 - set cka_nss_server_distrust_after for symantec root certs bug 1621159 - set cka_nss_server_distrust_after for consorci aoc, grca, and sk id root certs bug 1629414 - ppc64: correct compilation error between vmx vs. vsx vector instructions bug 1639033 - fix various compile warnings in nss bug 1640041 - fix a null pointer in security/nss/lib/ssl/sslencode.c:67 bug 1640042 - fix a null pointer in security/nss/lib/ssl/sslsock.c:4460 bug 1638289 - avoid multiple definitions of sha{256,384,512}_* symbols when linking libfreeblpriv3.so in firefox on ppc64le bug 1636389 - relocate deprecated seed algorithm bug 1637083 - lib/ckfw: no such file or directory. stop. bug 1561331 - additional modular inverse test bug 1629553 - rework and cleanup gmake b...
Initialize NSS database - sample 2
nss sample code 2: initialize the nss database. the nss sample code below demonstrates how to initialize the nss database. /* * print a usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -d [-p ]" " [-f ]\n\n", progname); fprintf(stderr, "%-15s specify a db directory path\n\n", "-d "); fprintf(stderr, "%-15s specify a plaintext password\n\n", "-p "); fprintf(stderr, "%-15s specify a password file\n\n", "-f "); exit(-1); } /* * initslotpassword */ char * initslotpassword(pk11slotinfo *slot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; ...
nss tech note5
using nss to perform miscellaneous cryptographic operations nss technical note: 5 nss project info is at http://www.mozilla.org/projects/security/pki/nss/ you can browse the nss source online at http://lxr.mozilla.org/mozilla/source/security/nss/ and http://lxr.mozilla.org/security/ be sure to look for sample code first for things you need to do. note: this document contains code snippets that focus on essential aspects of the task and often do not illustrate all the cleanup that needs to be done. also, this document does not attempt to be an exhaustive survey of all possible ways to do a certain task; it merely tries to show a certain way. encrypt/decrypt include headers #include "nss.h" #include "pk11pub.h" make sure nss is initialized.the simplest init funct...
nss tech note6
and compare it with the value in libsoftokn3.chk/softokn3.chk. the following applies to nss 3.8 through 3.10 : on 32-bit solaris sparc (i.e., not x86, and not 64-bit sparc) and 32-bit hp-ux pa-risc (i.e., not itanium, and not 64-bit pa-risc), there are two more .chk files: libfreebl_pure32_3.chk and libfreebl_hybrid_3.chk. the following applies to nss 3.11 : the low-level freebl cryptographic code has been separated from softoken on all platforms. even on platforms for which there is only one implementation of freebl, there is now a separate freebl shared library. the freebl library implements a private interface internal to nss. on 32-bit windows and 32-bit os/2, this shared library is called freebl3.dll, and the corresponding .chk file is called freebl3.chk . on 32-bit solaris x86, 64-b...
NSS Tech Notes
tn2: using the pkcs #11 module logger. tn3: all about certificate extensions. ...
FC_InitPIN
" state (cks_rw_so_functions). the role of the pkcs #11 so is to initialize a token and to initialize the normal user's pin. in the nss cryptographic module, one uses the empty string password ("") to log in as the pkcs #11 so. the module only allows the pkcs #11 so to log in if the normal user's pin has not yet been set or has been reset. return value fc_initpin() returns the following return codes. ckr_ok: normal user's pin initialization succeeded. ckr_session_handle_invalid: the session handle is invalid. ckr_user_not_logged_in: the session is not in the "r/w so functions" state. ckr_pin_invalid: the pin has an invalid utf-8 character. ckr_pin_len_range: the pin is too short, too long, or too weak (doesn't have enough character types). ckr_device_error: normal user's pin is alrea...
FC_InitToken
oken (to assume the nss user role) because either the user's password hasn't been set yet or the user forgets the password and needs to blow away the password-encrypted private key database and start over. note: the so password should be the empty string, i.e., ulpinlen argument should be 0. fc_inittoken() ignores the plabel argument. return value fc_inittoken() returns the following return codes. ckr_ok: token initialization succeeded. ckr_slot_id_invalid: slot id is invalid. ckr_token_write_protected we don't have a reference to the key database (we failed to open the key database or we have released our reference). ckr_device_error: failed to reset the key database. application usage fc_inittoken() is used to reset the password for the key database when the user forgets the ...
FC_Initialize
security device' cryptoslotdescription='psm internal cryptographic services' dbslotdescription='psm private keys' fipsslotdescription='psm internal fips-140-1 cryptographic services' fipstokendescription='psm fips-140-1 user private key services' minps=0" see pkcs #11 module specs for complete documentation of the library parameters string. return value fc_initialize returns the following return codes. ckr_ok: library initialization succeeded. ckr_arguments_bad pinitargs is null. pinitargs->libraryparameters is null. only some of the lock functions were provided by the application. ckr_cant_lock: the ckf_os_locking_ok flag is not set in pinitargs->flags. the nss cryptographic module always uses os locking and doesn't know how to use the lock functions provided by the appl...
FC_Login
er that points to the user's pin ulpinlen [in] the length of the pin description fc_login() logs a user into a token. the security officer (cku_so) only logs in to initialize the normal user's pin. the so pin is the empty string. the nss cryptographic module doesn't allow the so to log in if the normal user's pin is already initialized. return value fc_login() returns the following return codes. ckr_ok: the user logged in successfully. ckr_device_error: the token is in the error state. ckr_host_memory: memory allocation failed. ckr_pin_incorrect: the pin is incorrect. ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255). the function should return ckr_pin_incorrect in this case. ckr_session_handle_invalid: the session handle is invalid. ckr_user_already_lo...
NSC_InitToken
base, removes the password, and then marks all the user certs in the certificate database as non-user certs. (user certs are the certificates that have their associated private keys in the key database.) note: the so password should be the empty string, i.e., ulpinlen argument should be 0. nsc_inittoken() ignores the plabel argument. return value nsc_inittoken() returns the following return codes. ckr_ok: token initialization succeeded. ckr_slot_id_invalid: slot id is invalid. ckr_token_write_protected slot id is 1. (the non-fips mode has two slots: 1 and 2. the key database is in slot 2. slot 1 doesn't have a key database.) we don't have a reference to the key database (we failed to open the key database or we have released our reference). ckr_device_error: failed to reset the k...
NSC_Login
er that points to the user's pin ulpinlen [in] the length of the pin description nsc_login() logs a user into a token. the security officer (cku_so) only logs in to initialize the normal user's pin. the so pin is the empty string. the nss cryptographic module doesn't allow the so to log in if the normal user's pin is already initialized. return value nsc_login() returns the following return codes. ckr_ok: the user logged in successfully. ckr_device_error: the token is in the error state. ckr_host_memory: memory allocation failed. ckr_pin_incorrect: the pin is incorrect. ckr_pin_len_range: the pin is too long (ulpinlen is greater than 255).the function should return ckr_pin_incorrect in this case. ckr_session_handle_invalid: the session handle is invalid. ckr_user_already_logged_i...
NSS tools : modutil
has information on the new database design and how to configure applications to use it. o https://wiki.mozilla.org/nss_shared_db_howto o https://wiki.mozilla.org/nss_shared_db additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [2]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape, red hat, sun, oracle, mozilla, and google. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. license licensed under the mozilla public license, v. 2.0. if a copy ...
NSS tools : vfyserv
name vfyserv — tbd synopsis vfyserv description the vfyserv tool verifies a certificate chain options additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape, red hat, and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license version 2. references visible links 1. http://www.mozilla.org/projects/security/pki/nss/ ...
sslintro.html
ent. at the http protocol level, nothing more is being said (that is, no http request or response is being sent), so the server first uses ssl_rehandshake to begin a new handshake and then call ssl_forcehandshake to drive the handshake to completion. functions used by callbacks an ssl application typically provides one or more callback functions that are called by the ssl or pkcs #11 library code under certain circumstances. numerous functions provided by the nss libraries are useful for such application callback functions, including these: cert_checkcertvalidtimes cert_getdefaultcertdb cert_destroycertificate cert_dupcertificate cert_findcertbyname cert_freenicknames cert_getcertnicknames cert_verifycertname cert_verifycertnow pk11_findcertfromnickname pk11_findkeyb...
NSS Tools pk12util-tasks
use nss functions in pcertdb for handling older database ...
NSS Tools signver-tasks
nss security tools: signver tasks newsgroup: mozilla.dev.tech.crypto task list remove private hash algortihms and replace with code in lib/hash, lib/crypto, and ...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
he new database design and how to configure applications to use it. o https://wiki.mozilla.org/nss_shared_db_howto o https://wiki.mozilla.org/nss_shared_db additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [2]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki authors the nss tools were written and maintained by developers with netscape, red hat, and sun. authors: elio maldonado <emaldona@redhat.com>, deon lackey <dlackey@redhat.com>. copyright (c) 2010, red hat, inc. licensed under the gnu public license vers...
Necko FAQ
currently you'd need to get the mozilla tree and at least build nspr, and xpcom. ...
Multithreading in Necko
n of few cases). most simple protocol handlers (eg. file, finger, datetime) do not worry about threading issues. the internal i/o interfaces default to proxying all callbacks to the main thread. this keeps simple protocol handlers simple :-) more complex protocol handlers (eg. http, ftp) operate partially on the background threads to improve performance. for example, the http protocol handler has code that runs on the socket transport thread to kick off pending requests well before the main thread would get around to doing so. socket transport thread (1) socket connections are processed on a single background thread. this thread is controlled by the nssockettransportservice. it sits in a loop, polling a list of sockets. when a socket can be read, the socket's listener is notified either syn...
Necko
x) and can be used for writing other networking clients. currently the library is built as part of the mozilla distribution. you can get the whole distribution as described in the build documentation. eventually we'd like to move to a binary distribution mechanism for the networking library so that you can build your application that uses this library without having to build mozilla. browse our code in its latest state at netwerk/ documents a necko code walkthrough necko architecture necko multithreading necko faq necko interfaces overview the necko http module proxies in necko pac files community view mozilla forums... mailing list newsgroup rss feed ...
Renaming With Pork
these notes are based on tools pork refactoring toolchain [required]. see installing pork. filterdiff from patchutils renaming a class 1. make two copies of the source(analysis and test). this isn't strictly required, but will save time. 2. the first copy will be an analysis copy. convince gcc to create annotated .ii files while compiling the analysis copy. ...
Rhino documentation
must have to run rhino; what rhino cannot do. downloads archive includes release notes for rhino releases optimization details on the various optimization levels. faq answers to frequently asked questions about rhino. rhino history history of the beast. writing scripts scripting java how to use rhino to script java classes. performance hints some tips on writing faster javascript code. javascript tools rhino shell interactive or batch execution of scripts. javascript debugger debugging scripts running in rhino. javascript compiler compiling scripts into java class files. running the rhino tests running the javascript test suite with rhino. embedding rhino embedding tutorial a short tutorial on how to embed rhino into your application. api javadoc reference (...
Download Rhino
2 2020-01-13 release notes rhino1.7.12.zip to download older rhino versions, see the rhino downloads archive. license rhino is open source. as of release 1.7r4 rhino is available under mpl 2.0. previous versions were released under mpl 1.1/gpl 2.0 license. see rhino license for further information. source in addition to getting the source from the zip files above, the source code for rhino can be found in github at https://github.com/mozilla/rhino. to get the source, use the command git clone https://github.com/mozilla/rhino.git rhino uses gradle as its build system. running the ./gradlew tasks command at the top directory of the rhino distribution will print the list of available build targets. ...
Rhino downloads archive
rhino1_6r5.zip rhino 1.6r4 2006-09-10 bug 343976 rhino1_6r4.zip rhino 1.6r3 2006-07-24 changes in 1.6r3 rhino1_6r3.zip rhino 1.6r2 2005-09-19 changes in 1.6r2 rhino1_6r2.zip rhino 1.6r1 2004-11-29 changes in 1.6r1 rhino1_6r1.zip rhino 1.5r5 2004-03-25 changes in 1.5r5 ...
Rhino FAQ
tance, to create an array of java.lang.string of length five, do var stringarray = java.lang.reflect.array.newinstance(java.lang.string, 5); then if you wish to assign the string "hi" to the first element, simply execute stringarray[0] = "hi". creating arrays of primitive types is slightly different: you must use the type field. for example, creating an array of seven ints can be done with the code var intarray = java.lang.reflect.array.newinstance(java.lang.integer.type, 7); when i try to execute a script i get the exception required security context missing. what's going on? you've likely missed placing the security.properties file in your class path at org.mozilla.javascript.resources. can i use rhino in a web browser? rhino is a library for java use, and not for general web browse...
Rhino license
rhino is available under open source licenses. mpl/gpl license the majority of the source code for rhino is available under a mpl 1.1/gpl 2.0 license. license for portions of the rhino debugger additionally, some files (currently the contents of toolsrc/org/mozilla/javascript/tools/debugger/treetable/) are available under the following license: * copyright 1997, 1998 sun microsystems, inc. all rights reserved. * * redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - redistributions in binary form must reproduce the above copyright * notice,...
Rhino optimization
ted optimization settings are: -1 interpretive mode is always used. the compilation time is minimized at the expense of runtime performance. no class files are generated, which may improve memory usage depending on your system. another benefit of the interpreted mode is that the interpreter performs tail-call elimination of recursive functions. also, you must use this optimization level if your code uses continuation objects. if the optimization package is not available, then optimization acts as if it is always -1. 0 no optimizations are performed. the bytecode compiler runs fastest in this mode, but the generated byte code is less efficient. 1-9 all optimizations are performed. simple data and type flow analysis is performed to determine which javascript variables can be allocated to ...
The JavaScript Runtime
interpretation beginning with rhino 1.4 release 2, an interpretive mode is supported. when scripts are compiled in interpretive mode, an internal representation of the compiled form is created and stored rather than generating a java class. execution proceeds by evaluating this compiled form using support routines in rhino. compilation to java bytecodes for improved performance, rhino may compile javascript scripts to java bytecodes. the generated bytecodes in turn depend upon runtime support routines. each javascript script or function is compiled to a separate class. compilation of javascript source to class files is supported. it is possible to specify the class files as well as the packages to generate into. types and values there are six fundamental types in javascript. thes...
Shumway
er "shumway" within flash content, clicking "report problems", and filling the form. performance and compatibility issues with flash content should be reported through github. from the main page for shumway at github, click on "issues" and browse the outstanding issues for similar bugs to contribute to. click on "new issue" to file a new entry if a duplicate is not found. please note that source code will be requested for the shumway developers to use as small test cases. there does not currently exist a private method to contribute source code. you could also directly commit bug fixes as pull requests. this would be very much appreciated. ...
Functions
there are four variations that affect how nameexpressions are evaluated. ...
Garbage collection
ental slice stop, so the mutator resumes. if the mutator stores b into a, so that a contains a pointer to b, and deletes all existing pointers to b, then: b is live, because a is black and contains a pointer to b. b will not be marked, because b is only reachable through a and we are all done with a, because a is black. thus, b is live but will be collected. the write barrier is a piece of code that runs just before a pointer store occurs and records just enough information to make sure that live objects don't get collected. the spidermonkey incremental write barrier spidermonkey uses a (relatively!) simple, common incremental write barrier called a snapshot-at-the-beginning allocate-black barrier. to understand how this barrier works, first assume that we're going to do an increment...
JIT Optimization Outcomes
emstub_dense icgetelemstub_densehole icgetelemstub_typedarray icgetelemstub_argselement icgetelemstub_argselementstrict icsetelemstub_dense icsetelemstub_typedarray icnamestub_readslot icnamestub_callgetter call inlining outcomes optimization outcomes of attempts to inline function calls. cantinlinegeneric cantinlineclassconstructor cantinlineexceededdepth cantinlineexceededtotalbytecodelength cantinlinebigcaller cantinlinebigcallee cantinlinebigcalleeinlinedbytecodelength cantinlinenothot cantinlinenotindispatch cantinlinenativebadtype cantinlinenotarget unable to inline function call. the callee (target) function, f in f(x), is not known at jit time. cantinlinenotinterpreted unable to inline function call. the callee function is not an interpreted function. for exampl...
INT_FITS_IN_JSVAL
nvert i to a jsval using js_newnumbervalue. warning: the type of the argument i must be jsint, but the c/c++ compiler does not enforce type safety here. if i is an unsigned or 64-bit value, int_fits_in_jsval can silently give the wrong answer. starting in spidermonkey 1.8.5, jsval can store a full 32-bit integer, so this check isn't needed any longer for 32-bit integers. example the following code snippet illustrates how a c variable, item, is conditionally tested in an if statement to see if it is a legal jsval integer value. if (int_fits_in_jsval(item)) { /* ... */ } else { js_reporterror(cx, "integer out of range: %d", item); } see also int_to_jsval changeset - 52750:05bd86e3559a ...
JS::CallArgs
ssert this, but it will do so eventually.) you don't need to use or change this if your method fails. description js::callargs is helper class encapsulating access to the callee, this value, arguments, and argument count for a function call. the intent of js::callargs is that they be used to encapsulate access to the un-abstracted unsigned argc, value *vp arguments to a function. new code should use callargs instead of js_callee etc. whenever possible. the eventual plan is to change jsnative to take const callargs& directly, for automatic assertion of correct use and to make calling functions more efficient. embedders should start internally switching away from using argc and vp directly, except to create a callargs. then, when an eventual release making that change occurs, porti...
JS::CloneFunctionObject
ontext from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. funobj js::handleobject the function to clone. scopechain js::autoobjectvector the new function's scope chain. description js::clonefunctionobject creates a new function object from funobj. the new object has the same code and argument list as funobj. if scopechain is supplied, it uses scopechain as its enclosing scope. if scopechain is omitted, it creates a new function object in cx's global. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. the new object's prototype is function.prototype; js_newobject : choosing a default prototype ...
JS::Compile
the script. filename is the name of the file (or url) containing the script. this information is included in error messages if an error occurs during compilation.. on success, js::compile stores an object representing the newly compiled script into script, and returns true. otherwise, it returns false and the value left in script is undefined. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compile js::evaluate js::compileoffthread js::compilefunction js_decompilescript bug 771705 bug 1143793 -- removed obj parameter ...
JS::CompileFunction
ction from a text string chars, bytes, or srcbuf. name is the name to assign to the newly created function. nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument. the number of argument names should match the number of arguments specified in nargs. chars, bytes, or srcbuf is a string containing the source code of the function. length is the length of the source code in characters. on success, js::compilefunction stores an function object representing the newly compiled function into fun and and returns true. otherwise, it returns false and the value left in fun is undefined. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compilefunction js::eval...
JS::CompileOffThread
dscript must be invoked on the main thread to get the result script or nullptr. if maybecx is not specified, the resources will be freed, but no script will be returned. the characters passed in to js::compileoffthread must remain live until the callback is invoked, and the resulting script will be rooted until the call to finishoffthreadscript. see also the jsapi user guide contains example code using compiled scripts. mxr id search for js::compileoffthread js::evaluate js::compile js::compilefunction js_decompilescript bug 897655 ...
JS::GetDeflatedUTF8StringLength
this article covers features introduced in spidermonkey 38 returns the length of the char buffer required to encode given string as utf8. syntax size_t getdeflatedutf8stringlength(jsflatstring* s); name type description s jsflatstring * the pointer to the string to calculate the length. description js::getdeflatedutf8stringlength returns the length of the char buffer required to encode s as utf8. the returned length does not include the null-terminator. see also js::deflatestringtoutf8buffer bug 1034627 ...
JS::PropertySpecNameIsSymbol
this article covers features introduced in spidermonkey 38 determine if the given jspropertyspec::name or jsfunctionspec::name value is actually a symbol code and not a string. syntax bool js::propertyspecnameissymbol(const char *name); name type description name const char * the pointer of the name, actually the uintptr_t type, and not a pointer to any string. description js::propertyspecnameissymbol determines if the given jspropertyspec::name or jsfunctionspec::name value is actually a symbol code and not a string, and returns true if so. see also mxr id search for js::propertyspecnameissymbol js::propertyspecnameequalsid js::propertyspecnametopermanentid jspropertyspec jsfunctionspec bug 1082672 ...
JS::SourceBufferHolder
the buffer and length values, it also provides a way to optionally pass ownership of the buffer to the js engine without copying. rules for use: the data array must be allocated with js_malloc or js_realloc if ownership is being granted to the sourcebufferholder. if ownership is not given to the sourcebufferholder, then the memory must be kept alive until the js compilation is complete. any code calling sourcebufferholder::take() must guarantee to keep the memory alive until js compilation completes. normally only the js engine should be calling take(). example size_t length = 512; char16_t* chars = static_cast<char16_t*>(js_malloc(sizeof(char16_t) * length)); js::sourcebufferholder srcbuf(chars, length, js::sourcebufferholder::giveownership); js::compile(cx, obj, options, srcbuf); ...
JSCheckAccessOp
of the property. description check whether obj[id] may be accessed per mode, returning js_false on error/exception, js_true on success with obj[id]'s stored value in *vp. as for jspropertyop, id is either a string or an int jsval. jscheckaccessop implementations generally work by using jsdbgapi functions such as js_frameiterator and js_stackframeprincipals to obtain the principals of the code attempting the checked operation, then examining those principals and comparing them with the system's security policy. the nature of principals and the security policy are entirely up to the application. if a class leaves the checkaccess field null, a runtime-wide object access callback is called instead; see js_setcheckobjectaccesscallback. jsclass hooks jsclass offers the following hook: ...
JSFastNative
is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8 jsfastnative is the type of fast native functions in the jsapi. apis such as js_initclass and js_definefunctions can create custom methods that are implemented as c/c++ functions of this type, instead of jsnative. the term "native" here refers to c/c++ code as opposed to javascript code. added in spidermonkey 1.8.1 jsfastnative has been renamed to jsnative. syntax typedef jsbool (*jsfastnative)(jscontext *cx, unsigned int argc, jsval *vp); name type description cx jscontext * the context in which the fast native is being called. provides request. in js_threadsafe builds, the javascript engine calls this callback...
JSFinalizeOp
eference to obj. warning: this hook is called during garbage collection. any jsapi call that would allocate memory from the gc heap will fail if called from a finalizer. for other ways to interact with garbage collection (e.g. implementing weak references), see js_setgccallback. jsclass hooks jsclass offers the following hook: the jsclass.finalize callback is a hook for destructor code. the garbage collector calls the finalize hook of each jsobject it collects. see also mxr id search for jsfinalizeop jsclass js_setgccallback ...
JSFreeOp
ethod description jsruntime *runtime() const returns a pointer to jsruntime passed to constructor. description various finalization api takes not jscontext * but rather either jsfreeop structure or its library-private counterpart freeop. these structures wrap parameters that are passed to the finalizers removing most of explicit dependencies on jscontext in the finalization code. see also mxr id search for jsfreeop js_freeop js_getdefaultfreeop jsfinalizecallback jsdestroycompartmentcallback bug 737365 ...
JSFunctionSpec
lt-in js call wrapped by this function. if the function does not wrap a native js call, set this value to null. nargs uint16_t the value used for function.length. this no longer guarantees anything about the vp array. flags uint16_t the bitwise or of any number of function flags. selfhostedname const char * the function's name in self-hosted javascript code. description jsfunctionspec defines the attributes for a single js function to associate with an object. an application typically has an array of jsfunctionspec to define all the functions for an object and calls js_definefunctions or js_initclass to create the functions and assign them to an object. jsfunctionspec can also be used to define an array element rather than a named property. ar...
JSID_EMPTY
internal jsid value which is used in type inference. syntax const jsid jsid_empty; const js::handleid jsid_emptyhandle; // added in spidermonkey 31 description jsid_empty is an internal jsid value which is used in type inference code. jsid_emptyhandle is the handle to the jsid with the value of jsid_empty. see also mxr id search for jsid_empty mxr id search for jsid_emptyhandle bug 912411 ...
JSMarkOp
obsolete since jsapi 29this 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. jsmarkop is the type of the jsclass.mark callback in spidermonkey 1.7 and earlier. in spidermonkey 1.8, jsmarkop will be deprecated. all new code using spidermonkey 1.8 or later should use a jstraceop instead to ensure that the tracing apis work properly. syntax typedef uint32 (* jsmarkop)(jscontext *cx, jsobject *obj, void *arg); name type description cx jscontext * the js context in which the mark phase of garbage collection is occurring. obj jsobject * the object to be marked. arg void * opaque data which the mark hook must pass through to js_mar...
JSNewResolveOp
he resolve callback. (the same flags are used in js_lookuppropertywithflags.) jsresolve_qualified obsolete since jsapi 20 the property access uses the . or [] operator: obj.id or obj[id], not id. jsresolve_assigning obsolete since jsapi 31 the property appears on the left-hand side of an assignment. jsresolve_detecting obsolete since jsapi 20 the property is being used in code like "if (o.p)...", or a similar idiom where the apparent purpose of the property access is to detect whether the property exists. (this flag has been replaced with the jsclass_emulates_undefined mechanism.) jsresolve_declaring obsolete since jsapi 15 the property is being declared in a var, const, or function declaration. jsresolve_classname obsolete since javascript 1.8.8 class...
JSObjectOps.newObjectMap
tmapop by calling the jsclass.getobjectops callback of a standard jsclass. create a new instance of (a concrete subclass of) jsobjectmap (see jsobj.h), with the nrefs and ops members initialized from the same-named parameters, and with the nslots and freeslot members initialized according to ops and clasp. return null on error, non-null on success. jsobjectmaps are reference-counted by generic code in the engine. usually, the nrefs parameter to jsobjectops.newobjectmap will be 1, to count the ref returned to the caller on success. after a successful construction, some number of js_holdobjectmap and js_dropobjectmap calls ensue. when nrefs reaches 0 due to a js_dropobjectmap call, jsobjectops.destroyobjectmap will be called to dispose of the map. ...
JSPRINCIPALS_HOLD
ext. principals jsprincipals * pointer to the jsprincipals object to hold or drop. this argument must not be null. description jsprincipals_hold and jsprincipals_drop are used to manage memory for jsprincipals objects. principals are used by the spidermonkey security system. jsprincipals objects are not jsobjects. they are reference counted, not garbage collected. application code that stores a pointer to a jsprincipals object must call jsprincipals_hold(cx, principals) before storing it and jsprincipals_drop(cx, principals) when done with it. jsprincipals_hold(cx, principals) increments the reference count of principals by 1. jsprincipals_drop(cx, principals) decrements the reference count of principals by 1. if the reference count drops to 0, indicating that no one is us...
JSScript
jsscript is a type in the jsapi. todo: documentation on this gigantic class. for now, i'll just say that this class represents a section of compiled javascript code, and the functions to create, run, and analyize it. see also uxp source jsscript.h uxp source jsscript.cpp ...
JSSecurityCallbacks.contentSecurityPolicyAllows
to the property. jscheckaccessop is the type of the callback. (it is also the type of the callback set by js_setcheckobjectaccesscallback.) syntax typedef jsbool (*jscspevalchecker)(jscontext *cx); name type description cx jscontext * the js context in which the property access attempt is occurring. description check whether runtime code generation is allowed for the current global. jssecuritycallbacks.contentsecuritypolicyallows is invoked once per global object upon the first attempt to evaluate js code from a string (either through eval or the function constructor). ...
JSTraceOp
g. jstraceop implementation can assume that no other threads mutates object state. it must not change state of the object or corresponding native structures. the only exception for this rule is the case when the embedding needs a tight integration with gc. in that case the embedding can check if the traversal is a part of the marking phase through calling js_isgcmarkingtracer and apply a special code like emptying caches or marking its native structures. jsclass hooks jsclass offers the following hook: the jsclass.trace callback is called to enumerate all traceable things reachable. see also mxr id search for jstraceop jsclass ...
JSVAL_IS_DOUBLE
rs, its use is discouraged since it could be removed at any time. try to avoid using it. determines if a given jsval is a number represented as a jsdouble. syntax jsval_is_double(v) description jsval_is_double(v) is true if v is a number represented in memory as a jsdouble. to check whether v is a number, regardless of implementation details, use jsval_is_number instead. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js double data type. if (jsval_is_double(myitem)) { . . . } see also bug 952650 ...
JSVAL_IS_INT
r represented in memory as an integer. syntax jsval_is_int(v) description jsval_is_int(v) is true if the jsval v is a number represented in memory as an integer. to test whether a value is a number, regardless of how it is represented in memory, use jsval_is_number instead. to convert between c integer types and jsval, use jsval_to_int, int_fits_in_jsval, and int_to_jsval. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer data type. if (jsval_is_int(myitem)) { . . . } see also bug 952650 ...
JSVAL_IS_NULL
determine if a given jsval is null. syntax jsval_is_null(v) description jsval_is_null(v) is true if v is jsval_null, which is the javascript null value. (note: jsval_is_object(jsval_null) is also true.) example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it contains a null value. if (jsval_is_null(myitem)) { ... } see also bug 952650 ...
JSVAL_IS_NUMBER
feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determine if a given jsval is a javascript number. syntax jsval_is_number(v) description jsval_is_number(v) is true if v is a javascript number. to convert a numeric jsval to a c floating-point number, use js_valuetonumber. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer or double value. if (jsval_is_number(myitem)) { ... } see also bug 952650 ...
JSVAL_IS_STRING
re is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determines if a given jsval is a string. syntax jsval_is_string(v) description jsval_is_string(v) is true if v is a string. to access the content of a string jsval, use jsval_to_string, js_getstringchars, and js_getstringlength. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a string. if (jsval_is_string(myitem)) { ... } see also bug 952650 ...
JSVAL_IS_VOID
obsolete since jsapi 32this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. determines if a given jsval is the javascript value undefined. syntax jsval_is_void(v) description jsval_is_void(v) is true if v is jsval_void, which represents the javascript value undefined. example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is void. if (jsval_is_void(myitem)) { ... } see also bug 952650 ...
JS_AddArgumentFormatter
see also bug 788359 ...
JS_AddExternalStringFinalizer
rnalstring() when creating the string. it is the callback's responsibility to free the memory. after this callback, the js engine will not use that memory anymore and will not keep a pointer to it. the callback may not keep a reference to this jsstring, as its memory is about to be freed. description add a finalizer for external strings created by js_newexternalstring using a type-code returned from this function, and that understands how to free or release the memory pointed at by js_getstringchars(str). returns a nonnegative type index if there is room for finalizer in the global gc finalizers table, else returns -1. in a js_threadsafe build, this function must be invoked on the primordial thread only, at startup—or else the entire program must single-thread itself while l...
JS_CheckAccess
cessed. mode jsaccessmode the type of access requested (read, write, etc.) vp jsval * out parameter. on success, *vp receives the property's stored value. attrsp unsigned int * out parameter. on success, *attrsp receives the property attributes. description js_checkaccess determines whether the property of obj given by id can be accessed by the code currently running in the context cx. the mode parameter specifies what kind of access to check for. it is one of the following values: value description jsacc_proto check for permission to read to obj's prototype. (this is redundant with passing the string id "__proto__" as id.) jsacc_parent check for permission to read obj's parent. (this is redundant with p...
JS_ClearContextThread
d at a time. each request runs from start to finish on a single thread. before transferring a jscontext from thread a to thread b, thread a must call js_clearcontextthread. this is the last thing thread a does with the context. before thread b uses the jscontext, it must call js_setcontextthread. this is the first thing thread b does with the context, before beginning a request. so the usual code for using a jscontext on a thread other than the one where it was created 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 u...
JS_ClearNewbornRoots
on. 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 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 ...
JS_CloneFunctionObject
ntext * 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. funobj jsobject * the function to clone. parent jsobject * the new function's parent. description js_clonefunctionobject creates a new function object from funobj. the new object has the same code and argument list as funobj, but uses parent as its enclosing scope. this can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. the new object's prototype is function.prototype; js_newobject: choosing a default prototype explains exactly how this is computed. js_clonefunctionobject takes care to choose a prototype that shares ...
JS_CompareStrings
. on success the function returns js_true. on error, it returns js_false and the value in result is unchanged. this function imposes a total order on all javascript strings, the same order imposed by the javascript string comparison operators (<, <=, >, >=), as described in ecma 262-3 § 11.8.5. as the standard says: the comparison of strings uses a simple lexicographic ordering on sequences of code point value values. there is no attempt to use the more complex, semantically oriented definitions of character or string equality and collating order defined in the unicode specification. therefore strings that are canonically equal according to the unicode standard could test as unequal. see also mxr id search for js_comparestrings js_convertvalue js_getstringchars js_getstringlength js_valuet...
JS_CompileScriptForPrincipals
he function. used to report filename or url in error messages. lineno unsigned int line number. used to report the offending line in the file or url if an error occurs. version jsversion javascript version for the script. description js_compilescriptforprincipals compiles a security-enabled script, src, for execution. js_compileucscriptforprincipals is the unicode version of the function. the script is associated with a js object. principals is a pointer to the jsprincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length indicates the length of the script, in characters. filename is the name of the file (or url) containing the script. this information is included...
JS_ContextIterator
the cycle. iterp must point to a variable of type jscontext *. if *iterp is null, js_contextiterator modifies it to point to the first jscontext in the list. ...
JS_DefineFunction
it is called. flags unsigned the logical or of zero or more property attributes. description js_definefunction exposes a c/c++ function to scripts by defining a new method on an existing javascript object. it creates the new function object as though by calling js_newfunction, then makes it a method of obj as though by calling js_defineproperty. js_defineucfunction is the unicode version of the function. name is the name of the property to create in obj. that is, it is the method name that scripts can use to call the new function. it also becomes the name property of the new function object and can be accessed using js_getfunctionid. call is a pointer to the c/c++ function that is to be exposed to javascript. nargs indicates the number of arguments the function expects to...
JS_DefineOwnProperty
perty. so the same restrictions apply as for that function (e.g. it is not possible to change a non-configurable property). descriptor is supposed to be a property descriptor, this means you need to create an object with properties such as value, writable, get or set. see object.defineproperty for a list of possible fields. a getter or setter defined with this functions will be observable from js code. see also js_setproperty js_getpropertydescriptorbyid object.defineproperty bug 1017323 ...
JS_DefinePropertyWithTinyId
lue for the new property. getter jspropertyop getproperty method for retrieving the current property value. setter jspropertyop setproperty method for specifying a new property value. attrs unsigned int property attributes. description js_definepropertywithtinyid defines an object property with a tiny id. js_defineucpropertywithtinyid is the unicode version of the function. except for the tinyid parameter, these functions behave exactly as js_defineproperty and js_defineucproperty. see those functions for more details. tinyid is a signed 8-bit integer that affects the id value passed to certain callbacks. any time the javascript engine would pass the name of the property as a string to the id parameter of a tiny-id-aware callback, it passes...
JS_DeleteProperty2
terminated. succeeded bool * out parameter. on success, *succeeded receives false if the property was not deleted because it is permanent and true otherwise. description js_deleteproperty2 removes a specified property, name, from an object, obj, and stores true or false in *succeeded. it behaves like the javascript expression delete obj[name]. js_deleteucproperty2 is the unicode version of the function. js_deletepropertybyid2 is the same but takes a js::handleid for the property name. first, a property lookup is performed. then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *...
JS_DumpHeap
t = 0x03, // shape details are exposed through js_traceshapecyclecollectorchildren. jstrace_shape = 0x04, // the kind associated with a nullptr. jstrace_null = 0x06, // a kind that indicates the real kind should be looked up in the arena. jstrace_outofline = 0x07, // the following kinds do not have an exposed c++ idiom. jstrace_base_shape = 0x0f, jstrace_jitcode = 0x1f, jstrace_lazy_script = 0x2f, jstrace_type_object = 0x3f, jstrace_last = jstrace_type_object }; description see bug 378261 for detail. when tracing a thing, the gc needs to know about the layout of the object it is looking at. there are a fixed number of different layouts that the gc knows about. the "trace kind" is a static map which tells which layout a gc thing has. alt...
JS_DumpNamedRoots
m or write to this pointer at all. it is passed to the dump function unchanged. it may be null. description each call to js_addnamedroot creates a record in a table of named roots maintained by the garbage collector. js_dumpnamedroots provides a way for the application to access the contents of that table. it calls the dump function once for each named root in the given runtime rt. in pseudocode: /* pseudocode explanation of what js_dumpnamedroots does */ void js_dumpnamedroots(jsruntime *rt, dumpfn dump, void *data) { for each (root in rt->namedroots) dump(root.name, root.address, data); } callback syntax dump is a pointer to a function provided by the application. when js_dumpnamedroots calls it, it passes three arguments: argument type description ...
JS_EvaluateScript
report filename or url in error messages. lineno unsigned int line number. used to report the offending line in the file or url if an error occurs. rval jsval * out parameter. on success, if rval is not null, *rval receives the result value. description js_evaluatescript compiles and executes a script in the specified scope, obj. js_evaluateucscript is the unicode version of the function. src is the string containing the text of the script. length indicates the size of the text version of the script in characters. filename is the name of the file (or url) containing the script. this information is used in messages if an error occurs during compilation. similarly, lineno is used to report the line number of the script or file where an error occurred durin...
JS_EvaluateScriptForPrincipals
in the file or url if an error occurs. rval jsval * out parameter. on success, *rval receives the value from the last-executed expression statement in the script. version jsversion javascript version for the script. description js_evaluatescriptforprincipals compiles and executes a script in the specified scope, obj. js_evaluateucscriptforprincipals is the unicode version of the function. principals is a pointer to the jsprincipals structure that contains the security information to associate with this script. src is the string containing the text of the script. length is the length of the script, in characters. filename is the name of the file (or url) containing the script. this information is used in messages if an error occurs during compilation. si...
JS_ExecuteScript
a cross-compartment script. if the script is cross-compartment, it is cloned into the current compartment before executing. if the script executes successfully, rval receives the value from the last executed expression statement processed in the script, and js_executescript returns true. otherwise it returns false, and the value left in rval is unspecified. the jsapi user guide contains example code using compiled scripts. to execute a script that has not been compiled, use js::evaluate instead. see also mxr id search for js_executescript mxr id search for js::cloneandexecutescript js::compile js::evaluate bug 993438 bug 1145294 -- removed obj from js::cloneandexecutescript. bug 1097987 -- removed obj from js_executescript ...
JS_FlushCaches
obsolete since jsapi 15this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8.5 flushes the code cache for the current thread. the operation might be delayed if the cache cannot be flushed currently because native code is currently executing. syntax void js_flushcaches(jscontext *cx); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description . see also bug 737364 ...
JS_FreezeObject
freeze an object. syntax bool js_freezeobject(jscontext *cx, js::handle<jsobject*> 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::handle&lt;jsobject*&gt; an object to freeze. description freezes an object. this means that other code cannot delete, add or change any properties on the object. see es5's object.freeze method. see also mxr id search for js_freezeobject javascript reference: the object.freeze method of object js_deepfreezeobject bug 492849 ...
JS_GC
for which to perform garbage collection. obsolete since jsapi 50 description js_gc performs garbage collection of js objects, strings and other internal data structures that are no longer reachable in the specified context or runtime. garbage collection frees memory so that it can be reused by the system. when your scripts create many objects, you may want to call js_gc directly in your code, particularly when a script terminates or when the application has idle time. to perform garbage collection only if needed, call js_maybegc instead. use js_setgccallback to add hooks that are called during garbage collection. see also mxr id search for js_gc js_maybegc bug 737364 -- changed to jsruntime bug 1283855 -- changed to jscontext ...
JS_GetFunctionObject
unction or similar functions. in other cases, the object returned by js_getfunctionobject is not necessarily safe to call and should not be exposed to script. in the javascript language, functions are objects. but in the jsapi there are two separate concepts: a jsobject is what is exposed to scripts and has properties and can be stored in variables; and the corresponding jsfunction contains the code of a function. for certain functions, the two have a strictly one-to-one relationship, and for those functions it is safe to call js_getfunctionobject to move from the jsfunction to the jsobject. however, for other functions, and particularly for javascript closures, many jsobjects may share the same jsfunction. in these cases, this function should not be called. calling the jsobject returned by...
JS_GetGCParameter
n seconds. description js_getgcparameter returns the current parameter of the garbage collection. if successful, js_getgcparameter returns the current parameter. js_setgcparameter ajusts the parameter of the garbage collection. ...
JS_GetGlobalObject
ture versions of spidermonkey. js_getglobalobject retrieves the global object for a specified jscontext *, cx. this returns null if cx has no global object. spidermonkey supports applications that have multiple global objects, such as the various window objects in a web browser. the object returned by js_getglobalobject is not necessarily the same thing as the global object seen by any javascript code that runs in cx! if a function is executing, the global object used by that function is determined when the function is created. furthermore, some jsapi functions, such as js_executescript, allow the caller to specify a global object in which the script executes. in either case, the global function used by the function or script may differ from the context's global object. the context's global ob...
JS_GetImplementationVersion
get the version number of the js engine. syntax const char * js_getimplementationversion(void); description js_getimplementationversion returns a hard-coded, english language string that specifies the version number of the js engine currently in use, and its release date. see also mxr id search for js_getimplementationversion js_getversion js_setversionforcompartment ...
JS_GetProperty
t name is null-terminated. vp js::mutablehandlevalue out parameter. on success, *vp receives the current value of the property, or undefined if no such property is found. description js_getproperty examines a specified js object obj and its prototype chain for a property with the specified name. it behaves like the javascript expression obj[name]. js_getucproperty is the unicode version of the function. js_getpropertybyid is the same but takes a js::handleid for the property name. in the simplest case, js_getproperty stores the value of the property in *vp and returns true. however, several different hooks can affect property gets. the full algorithm is described below. details first, a property lookup is performed. if the lookup proceeds without error, exactly one of...
JS_GetPropertyAttributes
s. foundp jsbool * out parameter. if no error occurs, *foundp receives js_true if the specified property is found and js_false if it is not found. if an error occurs, the value left in *foundp is unspecified. description js_getpropertyattributes retrieves the property attributes of the property with the given name on a given object, obj. js_getucpropertyattributes is the unicode version of the function. if an error occurs, the return value is js_false, and the values left in *attrsp and *foundp are unspecified. if obj does not have the specified property, or if it inherits it from some other object (on its prototype chain, for example), then *foundp is set to js_false. the value left in *attrsp is unspecified. the return value is js_true (to indicate that no error occu...
JS_GetStringCharAt
h to create the new string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. str jsstring * or jsflatstring * the string to get character. index size_t an integer between 0 and 1-less-than the length of the string. res char16_t * (js_getstringcharat only) out parameter. on successful, receives the character code. description js_getstringcharat and js_getflatstringcharat get the specified character from the string str. on successful, js_getstringcharat returns true and stores the character code into *res, otherwise returns false. js_getflatstringcharat always succeeds, and returns the character code. index should not be greater than or equal to the length of str. see also mxr id search for ...
JS_GetStringChars
n js_getstringchars obsolete since javascript 1.8.5 returns a pointer to the first element of an array of jschars. warnings: the array is not necessarily null-terminated. to get the length of the string, use js_getstringlength. the program must not modify the array. if it does, the behavior is undefined. the content of a js string is not guaranteed to be valid utf-16. it may contain surrogate code units that aren't properly paired. it may also contain zeroes. the array returned by this function remains valid as long as str is valid. (eventually, str becomes unreachable, the garbage collector collects it, and the array is freed by the system.) js_getstringcharsz is the same except that it always returns either a null-terminated string or null, indicating out-of-memory. see also bug 60944...
JS_GetStringLength
return the length, in 16-bit code units, of a javascript string. syntax size_t js_getstringlength(jsstring *str); name type description str jsstring * the string to examine. description js_getstringlength reports the length, in 16-bit code units, of the string str. this is the same as the length property of the string. this is the same as the length of the array returned by js_getstringchars, in char16_ts (not bytes). because some unicode characters are represented using two 16-bit code units, the result is not necessarily the same as the number of unicode characters in the string. see also mxr id search for js_getstringlength js_comparestrings js_convertvalue js_getemptystringvalue js_getstringbytes js_internstring js_newstringcopyn js_newstringcopyz j...
JS_HasProperty
oundp bool * non-null pointer to a variable of type bool. on success, js_hasproperty stores true in this variable if obj has a property with the given name, and false if not. description js_hasproperty searches an object, obj, and its prototype chain, for a property with the specified name. it behaves like the javascript expression name in obj. js_hasucproperty is the corresponding unicode api. js_haspropertybyid is the same but takes a js::handleid for the property name. if the property exists, this function sets *foundp to true and returns true. if the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred). if an error occurs during the search, the function returns false, and the value of *foundp is undefined. se...
JS_IsAssigning
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. determine whether script is executing assignment operation. syntax jsbool js_isassigning(jscontext *cx); name type description description js_isassigning returns true if a script is executing and its current bytecode is a set (assignment) operation, even if there are native (no script) stack frames between the script and the caller to js_isassigning. see also bug 458421 ...
JS_IsExceptionPending
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. 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_...
JS_LeaveLocalRootScopeWithResult
if there is an enclosing local root scope, then rval is transferred to it. otherwise, the value is stored in an internal per-jscontext slot. this slot is rooted, but the value will eventually be overwritten by some other operation, and it is very difficult to figure out exactly when this will happen—or more to the point, guarantee that it won't happen in the time it takes some specific chunk of code to run. in any case, all other newborn values protected by the local root scope, aside from rval, become subject to garbage collection. see also bug 519949 bug 803907 ...
JS_NewContext
stackchunksize size_t the size, in bytes, of each "stack chunk". this is a memory management tuning parameter which most users should not adjust. 8192 is a good default value. description js_newcontext creates a new jscontext in the runtime rt. on success, it returns a pointer to the new context. otherwise it returns null. for more details about contexts, see jscontext. for sample code that creates and initializes a jscontext, see jsapi user guide. the stackchunksize parameter does not control the javascript stack size. (the jsapi does not provide a way to adjust the stack depth limit.) passing a large number for stackchunksize is a mistake. in a debug build, large chunk sizes can degrade performance dramatically. the usual value of 8192 is recommended. the application must c...
JS_NewObjectForConstructor
. added in spidermonkey 17 vp jsval * pointer to a constructor. this must be an object that has a prototype property. args js::callargs &amp; call argument to get a constructor as callee. added in spidermonkey 38 description js_newobjectforconstructor creates a new object exactly as the given constructor would if invoked with new. this function does not run the code of the constructor function--it just creates the object. if the constructor argument is not an object jsval, this function will assert (in debug builds). if the constructor does not have a prototype property, this function will return null and set an exception on cx. the standard object creation api, js_newobject, takes explicit arguments for the class, prototype, and parent of the new object. wi...
JS_NewUCString
pointer to a character array, allocated with js_malloc, containing the characters for the js string to create. the javascript engine adopts the buffer. length size_t number of characters in the text string. description js_newstring creates and returns a new string, using the memory starting at buf and ending at buf + length as the character storage. js_newucstring is the unicode version of the function. the character array, buf, must be allocated on the heap using js_malloc. on success, the javascript engine adopts responsibility for memory management of this region. the application must not read, write, or free the buffer. this allows the javascript engine to avoid needless data copying. on success, js_newstring and js_newucstring return a pointer to the new string. on ...
JS_NewStringCopyN
* or const char16_t * pointer to the array of characters containing the text for the js string to create. n size_t number of characters to copy from s into the new string. description js_newstringcopyn allocates space for a javascript string and its underlying storage, and copies n characters from a c character array, s, into the new jsstring. js_newucstringcopyn is the unicode version of the function. the two functions differ only in the type of the character array s; both functions create ordinary javascript strings, and all javascript strings are made up of 16-bit characters. if the array s contains more than n characters, the new string contains a truncated version of the original string. the string may contain null characters ('\0'). they are copied into the new st...
JS_PSGS
ty. (or index, if jsprop_index is present in flags) getter jsnative pointer to the c/c++ implementation of the getter function. setter jsnative pointer to the c/c++ implementation of the setter function. flags uint16 the bitwise or of any number of property attributes. gettername const char * the function's name in self-hosted javascript code for getter function. settername const char * the function's name in self-hosted javascript code for setter function. description these macros encapsulate the definition of jsnative-backed jspropertyspecs, by defining the jsnativewrappers for them. see also mxr id search for js_psg mxr id search for js_psgs mxr id search for js_self_hosted_get mxr id search for js_sel...
JS_RemoveExternalStringFinalizer
s discouraged since it could be removed at any time. try to avoid using it. unregister a custom string memory manager. syntax int js_removeexternalstringfinalizer(jsstringfinalizeop finalizer); name type description finalizer jsstringfinalizeop the finalizer to remove. description remove finalizer from the global gc finalizers table, returning its type code if found, -1 if not found. as with js_addexternalstringfinalizer, there is a threading restriction if you compile the engine js_threadsafe: this function may be called for a given finalizer pointer on only one thread; different threads may call to remove distinct finalizers safely. you must ensure that all strings with finalizer's type have been collected before calling this function. otherwise...
JS_SaveFrameChain
saves and restores frame chains. syntax bool js_saveframechain(jscontext *cx); void js_restoreframechain(jscontext *cx); name type description cx jscontext * the context to query. description these two functions are used to set aside cx's call stack while that stack is inactive. after a call to js_saveframechain, it looks as if there is no code running on cx. before calling js_restoreframechain, cx's call stack must be balanced and all nested calls to js_saveframechain must have had matching js_restoreframechain calls. js_saveframechain deals with cx not having any code running on it. see also mxr id search for js_saveframechain mxr id search for js_restoreframechain ...
JS_SetBranchCallback
cb jsbranchcallback pointer to the callback function. callback syntax jsbool (*jsbranchcallback)(jscontext *cx, jsscript *script); name type description cx jscontext * pointer to a jscontext which the callback may use to call into jsapi functions. for example, the callback my call js_maybegc(cx). this is the context that is currently executing the code that triggered the callback. provides request. in js_threadsafe builds, the javascript engine calls this callback only from within an active request on cx. the callback does not need to call js_beginrequest()). script jsscript the script that is running. this is guaranteed to be non-null, unless the jsoption_native_branch_callback option has been enabled for the context cx using j...
JS_SetErrorReporter
jserrorreport structure. the error reporter callback must not reenter the jsapi. like all other spidermonkey callbacks, the error reporter callback must not throw a c++ exception. note that js_seterrorreporter has no facility to directly pass a user data pointer to the error reporting function. you can work around this by using the js_setruntimeprivate and js_getruntimeprivate methods. ...
JS_SetGCZeal
12 verify post write barriers between paints. 13 check internal hashtables on minor gc. 14 perform a shrinking collection every frequency allocations. with gc zeal enabled, gc-related crashes are much easier to reproduce (they happen more reliably) and debug (they happen sooner, closer to the source of the bug). the drawback is that gc zeal can cause javascript code to run extremely slowly. regularly running your test suite with gc zeal enabled at level 2 is a good practice. this function is available only in debug builds. to enable this function in an optimized build, define the macro js_gc_zeal building spidermonkey. (in a debug build of gecko, you can also set the current gc zeal level using the javascript.options.gczeal preference.) see also mxr id sea...
JS_SetGlobalObject
bal object is in the garbage collector's root set. this means that global objects are automatically protected from garbage collection, as are any values reachable from their properties. for full ecmascript standard compliance, obj should be of a jsclass that has the jsclass_global_flags flag. applications typically set a context's global object using js_initstandardclasses instead. see the sample code at jsapi user guide. see also js_getglobalobject bug 899245 ...
JS_SetInterruptCallback
syntax jsinterruptcallback js_setinterruptcallback(jsruntime *rt, jsinterruptcallback callback); jsinterruptcallback js_getinterruptcallback(jsruntime *rt); void js_requestinterruptcallback(jsruntime *rt); name type description rt jsruntime * the runtime. callback jsinterruptcallback the callback function to install. ...
JS_SetOperationCallback
obsolete since jsapi 30this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this article covers features introduced in spidermonkey 1.8.5 set a callback function that is automatically called periodically while javascript code runs. these methods/types are renamed to js_setinterruptcallback, js_getinterruptcallback, js_requestinterruptcallback and jsinterruptcallback in spidermonkey 30. syntax void js_setoperationcallback(jscontext *cx, jsoperationcallback callback); jsoperationcallback js_getoperationcallback(jscontext *cx); void js_triggeroperationcallback(jsruntime *rt); name type description cx jscontext * a context. rt jsruntime *...
JS_SetProperty
v js::handlevalue in/out parameter. *vp is the value to assign to the property. ordinarily this function leaves v unchanged, but it is possible for a jsclass.addproperty hook or a non-default setter to assign to v. description js_setproperty assigns the value v to the property name of the object obj. it behaves like the javascript expression obj[name] = v. js_setucproperty is the unicode version of the function. js_setpropertybyid is the same but takes a js::handleid for the property name. if obj is a proxy, the js_setproperty [[set]] internal method defined in es2015 (rev 29 9.5.9) is performed. if obj is a native object with custom setgeneric op, the op is called with (cx, obj, id, &v, false)). otherwise, [[set]] internal method defined in es2015 (rev 29 9.1.9) is performed.
JS_SetPropertyAttributes
t (in js_setucpropertyattributes only) the length of name, in characters. attrs unsigned int attribute values to set. foundp jsbool * out parameter. flag indicating whether or not the specified property was located. description js_setpropertyattributes sets the attributes for a specified property, name of an object obj. js_setucpropertyattributes is the unicode version of the function. attrs is an unsigned integer containing the attribute value to set. it is the bitwise or of zero or more of the following values: flag purpose jsprop_enumerate property is visible in for and in loops. jsprop_readonly property is read only. jsprop_permanent property cannot be deleted. jsprop_exported property ca...
JS_THREADSAFE
note: js_threadsafe is now permanently on. js_threadsafe was a compile-time option that enables support for running multiple threads of javascript code concurrently as long as no objects or strings are shared between them. we have recently made major changes to this feature. until recently, sharing objects among threads would mostly work, although scripts could easily make it crash. we have now completely removed that feature. each thread that uses the javascript engine must essentially operate in a totally separate region of memory. requests in a js_threadsafe build, the application must separate code that uses the jsapi from code that performs blocking i/o or time-consuming calculations. a request is a region of code that uses the jsapi. requests must be bracketed with calls to ...
JS_ValueToFunction
ascript value, v, to a function. js_valuetoconstructor is the exactly same function as js_valuetofunction. this conversion is dangerous and almost entirely useless, because the resulting jsfunction is not a real function object and therefore cannot be safely passed to any other jsapi function. that includes js_callfunction() and js_getfunctionobject(). a jsfunction represents only the compiled code and not the environment of the function. unless the function happens to be a native function, this means it isn't attached to any global or enclosing scope, and therefore must not be treated like a real function. instead, use jsval_is_object and js_objectisfunction() to check whether a value is already a function, or use js_convertvalue() to convert a value to jstype_function safely. if v is ...
JS_malloc
ntext used to allocate p. that is, it is safe to allocate memory in one context and free it in another, as long as both contexts are in the same runtime. implementation note: currently these four functions are implemented using the corresponding standard c functions. do not make assumptions based on this implementation detail. future releases may implement these functions differently. js_realloc code sample realloc is famously tricky to use correctly. here is an example of proper code: /* * `p` points to the memory area to resize. * we want to resize it to `newsize` bytes. */ void *p2 = js_realloc(cx, p, newsize); if (p2 == null) { if (p != null) js_free(cx, p); p = null; return null; } p = p2; see also mxr id search for js_malloc mxr id search for js_realloc mx...
jschar
pi 35this 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. jschar is the type of javascript "characters", the 16-bit elements that make up strings. jschar, a typedef for the standard c++ type char16_t, will be removed in jsapi 38. functions that use jschar will use char16_t directly. embedder code should use char16_t, too. (see bug 1063962.) as required by the ecmascript standard, ecma 262-3 §4.3.16", javascript strings are arbitrary sequences of 16-bit values. a string may contain unmatched surrogates, which are not valid utf-16. it may also contain zeroes ('\0'). to get the characters of a javascript string, use js_getstringchars. see also bug 1063962 ...
jsdouble
jsdouble is a c floating-point number type. it is defined to be a 64-bit, ieee 754 compliant type. see ecma 262-3 §8.5. arithmetic on jsdouble values in c should behave exactly like the floating-point arithmetic in javascript, except that c and javascript may treat not-a-number values differently. ...
SpiderMonkey 52
that will open a small window in the bottom left with a line like "artifact uploaded:mozjs-52.x.y.tar.bz2". spidermonkey 52 is the javascript engine that shipped in firefox 52. it continues to improve performance over previous spidermonkey releases. it also contains new language and api features described in detail below. ...
Running Parsemark
download the suite of parse tests from bug 548621 and decompress them. ...
TPS Tests
to use restmail, do not use your personal firefox account, as tps will delete and replace the data in it many times, not to mention the first run is very likely to fail, since it expects a clean start). note: be prepared not to use your computer for 15 or so minutes after starting a full run of tps, as it will open and close a fairly large number of firefox windows. ...
Zest runtimes
related links zest overview ...
Zest
security tools runtimes the runtime environments that support zest tools the tools that include support zest implementation the state of zest development videos simon demoed zest at appsec usa in november 2013, and the full video of my talk is available on youtube. the zest part of the talk starts at 23:47. more details https://github.com/mozilla/zest - the code on github http://groups.google.com/group/mozilla-zest - the group used for discussing zest ...
compare-locales
n your machine. the easiest way is to just run $ pip install -u compare-locales running it compare-locales gathers the directories to compare from a toml file, usually found in $app/locales/l10n.toml. the details of the configuration file are described in the l10n-config docs. you pass the path to the toml file and the parent dir of the localizations as first arguments, followed by the locale codes of the locales you want to compare. if you want to test the localization for de, run $ compare-locales browser/locales/l10n.toml ./l10n/ de to check mobile, replace the previous line with: $ compare-locales mobile/android/locales/l10n.toml ./l10n/ zh-tw to check mail, suite, calendar that lives on comm-central, you can either rely on the check-out of mozilla within comm-central repository...
Mozinfo
the various checks needed lead to a lot of copy+pasting, leaving the reader to wonder....is this specific check necessary for (e.g.) an operating system? because information is not consolidated, checks are not done consistently, nor is it defined what we are checking for. mozinfo proposes to solve this problem. mozinfo is a bridge interface, making the underlying (complex) plethora of os and architecture combinations conform to a subset of values of relevance to mozilla software. the current implementation exposes relevant key, values: os, version, bits, and processor. ...
Redis Tips
ems like that long before you go into production. optimistic locking your transactions are atomic once they start, but of course you can't guarantee that you'll get there first. the redis command watch lets you name keys you're worried about; it causes your next transaction to be immediately aborted if any of the watched keys has been modified by anyone else. for example, here's some node code: var redis = require("redis"), client = redis.createclient({ ... }); client.watch("foo", function( err ){ if(err) throw err; client.get("foo", function(err, result) { if(err) throw err; // process result // heavy and time consuming operation here client.multi() .set("foo", "some heavy computation") .exec(function(err, results) ...
Setting up an update server
uilding firefox for more information on building firefox locally. these changes will need to be made in order to use the locally built mar: put this line in the mozconfig file in root of the build directory (create it if it does not exist): ac_add_options --disable-verify-mar several files contain a line that must be uncommented. open them and find this line: #defines['disable_updater_authenticode_check'] = true. delete the # at the beginning of the line to uncomment it. these are the files that must be changed: toolkit/components/maintenanceservice/moz.build toolkit/mozapps/update/tests/moz.build firefox should otherwise be built normally. after building, you may want to copy the installation of firefox elsewhere. if you update the installation without moving it, attempts ...
The Places database
ference to moz_bookmarks) and an annotation name (reference to moz_anno_attributes) to the value of the annotation. favicon table moz_favicons: this contains a list of unique favicon uris and data. one or more pages in moz_places refer to each entry. when no pages reference a favicon, the icon entry will be deleted. if the mime type of the image is image/png, the data blob must be reencoded from base16 (the format in which it is stored) to base64 in order to display correctly. expiration expiration is handled in toolkit/components/places/nsplacesexpiration.js. this algorithm determines the lifetime of all objects in the places system. periodically at runtime, the following happens to expire pages: expire visits that are older than the history expiration threshold. dele...
Frecency algorithm
...
History Service Design
he old one, for both end users and extensions developers. view the service interface definition: nsinavhistoryservice.idl. objectives the primary objectives of the new history service implementation in places are: improve access to browsing history allow association of useful metadata with urls flexible query system for both end-users and add-ons developers clean architecture for ease of code reuse and maintainability the most known and visible feature of history are views. the user can query his visits based on a date range, meta contents or revisit behavior. this involves storing informations on all of the user's visits, including visit time, type of visit and meta data. old history system was instead only storing first and last visit date, and a generic visits counter, creating s...
Querying Places
string starting with "place:" using queriestoquerystring. the resulting string can be stored or bookmarked. when a "place:" uri is bookmarked, it will expand to the results of the query when it is opened by the user. the original objects can be deserialized from the string using querystringtoqueries. be careful, querystringtoqueries may not return any query objects if the string was empty. your code should handle this case. there will always be an options structure returned. if no options were specified, it will have the default values. if there were no query parameters specified but the input string was not empty (there were options) you may get one query object returned, containing the default query values. example of serializing and deserializing two queries and an options object: let q...
Retrieving part of the bookmarks tree
getchild(i); dump("child: " + node.title + "\n"); } // close a container after using it! rootnode.containeropen = false; if you encounter a node with a type of result_type_folder or another type of container, you can open these folders and descend into the hierarchy. you will want to read the section "using the results" in places:query system to understand the different result types. ...
Using the Places annotation service
for an overview of the places database design, see the places database. most methods in the service are duplicated with one method labeled as a 'page annotation' taking an nsiuri and the others labeled as an 'item annotation' and taking the id of an item in the places database. ...
Using the Places favicon service
nnotation uris are described in more detail in using the places annotation service. you should always use nsifaviconservice.getfaviconimageforpage() to get the favicon for a page. if the page has no favicon, or we have never heard of the page, this function will return a "chrome:" uri of the default favicon. this allows efficient caching, since the default favicon will probably be cached in its decoded form by the image library. if there is an error loading the favicon for an annotation uri, the default favicon data will be returned by the annotation service's protocol handler. however, since the uri will be different from the default favicon, the decoded image will not be cached by the image library. see also nsifaviconservice ...
Places
nvenient. it also includes new features including favicon storage and the ability to annotate pages with arbitrary information. it also introduces new user interfaces for managing all this information; see places on the mozilla wiki. places stores its data in an sqlite database using the mozstorage interfaces. documentation places migration guide migrating existing code to use the places api. manipulating bookmarks using places examples for how to work with bookmarks using the places api. using the places tagging service how to use the tagging service. using the places history service how to access history information using the places api. using the places favicon service how to manipulate favicons using the places api. ...
Preferences API
ing. you can also create a xul-based options window easily to allow user modify some preferences. ...
FUEL
the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/fuel/application;1"].getservice(components.interfaces.fueliapplication); ...
SMILE
the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/smile/application;1"].getservice(components.interfaces.smileiapplication); ...
STEEL
in seamonkey ("smile"). objects extiapplication objects extiapplication exticonsole extieventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage steeliapplication objects steeliapplication xpcom although the steel steeliapplication object is preloaded into xul scripts, it is not preloaded into javascript xpcom code. the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/steel/application;1"].getservice(components.interfaces.steeliapplication); other resources steel development plan. bug 408370 bug 1278067 ...
extIApplication
e for the restart to be canceled. boolean restart() return value boolean value indicating whether the restart was successful. getextensions(acallback) calls acallback with the list of installed extensions. void getextensions(extiextensionscallback acallback) return value none. xpcom although the application object is preloaded into xul scripts, it is not preloaded into javascript xpcom code. the object needs to be accessed like any other xpcom service: var application = components.classes["@mozilla.org/fuel/application;1"].getservice(components.interfaces.fueliapplication); see also fuel (firefox), steel (thunderbird) and smile (seamonkey) ...
extIPreferenceBranch
name of a preference adefaultvalue the default value of a preference. this will be passed back to you without any processing and can be something which would not be valid as a preference. for example, null/undefined/an object. return value the value of the preference or the given default value if preference does not exists. the use of a variant as the return value means that to javascript code the value will appear as a value of the same type as is used in the preferences file and no coercion will occur. a quoted string in the preference file will always appear as a string, even if the value of the string is "true" or "false". an integer preference appears as a javascript number, and a boolean appears as a javascript boolean. there are no other types supported by the preference subs...
Bundling multiple binary components
ork across platforms. this approach uses only one binary for each platform (win/mac/linux) but creates complexity in the binaries - loading the methods and creating the wrappers. the costs get higher if you have many methods that need to be loaded. stub loader this approach involves using a stub loader component. the stub component is an xpcom component itself and when registered by xpcom, the code would sniff the runtime version and operating system then the stub load the appropriate "real" xpcom component for the current configuration. it's pretty simple to do and the concept can be used to load third-party shared libraries (dll, so, dylib) used in xpcom components. in this case, we would use the stub to load the right binary component instead. some key points: the real components have...
Fun With XBL and XPConnect
r (like my auto complete session object). creating the event handler the last part is the easy part. i wanted a handler that would kick off the auto complete search. ...
Generic factory
actory->setconstructor(&mycomponent::create); } return factory; } this example assumes that the xpcom repository is available as an interface (which it soon will be). background (this is based on my original news posting <beard-2402991733140001@h-198-93-95-151.mcom.com>.) we seem to be creating a huge number of different factory implementations. it seems to me that we can cut down on code size (all those queryinterface, addref, release implementations) if we just use the following class for all of the simple factories: // idea: why not create a generic factory facility so we can avoid // duplication of so much nsifactory code? all we need is an allocator // function, the rest of the implementation is exactly the same. #include "nsifactory.h" class nsgenericfactory : public...
Inheriting from implementation classes
aces (i.e. the problem would not exist with java's interfaces). example problem you have interfaces a and b, b inherits from a, and you have implementation classes for both a and b, and you want the implementation class for b to inherit from the implementation class for a. the latter is the problem. the lacking virtual in the generated ib c++ abstract class doesn't make things easier. so, in code: idl: interface ia { void funca(); } interface ib : ia { void funcb(); } interface ic : ib { void funcc(); } c++ implementation: class a : public ia { ??? } class b : public a, public ib { ??? } class c : public b, public ic { ??? } example solution a.h, as usual: class a : public ia { ... ns_decl_isupports ns_decl_ia } a.cpp, as usual: ns_impl_isupports1(a, ia) ...
Receiving startup notifications
ically as was done in the past, you add lines to your chrome.manifest to let the application handle it for you. for example: category profile-after-change mycomponent @foobar/mycomponent;1 important: in the past, the contract id of the category entry started with "service," if the component was implemented as a service. this is no longer the case, so be sure to remove that when migrating existing code. additionally, the earliest startup time notification you can receive is now profile-after-change. your add-on will not receive xpcom-startup or app-startup notifications. the startup process during application startup, the application's manifest is used to get a list of the components it needs to register, and those components are loaded. this gets enough of xpcom and the application loaded and ...
Interfacing with the XPCOM cycle collector
unfortunately this macro defines the trace method and so you can't list your js object; hence, you need to also manually implmenet trace and unlink as above. handling js::value fields recall (or see here) that a js::value may reference a string or object and is subject to gc. hence, we need to tell th...
Components.ID
string of the format '{00000000-0000-0000-0000-000000000000}' giving the interface id of the interface description components.id creates interface ids for use in implementing methods like queryinterface, getinterfaces, and other methods that take interface ids as parameters. components.classes, components.classesbyid, components.interfaces provide pretty much all the nsids that most javascript code would ever need to deal with. the exception to this is the case where a component is written in javascript and needs to register itself with the component manager using its own nsid - an id that is not already registered and thus does not appear in components.classes. ...
Components.results
components.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpconnect/src/xpc.msg (also at table of errors), with the value of each corresponding to that constant's value. introduction components.results is an object whose properties are the names of well-known xpcom result codes, with each value being that of the corresponding result code. elements in this array can be used to test against unknown nsresult variables or they can be 'thrown' to indicate failure... if(something_unexpected_happened) throw components.results.ns_error_unexpected; the elements of the components.results object can be enumerated using a for-in loop. usage implementing nsisupports the standard nsisupports is usually implemented in jav...
Components.utils.cloneInto
way to take an object defined in a privileged scope and create a structured clone of it in a less-privileged scope. it returns a reference to the clone: var clonedobject = cloneinto(myobject, targetwindow); you can then assign the clone to an object in the target scope as an expando property, and scripts running in that scope can access it: targetwindow.foo = clonedobject; in this way privileged code, such as an add-on, can share an object with less-privileged code like a normal web page script. syntax components.utils.cloneinto(obj, targetscope[, options]); parameters obj : object the object to clone. targetscope : object the object to attach the object to. options : object this optional parameter is an object with the following optional properties: clonefunctions...
Components.utils.forceGC
llector in addition to the garbage collector in the javascript engine. this will make sure that xpcom components that build cycles with javascript objects also get collected which might be important, for example for testcases that depend on the garbage collector. requires universalxpconnect privileges. if you want to schedule garbage collection to occur in the future, at a time when no javascript code is running, you can use components.utils.scheduleprecisegc() instead. ...
Components.utils.getWeakReference
r which to obtain a weak reference. note: in gecko 11.0, this method was changed to throw an exception if obj is null. ...
Development
build instructions the build instructions are available here: building javaxpcom. bugs all javaxpcom bugs are tracked in bugzilla, using the "core" product and "java to xpcom bridge" component. ...
JavaXPCOM
ication. javaxpcom is very similar to xpconnect (javascript-xpcom bridge), and uses xpidl. note: javaxpcom was included in xulrunner up through version 1.9.2. it has been removed in xulrunner 2, and is not actively maintained. documentation javaxpcom development how to get and build the source, as well as how to view and report bugs. sample code there are several java test applications checked in to the tree that give examples on how to embed gecko or init xpcom from within java. embedding mozilla in a java application using javaxpcom xulrunner ships with the javaxpcom component, which allows java code to interact with xpcom objects. as you will see in this article, working with xpcom objects in java i...
PlXPCOM
the resources here provide information about this language binding and how to use it. ...
PyXPCOM
developed by activestate tool corporation, and came out of their komodo project. current releases are now integrated with the mozilla build system. other resources pythonext - extension that provides pyxpcom samples - demo applications using pyxpcom community python-xpcom bindings mailing list (activestate) #pyxpcom on irc.mozilla.org source code the pyxpcom code is available here: http://hg.mozilla.org/pyxpcom/ to build pyxpcom, see building pyxpcom. related topics xpcom pydom: replace javascript with python python-spidermonkey ...
Architecture basics
xpcom is like com, for windows. it lets you get pointers to components inside mozilla, and it lets you talk about their interfaces as well. xpconnect is what lets javascript talk with mozilla guts, the xpcom system. you can imagine it like a bridge between javascript code, and mozilla guts. xpcshell is a command line interface to mozilla javascript. it's an interactive interpreter -- it gives you a shell that talks straight to mozilla, via javascript's xpconnect bridge into it. ...
nsIProfile
...
HOWTO
on-ui javascript chrome files problem you want to write a javascript file, and run it in xpcshell. the file uses js modules. maybe it even uses javascript files from chrome:// urls. e.g., you use: components.utils.import("resource://app/modules/gloda/log4moz.js"); however, you get (for that particular line, which is the first import): uncaught exception: [exception... ...
XPCShell Reference
function dumps the xpconnect object. see the documentation on debugdump() for the nsixpconnect interface for more information. version(newversion) version() returns the javascript engine version number. if you pass a number to it, it will set the version number (and return the old version number). see the above documentation on the -v command-line argument for more information. quit(exitcode) quit() exits the shell. you can specify arguments that will get translated to an exit code. quit(5) will exit xpcshell with a result code of 5. original document information author: david bradley <dbradley@netscape.com> last updated date: 17 march 2003 copyright information: portions of this content are © 1998–2008 by individual mozilla.org contributors; content available under a cre...
xpcshell
unlike the ordinary js shell (js), xpcshell lets the scripts running in it access xpcom functionality. prerequisites you need your own build of mozilla to use xpcshell. running xpcshell ./run-mozilla.sh ./xpcshell xpcshell is almost always in the same directory as run-mozilla.sh. $ locate run-mozilla.sh /usr/lib/firefox-0.10.1/run-mozilla.sh /usr/lib/thunderbird-0.9/run-mozilla.sh /usr/local/mozilla/run-mozilla.sh /opt/mozilla/run-mozilla.sh /root/.trash/mozilla/run-mozilla.sh just pick one, cd over there, and run-mozilla.sh xpcshell, if it's present. ...
XPConnect
xpconnect is part of firefox and is actively used in xul applications. documentation architecture basics xpconnect, javascript, xpcom, xul... using components how to talk with xpcom components. xpconnect and xpidl faq a faq about using xpconnect and xpidl. this page needs to migrate to mdn. ...
nsDirectoryService
t can give you the path of the system's temporary directory, desktop directory, current working directory, and so on. class id f00152d0-b40b-11d3-8c9c-000064657374 contractid @mozilla.org/file/directory_service;1 supported interfaces nsiproperties nsidirectoryservice remarks this component is a singleton and should therefore be accessed via the xpcom service manager. example code #include "nsxpcom.h" #include "nscomptr.h" #include "nsdirectoryservicedefs.h" #include "nsiservicemanager.h" #include "nsiproperties.h" /** * get the location of the system's "temp" directory. */ nsresult gettempdir(nsifile **aresult) { nsresult rv; nscomptr<nsiservicemanager> svcmgr; rv = ns_getservicemanager(getter_addrefs(svcmgr)); if (ns_failed(rv)) return rv; nscomptr<...
nsLocalFile
« xpcom api reference summary a component implementing nsilocalfile. class id 2e23e220-60be-11d3-8c4a-000064657374 contractid @mozilla.org/file/local;1 supported interfaces nsilocalfile, nsifile remarks this component should be accessed via the xpcom component manager. example code function getfilesize(path) { var file = components.classes["@mozilla.org/file/local;1"]. createinstance(components.interfaces.nsilocalfile); file.initwithpath(path); return file.filesize; } see also components, nsicomponentmanager ...
nsScriptableInputStream
« xpcom api reference summary a component implementing nsiscriptableinputstream. class id 7225c040-a9bf-11d3-a197-0050041caf44 contractid @mozilla.org/scriptableinputstream;1 supported interfaces nsiscriptableinputstream, nsiinputstream remarks this component should be accessed via the xpcom component manager. ...
NS_GetComponentManager
the ns_getcomponentmanager function returns a reference to the xpcom component manager. #include "nsxpcom.h" #include "nsicomponentmanager.h" nsresult ns_getcomponentmanager( nsicomponentmanager** aresult ); parameters aresult [out] a reference to the xpcom component manager. return values the ns_getcomponentmanager function returns ns_ok if successful. otherwise, it returns an error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. see bug 99147 for details. see also nsicomponentmanager ...
NS_GetComponentRegistrar
onentregistrar function returns a reference to the xpcom component registrar. #include "nsxpcom.h" #include "nsicomponentregistrar.h" nsresult ns_getcomponentregistrar( nsicomponentmanager** aresult ); parameters aresult [out] a reference to the xpcom component registrar. return values the ns_getcomponentregistrar function returns ns_ok if successful. otherwise, it returns an error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. see bug 99147 for details. see also nsicomponentregistrar ...
NS_GetMemoryManager
« xpcom api reference summary the ns_getmemorymanager function returns a reference to the xpcom memory manager. #include "nsxpcom.h" #include "nsimemory.h" nsresult ns_getmemorymanager( nsimemory** aresult ); parameters aresult [out] a reference to the xpcom memory manager. return values the ns_getmemorymanager function returns ns_ok if successful. otherwise, it returns an error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. any code, intended to be used exclusively with mozilla 1.8 and above, may use ns_alloc, ns_realloc, and ns_free instead to access the xpcom memory manager's methods. history this function was finalized for mozilla 0.9.7. see bug 1...
NS_GetServiceManager
ce summary the ns_getservicemanager function returns a reference to the xpcom service manager. #include "nsxpcom.h" #include "nsiservicemanager.h" nsresult ns_getservicemanager( nsiservicemanager** aresult ); parameters aresult [out] a reference to the xpcom service manager. return values the ns_getservicemanager function returns ns_ok if successful. otherwise, it returns an error code. remarks the object returned is a singleton that is valid until ns_shutdownxpcom is called. the interface pointer should be release'd when it is no longer needed. history this function was finalized for mozilla 0.9.6. see bug 99147 for details. see also nsiservicemanager ...
NS_InitXPCOM2
d runtime libraries. pass null to specify that the current working directory should be used. aappfilelocationprovider [in] the object to be used by xpcom to locate application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. return values the ns_initxpcom2 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom2 (or ns_initxpcom3) before proceedin...
NS_InitXPCOM3
user profile, the component registry, etc.). this parameter may be nsnull. astaticmodules [in] an array of nsstaticmoduleinfo objects. passing null causes the default (built-in) static modules to be registered, if present. astaticmodulecount [in] the number of elements in astaticmodules. return values the ns_initxpcom3 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom3 (or ns_initxpcom2) before proceedin...
NS_ShutdownXPCOM
the ns_shutdownxpcom function terminates use of xpcom in the calling process. #include "nsxpcom.h" nsresult ns_shutdownxpcom( nsiservicemanager* asvcmanager ); parameters asvcmanager [in] the nsiservicemanager instance that was returned by ns_initxpcom2 (or ns_initxpcom3) or null. return values the ns_shutdownxpcom function returns ns_ok if successful. otherwise, it returns an error code. remarks you must call this method once you are finished using xpcom. calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers. once this function has been called, the nsicomponentmanager and nsiservicemanager will refuse to return object instances. history this function was finalized for mozilla 0.9.6. see bug bug 99147 for details. see also ns_initxp...
NS_OVERRIDE
if there is no base class method with the same signature, a compiler with static-checking enabled will fail to compile. ns_override is declared in nscore.h, beginning with gecko 2.0. it was introduced in bug 500870. ...
BeginReading
« xpcom api reference summary the beginreading function returns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. ...
EndReading
nst char_type pointer to the element just beyond the last element of the string's internal buffer. const char_type* endreading() const; remarks it is generally illegal to dereference the returned pointer, unless it is known that the string's internal buffer is null-terminated. the ns_cstringgetdata function can be used to determine if a nsacstring instance has null-terminated storage. example code see beginreading for an example. see also beginreading, ns_cstringgetdata, nsacstring ...
BeginReading
« xpcom api reference summary the beginreading function returns a const pointer to the first element of the string's internal buffer. const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated. the length of the array is determined by the result of the length method. ...
EndReading
onst char_type pointer to the element just beyond the last element of the string's internal buffer. const char_type* endreading() const; remarks it is generally illegal to dereference the returned pointer, unless it is known that the string's internal buffer is null-terminated. the ns_cstringgetdata function can be used to determine if a nsastring instance has null-terminated storage. example code see beginreading for an example. see also beginreading, ns_cstringgetdata, nsastring ...
nsAString
#include "nsstringapi.h" class nsastring { ... }; typedefs char_type [prunichar] storage unit for this class. self_type [nsastring] an alias for the type of this class. size_type [pruint32] type used to represent the number of double-byte units stored in the string. index_type [pruint32] type used to represent an offset into the string. ...
nsCOMPtr
#include "nscomptr.h" remarks consult using nscomptr for more info. to use this class, you must link your component or application against the xpcom glue library. ...
nsDependentCSubstring
class declaration nstdependentsubstring_chart a string class which wraps an external array of string characters. it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive. names: nsdependentsubstring for wide characters nsdependentcsubstring for narrow characters method overview constructors rebind beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const...
nsDependentSubstring
class declaration nstdependentsubstring_chart a string class which wraps an external array of string characters. it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive. names: nsdependentsubstring for wide characters nsdependentcsubstring for narrow characters method overview constructors rebind beginreading endreading beginwriting endwriting data length isempty isvoid isterminated charat operator[] first last countchar findchar equals equalsascii equalsliteral(const char equalsliteral(char lowercaseequalsascii lowercaseequalsliteral(const char lowercaseequalsliteral(char assign assignascii assignliteral(const...
get
« xpcom api reference summary the get function returns a const pointer to the string's null-terminated, internal buffer. const char_type* get() const; example code nsembedcstring str("hello world"); printf("%s\n", str.get()); ...
get
« xpcom api reference summary the get function returns a const pointer to the string's null-terminated, internal buffer. const char_type* get() const; example code void getbar(nsastring &result); void func() { nsembedstring str; getbar(str); const prunichar *data = str.get(); ... } ...
HeapMinimize
...
nsSupportsWeakReference
etailed description of weak references. #include "nsweakreference.h" class nssupportsweakreference { ... }; remarks in addition to inheriting from this class, you will need to ensure that your nsisupports::queryinterface implementation exposes nsisupportsweakreference as a supported interface. to use this class, you must link your component or application against the xpcom glue library. example code // supporting weak references to a hypothetical implementation // of the nsifoo interface... #include "nsweakreference.h" #include "nsifoo.h" class myfoo : public nsifoo, public nssupportsweakreference { public: ns_decl_isupports ns_decl_nsifoo ... }; ns_impl_isupports2(myfoo, nsifoo, nsisupportsweakreference) ... see also nsisupports::queryinterface , nsisupportsweakrefe...
jsdIStackFrame
g in this stack frame. read only. isconstructing boolean true if stack frame is constructing a new object. read only. isdebugger boolean true if stack frame represents a frame created as a result of a debugger evaluation. read only. isnative boolean true if stack frame represents a native frame. read only. obsolete since gecko 2.0 jsdcontext jsdcontext internal use only. read only. native code only! jsdstackframeinfo jsdstackframeinfo internal use only. read only. native code only! jsdthreadstate jsdthreadstate internal use only. read only. native code only! line unsigned long current line number (using the script's pc to line map.) read only. pc unsigned long current program counter in this stack frame. read only. scope jsdivalue top object in the scope chain. read only. s...
mozIJSSubScriptLoader
js/xpconnect/idl/mozijssubscriptloader.idlscriptable this interface can be used from privileged javascript to load and run javascript code from the given url at runtime. 66 introduced gecko 1.0 inherits from: nsisupports last changed in gecko 28 (firefox 28 / thunderbird 28 / seamonkey 2.25 / firefox os 1.3) implemented by: @mozilla.org/moz/jssubscript-loader;1. to get this service, use: var mozijssubscriptloader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); note: see components.utils.import for another way to import javascript code. method overview jsval loadsubscript(in string url, in object targetobj optional, in string charset optional); ...
mozIPersonalDictionary
he incorrect spelling of the word to add to the list of corrections. correction the correct spelling of the word. lang the language of the word. addword() add a word to the personal dictionary. void addword( in wstring word, in wstring lang ); parameters word the word to add to the dictionary. lang the 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 pr...
mozISpellCheckingEngine
and returns false if word is misspelled. getdictionarylist() gets the list of dictionaries. void getdictionarylist( [array, size_is(count)] out wstring dictionaries, out pruint32 count ); parameters dictionaries a list of dictionaries supported by this spell checker. the dictionary attribute can be set to one of these. each dictionary name is typically but not always a locale code. count the length of dictionaries. removedirectory() removes all the dictionaries in the specified directory from the spell checker. void removedirectory( nsifile dir ); parameters dir an nsifile object indicating the directory whose spell checkers are to be removed from the spell checker. suggest() gets a list of suggestions for a misspelled word. when this chan...
mozIStorageError
the mozistorageerror interface represents errors returned by the storage api, offering attributes to obtain the error code as well as a human-readable error message corresponding to the error that occurred. storage/public/mozistorageerror.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports attributes attribute type description message autf8string a human readable error string with details; this may be null if no details are available. read only. result long one of the error code values listed under constants on this page. constants constant value des...
nsIAboutModule
ppropriate flags for this about uri. newchannel() constructs a new channel for the about protocol module. nsichannel newchannel( in nsiuri auri ); parameters auri the uri of the new channel. return value a fully constructed channel that will load the about uri. see also on this page is seen how to make a custom about page. the section "firefox 4 (second approach)" provides copy paste code for working example. click here to view article. ...
nsIAccessibleEditableText
astring text, in long position); void pastetext(in long position); void setattributes(in long startpos, in long endpos, in nsisupports attributes); unimplemented void settextcontents(in astring text); attributes attribute type description associatededitor nsieditor returns an editor associated with the accessible. read only. native code only! methods copytext() copies the text range into the clipboard. void copytext( in long startpos, in long endpos ); parameters startpos start offset of the text to be copied into the clipboard. endpos end offset of the text to be copied into the clipboard. exceptions thrown ns_error_failure indicates the text cannot be copied into the clipboard. cuttext() deletes...
nsIAccessibleEvent
t_change 0x0006 an object had a significant layout change which could affect the type of accessible object -- this is a layout occurrence and is thus asynchronous. ...
nsIAccessibleWin32Object
...
nsIAlertsService
sed for ipc security checks, and to determine whether the alert is actionable. inprivatebrowsing optional controls the image loading behavior. if true, the image url will be loaded in private browsing mode. exceptions thrown ns_error_not_available unable to display the notification; this may happen, for example, on mac os x if growl is not installed. example simple usage the following code was used to display the above notification. var alertsservice = components.classes["@mozilla.org/alerts-service;1"]. getservice(components.interfaces.nsialertsservice); try { alertsservice.showalertnotification("chrome://mozapps/skin/downloads/downloadicon.png", "alert title", "alert text goes here.", ...
nsIAnnotationService
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: "@mozilla.org/browser/annotation-service;1". ...
nsIApplicationCache
gettypes( in acstring key ); parameters key the key for the cache entry whose types you wish to retrieve. return value a bit field indicating the entry's types. see constants for a list of types. initashandle() init this application cache instance to just hold the group id and the client id to work just as a handle to the real cache. used on content process to simplify the application cache code. void initashandle( in acstring groupid, in acstring clientid ); parameters groupid missing description clientid missing description markentry() adds item types to a given entry. void markentry( in acstring key, in unsigned long typebits ); parameters key the key for the cache entry to which to add types. typebits a bit field indicating the types to add to the entry. see constants fo...
nsIAutoCompleteListener
inherits from: nsisupports last changed in gecko 1.7 method overview void onautocomplete(in nsiautocompleteresults result, in autocompletestatus status); void onstatus(in wstring statustext); attributes attribute type description param nsisupports private parameter used by the autocomplete widget. ...
nsIBidiKeyboard
api to check the direction of keyboard layout, which has a problem with hebrew language. the problem is fixed on gtk+ version 2.10.1 and 2.12. in the gecko 1.9 branch, we are going to implement all the interface, with xkb functions for xlib and gtk2 backends. on the gtk2 backend, we will have gtk+ version checking, to use gtk+ implementations, if the problem doesn't exist. some other part of the code is going to be on gtk+ later, and we will use gtk+ api instead. both gtk+ and gecko versions, check keysym's on keyboard layout to detect the direction of the layout. for gtk+ (>=2.10.1, >=2.12.0) and all gecko versions, we check only the first shift-level of the layout, to fix the problem with hebrew layouts. more info: bug 348724, bug 348724, and gnome bug: 116626 mac only islangrtl is supporte...
nsIBinaryOutputStream
float afloat ); parameters afloat the floating point value to write to the stream. writestringz() writes an 8-bit pascal style string to the stream. the output data consists of a 32-bit length field, followed by that many 8-bit characters. void writestringz( in string astring ); parameters astring the string to write to the stream. writeutf8z() writes an 8-bit pascal style string (utf8-encoded) to the stream. the output data consists of a 32-bit length field, followed by that many 8-bit characters. void writeutf8z( in wstring astring ); parameters astring the string to write to the stream. writewstringz() writes a 16-bit pascal style string to the stream. the output data consists of a 32-bit length field, followed by that many prunichars. void writewstringz( in wstring astring ...
nsIBrowserHistory
e.hashistoryentries attribute is better for this. methods addpagewithdetails() obsolete since gecko 15.0 (firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) note: this method was removed in gecko 15.0. you should use moziasynchistory.updateplaces() instead. this method adds a page to the history with specific time stamp information. it is called by history importing code and is used in the history migration tool. void addpagewithdetails( in nsiuri auri, in wstring atitle, in long long alastvisited ); parameters auri the page that will be added to the history. atitle the title of the page. alastvisited when the page was last visited, in microseconds since the unix epoch. markpageasfollowedlink() obsolete since gecko 22.0 (firefo...
nsICancelable
in progress. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void cancel(in nsresult areason); methods cancel() call this method to request that this object abort whatever operation it may be performing. void cancel( in nsresult areason ); parameters areason a failure code indicating why the operation is being canceled. it is an error to pass a success code. ...
nsIChannel
null. attempts to set it to null must throw. note: this is distinctly different from the http referer (referring uri), which is typically the page that contained the original uri (accessible from nsihttpchannel.) owner nsisupports the owner, corresponding to the entity that is responsible for this channel. used by the security manager to grant or deny privileges to mobile code loaded from this channel. note: this is a strong reference to the owner, so if the owner is also holding a strong reference to the channel, care must be taken to explicitly drop its reference to the channel. securityinfo nsisupports transport-level security information (if any, else null) corresponding to the channel, normally presented through the interfaces nsitransportsecuri...
nsIClassInfo
cessed by any thread. main_thread_only 1 << 2 the class may only be accessed by the main application thread. dom_object 1 << 3 the class is a dom object. plugin_object 1 << 4 the class is a plugin object. content_node 1 << 6 specifies that this class implements nsicontent. note: this flag is private and is for use by the mozilla codebase only. reserved 1 << 31 the high order bit is reserved for consumers of these flags. no implementor of this interface should ever return flags with this bit set. eager_classinfo 1 << 5 this flag is designed for use with nsgenericfactory and can be set in nsmodulecomponentinfo::mflags. it has no meaning when returned from the flags attribute of a nsiclassinfo imple...
nsICommandLineRunner
n unsigned long state); void run(); void setwindowcontext(in nsidomwindow awindow); attributes attribute type description helptext autf8string process and combine the help text provided by each command-line handler. read only. methods init() called with the argc/argv combination passed to main. it assumes a native character set. on windows the character set is utf-8, not the native codepage. void init( in long argc, in nscharptrarray argv, in nsifile workingdir, in unsigned long state ); parameters argc the number of arguments being passed. argv an array storing pointers to the arguments workingdir directory where the command will run. this is used to resolve file and uri paths. state the type of command line being processed. this is an nsicommandline state flag. run(...
nsIContentPrefObserver
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void oncontentprefremoved(in astring agroup, in astring aname); void oncontentprefset(in astring agroup, in astring aname, in nsivariant avalue); methods oncontentprefremoved() called when a content preference is removed. ...
nsIContentSecurityPolicy
calls to this may trigger violation reports when queried, so this value should not be cached. read only. allowsinlinescript boolean whether this policy allows in-page script. calls to this may trigger violation reports when queried, so this value should not be cached. read only. isinitialized boolean set to true when the content security policy has been read in and parsed and...
nsIConverterInputStream
1.0 66 introduced gecko 1.8 inherits from: nsiunicharinputstream last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/converter-input-stream;1. ...
nsICookieManager2
the nsicookiemanager2 interface contains additional methods that expand upon the nsicookiemanager interface. netwerk/cookie/nsicookiemanager2.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsicookiemanager this interface is included in the services.jsm javascript code module. to create an object implementing this interface: components.utils.import("resource://gre/modules/services.jsm"); var cookieservice = services.cookies; method overview void add(in autf8string ahost, in autf8string apath, in acstring aname, in acstring avalue, in boolean aissecure, in boolean aishttponly, in boolean aissession, in print64 aexpiry); boolean cookieexists(in nsicookie2 acooki...
nsICryptoHMAC
secure hash algorithm 384 sha512 6 secure hash algorithm 512 methods finish() completes this hmac object and produces the actual hmac diegest data. note: this method may be called any time after init() is called. this call resets the object to its pre-init state. acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value a hash of the data that was read by this object. this can be either binary data or base 64 encoded. exceptions thrown ns_error_not_initialized if init() has not been called. init() initialize the hashing object. this method may be called multiple times with different algorithm types. warning: this approach is not...
nsIDNSRecord
netwerk/dns/nsidnsrecord.idlscriptable this interface represents the result of a dns lookup. since a dns query may return more than one resolved ip address, the record acts like an enumerator, allowing the caller to easily step through the list of ip addresses. inherits from: nsisupports last changed in gecko 1.7 method overview prnetaddr getnextaddr(in pruint16 aport); native code only! acstring getnextaddrasstring(); boolean hasmore(); void rewind(); attributes attribute type description canonicalname acstring for example, www.mozilla.org --> rheet.mozilla.org. read only. methods native code only!getnextaddr this function copies the value of the next ip address into the given prnetaddr struct and increments the internal address iterator. prnetaddr getnexta...
nsIDNSRequest
netwerk/dns/nsidnsrequest.idlscriptable please add a summary to this article. inherits from: nsisupports last changed in gecko 1.7 method overview void cancel(); methods cancel() called to cancel a pending asynchronous dns request. the listener will passed to asyncresolve will be notified immediately with a status code of ns_error_abort. void cancel(); parameters none. ...
nsIDNSService
ts.classes["@mozilla.org/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); let thread = components.classes["@mozilla.org/thread-manager;1"] .getservice(components.interfaces.nsithreadmanager).currentthread; let host = "www.mozilla.org"; let listener = { onlookupcomplete: function(request, record, status) { if (!components.issuccesscode(status)) { // handle error here return; } let address = record.getnextaddrasstring(); console.log(host + " = " + address); } }; dnsservice.asyncresolve(host, 0, listener, thread); ...
nsIDOMFileException
ons that can be raised by calls to the methods in the nsidomfile interface. note: gecko's implementation of this interface presently differs from the working draft of the file api specification. content/base/public/nsidomfileexception.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) attributes attribute type description code unsigned short the error code describing the error condition that took place; see the constants list for details. constants constant value description not_found_err 0 the specified file wasn't found. not_readable_err 1 the specified file wasn't readable. see also nsidomfile nsidomfilelist nsidomfilereader ...
nsIDOMGeoPositionAddress
gecko 14.0 inherits from: nsisupports last changed in gecko 11 (firefox 11 / thunderbird 11 / seamonkey 2.8) this object is obtained from an nsidomgeopositionaddress object via its address attribute. note: this needs to be moved into the dom reference. attributes attribute type description city domstring the city. read only. country domstring the country. read only. countrycode obsolete since gecko 11 domstring removed in firefox 11, since it isn't defined in the specification; use country instead. county domstring the county. read only. postalcode domstring the postal or zip code. read only. premises domstring the premises. read only. region domstring the region. read only. street domstring the street of the address. read only. streetnumber domstring the st...
nsIDOMGeoPositionError
the nsidomgeopositionerror interface represents an error that occurred while performing geolocation operations. dom/interfaces/geolocation/nsidomgeopositionerror.idlscriptable please add a summary to this article. last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports attributes attribute type description code short numerical error code; see error constants for a complete list. read only. message domstring human readable error message. read only. gecko 1.9.2 note the message attribute was removed in gecko 1.9.2 (firefox 3.6). error constants constant value description permission_denied 1 the user denied permission to retrieve location data. po...
nsIDOMGlobalPropertyInitializer
property in response to the content-document-global-created notification. method overview jsval init(in nsidomwindow window); methods init() jsval init( in nsidomwindow window ); parameters window the window to which the global property is being attached. return value the initialized global property. ensure that you never return any internal xpcom objects to untrusted code. it is also recommended to use __exposedprops__ to control which members are exposed. ...
nsIDOMOrientationEvent
dom/interfaces/events/nsidomorientationevent.idlscriptable please add a summary to this article. ...
nsIDOMSerializer
m. if this string is empty and root is a document, the document's character set will be used. serializetostring() the subtree rooted by the specified element is serialized to a string. astring serializetostring( in nsidomnode root ); parameters root the root of the subtree to be serialized. this could be any node, including a document. return value the serialized subtree in the form of a unicode string. ...
nsIDOMXPathException
dom/interfaces/xpath/nsidomxpathexception.idlscriptable describes an exception resulting from xpath operations. inherits from: nsisupports last changed in gecko 1.7 attributes attribute type description code unsigned short the error code; see error codes for details. constants error codes constant value description invalid_expression_err 51 an invalid xpath expression was used. type_err 52 an attempt was made to reference an unavailable type. see also introduction to using xpath in javascript document object model (dom) level 3 xpath specification nsidomxpathevaluator document.evaluate nsidomxpathresult ...
nsIDebug2
xpcom/base/nsidebug2.idlscriptable adds access to additional information in debug builds of mozilla code by expanding upon the features in nsidebug 1.0 66 introduced gecko 1.9.2 inherits from: nsidebug last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) attributes attribute type description assertioncount long the number of assertions since process start. this is normally zero in release builds, but does include calls to nsidebug.assertion(). read only. isdebugbuild boolean whether xpcom was compiled with debug defined. this often correlates to whether other code (for example, firefox, xulrunner) was compiled with debug defined. read only. see also nsidebug ...
nsIDirIndex
scription contenttype string the content type; may be null if it is unknown. unspecified for directories. description wstring a description for the filename, which should be displayed by a viewer. lastmodified prtime last-modified time in seconds-since-epoch. if the last modified time is unknown, this value is -1. location string the fully qualified filename, expressed as a uri. this is encoded with the encoding specified in the nsidirindexparser, and is also escaped. size long long file size; if the size is unknown, this value is -1. type unsigned long the type of the entry; one of the type_* constants. constants constant value description type_unknown 0 the type is unknown. type_directory 1 the directory entry represents a directory. type_file 2 the directory entry re...
nsIDirectoryService
init(); void registerprovider(in nsidirectoryserviceprovider prov); void unregisterprovider(in nsidirectoryserviceprovider prov); init() initializes the nsidirectoryservice instance. this method must be called before an nsidirectoryservice instance can be used. in the case of the xpcom directory service, this method is called as part of xpcom initialization. must not be called by external code; called internally by xpcom initialization. void init(); parameters none. registerprovider() register a provider with the service. the directory service will keep a strong reference to the nsidirectoryserviceprovider instances registered via registerprovider. the providers will be released when the service is destroyed at xpcom shutdown. call unregisterprovider() to force the directory service...
nsIDirectoryServiceProvider
getfile( in string prop, out prbool persistent ); parameters prop the symbolic name of the file. persistent true if the returned file will be cached by directory service. subsequent requests for this prop will bypass the provider and use the cache. false if the provider will be asked for this prop each time it is requested. return value the nsifile represented by the property. example this code creates a global, read-only string called currdir with the value of the current working directory. __definegetter__("currdir", function getcurrdir() { return components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsidirectoryserviceprovider) .getf...
nsIDirectoryServiceProvider2
enumerator getfiles(in string prop); methods getfiles() the directory service calls this when it gets a request for a prop and the requested type is nsisimpleenumerator. nsisimpleenumerator getfiles( in string prop ); parameters prop the symbolic name of the file list. return value an enumerator for a list of file locations. the elements in the enumeration are nsifile. use an xpcom return code of ns_success_aggregate_result if this result should be aggregated with other "lower" providers. if you are implementing this from js, you would be using components.returncode, but sadly this does not currently work (see bug 287107). ...
nsIEffectiveTLDService
the public suffix. exceptions thrown ns_error_invalid_arg this exception is thrown if ahost is empty. ns_error_unexpected this exception originates in the normalize() method in nsiidnservice and is thrown when ahost contains characters disallowed in uris. ns_error_host_is_ip_address this exception is thrown if ahost is a numeric ipv4 or ipv6 address. remarks all returned strings are encoded in ascii/ace and normalized according to rfc 3454. ...
nsIEventListenerInfo
divalue. otherwise null. this is the method you should use if you want to get access to the actual listener, but the debugger service must be already active, which significantly slows down script execution. accordingly, this should probably only be used by real debuggers. this approach is necessary because event listeners added with addeventlistener won't necessarily be nsieventlisteners; the dom code will fix up ordinary javascript functions to act as listeners. tosource() tries to serialize the event listener to a string. astring tosource(); parameters none. return value returns a string describing the event listener, or null if serialization isn't possible (for example, if the listener was written in c++). remarks nsieventlistenerinfo was introduced with bug 448602. see also nsieventlist...
nsIException
an inner exception that triggered this, if available. read only. linenumber pruint32 valid line numbers begin at '1'. '0' indicates unknown. read only. location nsistackframe a stack trace, if available. read only. message string a custom message set by the thrower. [binaryname(messagemoz)] read only. name string the name of the error code (a string representation of result) read only. result nsresult the nsresult associated with this exception. read only. methods tostring() a generic formatter - make it suitable to print, etc. string tostring(); parameters none. return value a string suitable for output. ...
nsIExternalHelperAppService
method overview boolean applydecodingforextension(in autf8string aextension, in acstring aencodingtype); nsistreamlistener docontent(in acstring amimecontenttype, in nsirequest arequest, in nsiinterfacerequestor awindowcontext, in boolean aforcesave); methods applydecodingforextension() determines whether or not data whose filename has the specified extension should be decoded from the specified encoding type before being saved or delivered to helper applications. boolean applydecodingforextension( in autf8string aextension, in acstring aencodingtype ); parameters aextension the filename extension to check. aencodingtype the encoding type to check. return value true if data from urls with the specified extension and encoding should be decoded pr...
nsIExternalProtocolService
part of the scheme itself. that is, pass "mailto" not "mailto:". return value true if we have a handler and false otherwise. getapplicationdescription() gets a human-readable description for the application responsible for handling a specific protocol. astring getapplicationdescription( in autf8string ascheme ); parameters ascheme the scheme to look up. for example, "mms". return value this code makes little sense and needs to be cleaned up. -nickolay <pre> // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"].getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .g...
nsIFeedProgressListener
sult object. note: if the feed type is one of the entry or item-only types, this event will never be called. void handlefeedatfirstentry( in nsifeedresult result ); parameters result an nsifeedresult describing the feed at the point at which the first entry is found, but before processing it. handlestartfeed() called as soon as a reasonable start to a feed is detected; this lets your code know that the feed does appear to be an actual feed rather than some other sort of document. void handlestartfeed( in nsifeedresult result ); parameters result an nsifeedresult describing the current state of the feed at the moment parsing begins. reporterror() called by the feed processor when a fatal xml parsing error occurs, or if the document isn't a feed. void reporterror( in ...
nsIFeedTextConstruct
aining the text and (if the text construct contains html or xhtml) its markup. nsidomdocumentfragment createdocumentfragment( in nsidomelement element ); parameters element the element in which to create the new document fragment. return value an nsidocumentfragment containing the text and markup. plaintext() returns the text as plain text with all markup stripped and all entities decoded. astring plaintext(); parameters none. return value the plain text version of the text construct's contents. if the type attribute is "text", this method returns the value of the text attribute unchanged. remarks if the document type is either "html" or "xhtml", a "<" character represents markup. to display that character, an escape such as "&lt;" must be used. if the type is "text", the...
nsIFileProtocolHandler
a local file and tries to interpret it as an internet shortcut (for example .url files on windows). nsiuri readurlfile( in nsifile file ); parameters file the nsifile to read. return value the nsiuri the file refers to. exceptions thrown ns_error_not_available the os does not support such files. ns_error_not_available the file is not an internet shortcut. see also code_snippets:file_i/o ...
nsIINIParserWriter
(in autf8string asection, in autf8string akey, in autf8string avalue); void writefile([optional] in nsifile ainifile, [optional] in unsigned long aflags); constants file writing constants these constants are specified when calling writefile(), in order to change its behavior. constant value description write_utf16 0x1 windows and the nsis installer code sometimes expect ini files to be in utf-16 encoding. on windows only, this flag to writefile() can be used to change the encoding from its default utf-8. methods setstring() set the value of a property string for a particular section and key. void setstring( in autf8string asection, in autf8string akey, in autf8string avalue ); parameters asection the name of the section in...
nsIJSID
d an nsiidref parameter, such as queryinterface(). note that for these cases of jsid the specified class or interface must exist and be scriptable. method overview boolean equals(in nsijsid other); const nsid* getid(); violates the xpcom interface guidelines void initialize(in string idstring); string tostring(); attributes attribute type description id nsidptr read only. native code only! obsolete since gecko 1.9 the internal nsid. name string read only. the name of the jsid, if it was set. number string read only. the string representation of the internal nsid. valid boolean read only. returns true if the jsid has been initialised. methods equals() this method determines if this nsijsid has the same nsid as another nsijsid. boolean equals( in nsijsid other ); pa...
nsIJetpack
no longer be triggered. areceiver the javascript function that should no longer be triggered. unregisterreceivers() this unregisters all callbacks previously registered with registerreceiver() for a particular message. void unregisterreceivers( in astring amessagename ); parameters amessagename the name of the message to unregister all callbacks from. evalscript() this asynchronously sends code to the jetpack process for evaluation. the code will be evaluated using at least javascript 1.8.1. when evaluated, the script's global scope will include all privileged apis. individual lines of the form //@line 1 "foo.js" can be used to specify filename and line number information for debugging purposes. void evalscript( in astring ascript ); parameters ascript the full contents of the scrip...
nsILocale
d in nsilocale.idl. currently those are: nsilocale_collate - collation order. how strings are sorted. nsilocale_ctype - character classification and case conversion. nsilocale_monetary - monetary formatting. nsilocale_numeric - numeric, non-monetary formatting. nsilocale_time - date and time formats. nsilocale_messages - related to fonts, character encodings and so on. return value the locale code to be used for the given category. a locale code is of the form language[-country[-region]], where "language" is an iso 639 language code (two letter codes preferred over three letter codes when available), "country" is an iso 3166 two letter country code, and "region" is a string of up to 5 letters. see also stringbundle ...
nsILocaleService
value the most preferred locale according to the acceptlanguage parameter. getsystemlocale() gets the user preference for locale from the operating system. nsilocale getsystemlocale(); parameters none. return value the user's os setting for preferred locale. newlocale() create a new nsilocale from a locale string. nsilocale newlocale( in astring alocale ); parameters alocale a locale code as described in nsilocale. return value a nsilocale representing the given locale. newlocaleobject() obsolete since gecko 1.9 (firefox 3) nsilocale newlocaleobject( in nsilocaledefinition localedefinition ); parameters localedefinition a locale definition as described in nsilocaledefinition. return value a nsilocale representing the given locale. calls to i...
nsILoginManagerCrypto
f the ciphertext value can not be successfully decrypted (for example, if it was encrypted with some other key). astring decrypt( in astring ciphertext ); parameters ciphertext the string to be decrypted. return value the decrypted string. encrypt() encrypts the specified string, returning the ciphertext value. note: the current implemention of this inferface simply uses nss/psm's "secret decoder ring" service. it is not recommended for general purpose encryption/decryption. can throw if the user cancels entry of their master password. astring encrypt( in astring plaintext ); parameters plaintext the string to be encrypted. return value the encrypted string. ...
nsIMIMEInputStream
he nsimimeinputstream also is used as an nsiseekablestream. ...
nsIMacDockSupport
idget/standalonenativemenu;1"].createinstance(ci.nsistandalonenativemenu); console.log('dockmenuelement:', dockmenuelement); nativemenu.init(dockmenuelement); docksupport.dockmenu = nativemenu; this replaces the default menu with this one menuitem that says "show most recent window". notice the activateapplication(true), if this is not done then firefox will not be activated. the result of this code is shown below. notice how the "new window" and "new private window" menuitem's are missing. therefore, if you would like to add or remove items to the menu it is recommended to manipulate the default menu item which is on the hidden window of firefox. note: the hidden window of firefox (services.appshel.hiddendomwindow) loads on browser startup, so if you would like to access it on startup of t...
nsIMarkupDocumentViewer
textdirection octet options for bidi presentation. use these attributes to access the individual bidi options. the default direction for the layout of bidirectional text. 1 - left to right 2 - right to left. biditexttype octet the ordering of bidirectional text. this may be either "logical" or "visual". logical text will be reordered for presentation using the unicode bidi algorithm. visual text will be displayed without reordering. 1 - the default order for the charset 2 - logical order 3 - visual order. defaultcharacterset acstring forcecharacterset acstring fullzoom float the amount by which to scale all lengths. default is 1.0. hintcharacterset acstring hintcharactersetsource pr...
nsIMemoryReporter
xpcom/base/nsimemoryreporter.idlscriptable reports memory usage information for a single area of the software. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) any piece of code that wishes to allow its memory use to be monitored may create an nsimemoryreporter object and then register it by calling nsimemoryreportermanager.registerreporter(). once that has been done, the reporter will be found by any client accessing the enumerator returned by nsimemoryreportermanager.enumeratereporters(). this includes the about:memory page. note: this interface is undergoing heavy development, and is subject to rapid changes. attributes attribute type description ...
nsIMenuBoxObject
layout/xul/base/public/nsimenuboxobject.idlscriptable represents the box object for a xul menu. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) to get access to the box object for a given menu, use code like this: var boxobject = xulmenu.boxobject.queryinterface(components.interfaces.nsimenuboxobject); method overview boolean handlekeypress(in nsidomkeyevent keyevent); void openmenu(in boolean openflag); attributes attribute type description activechild nsidomelement the currently active menu or menuitem child of the menu box. openedwithkey boolean true if the menubar was opened using the keyboard; otherwise false. note: for gecko 2.0, the openedwi...
nsIMessenger
names for each attachment. messageuriarray an array of urls for the message containing each attachment. savefirst if true, the attachments are saved using saveallattachments() before being deleted. withoutwarning if true, no warning is shown to the user before the delete. saveattachmenttofolder() saves an attachment in a given folder. saveattachmenttofolder() is used by the drag and drop code to drop an attachment to a destination folder. returns the actual file path (including the filename). nsilocalfile saveattachmenttofolder(in acstring , in acstring url, in acstring displayname, in acstring messageuri, in nsilocalfile adestfolder); ...
nsIModule
oad( in nsicomponentmanager acompmgr ); parameters acompmgr the global component manager. return value indicates to the caller whether or not the component module can be unloaded. returning true is not a guarantee that the module will be unloaded. it constitues only willingness of the module to be unloaded. it is very important to ensure that no outstanding references to the module's code/data exist before returning true. returning false guaratees that the module will not be unloaded. if the component module is native (that is, as part of a dll), then this method may be called to determine whether or not the dll may be unloaded from memory. note: as of gecko 1.7, native component modules are never unloaded. getclassobject() obtains a class object from a nsimodule for a given cid a...
Building an Account Manager Extension
n for imap accounts... if (server.type == \"imap\") return true; return false; }, queryinterface: xpcomutils.generateqi([ components.interfaces.nsimsgaccountmanagerextension ]) } step 2: building a component we convert the interface to a xpcom component and register it in the component manager as account manager extension. therefore we add the following code to the previous. the javascript file has to be saved either in the extension's or thunderbird's component directory. // define the contract information needed for this component... // ... the unique component identifier (change it if you copied this example!)... devmoaccountmanagerextension.prototype.classid = components.id("{659ce960-9dfb-11dd-ad8b-0800200c9a55}"); // ... the description and ...
nsIMsgCompFields
receiptheadertype print32 references char * replyto astring securityinfo nsisupports subject astring templatename astring temporaryfiles char * obsolete temporaryfiles obsolete, do not use anymore to astring usemultipartalternative prbool uuencodeattachments prbool methods utility methods prbool checkcharsetconversion ( out char * fallbackcharset ); nsimsgrecipientarray splitrecipients ( in prunichar * recipients, in prbool emailaddressonly ); void convertbodytoplaintext ( ); attachment handling methods void addattachment ( in nsimsgattachment attachment ); vo...
nsIMsgDBView
w pane of thunderbird and other xpcom based mail cients. inherits from: nsisupports implemented by: @mozilla.org/messenger/msgdbview;1. to create an instance, use: var dbview = components.classes[@mozilla.org/messenger/msgdbview;1?type=] .createinstance(components.interfaces.nsimsgdbview); where type designates different types of view's available. available in the mozilla codebase are types "quicksearch", "threadswithunread", "watchedthreadswithunread", "xfvf" (virtual folders), "search", "group", and "threaded" each with their own implementation of nsimsgdbview that provides a different sorting/view of the data. method overview void open(in nsimsgfolder folder, in nsmsgviewsorttypevalue sorttype, in nsmsgviewsortordervalue sortorder, in nsmsgviewflagstypeva...
nsIMsgIdentity
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. astring getunicharattribute(in string name); parameters name setunicharattribute() setter for unicode attributes. void setunicharattribute(in string name, in astring value); parameters name name of the attribute to set. value value to set the attribute to. getcharattribute() getter for char attributes. acstring g...
nsIMsgSearchNotify
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchnotify.idl [scriptable, uuid(ca37784d-352b-4c39-8ccb-0abc1a93f681)] interface nsimsgsearchnotify : nsisupports { void onsearchhit(in nsimsgdbhdr header, in nsimsgfolder folder); // notification that a search has finished. void onsearchdone(in nsresult status); /* * until we can encode searches with a uri, this will be an * out-of-bound way to connect a set of search terms to a datasource */ /* * called when a new search begins */ void onnewsearch(); }; ...
nsIMsgWindow
dow is stored in the global variable msgwindow. method overview void displayhtmlinmessagepane(in astring title, in astring body, in boolean clearmsghdr); void stopurls(); void closewindow(); attributes attribute type description windowcommands nsimsgwindowcommands this allows the backend code to send commands to the ui, such as clearmsgpane. statusfeedback nsimsgstatusfeedback this allows the backend code to send status feedback to the ui. msgheadersink nsimsgheadersink this allows the backend code to send message header information to the ui. transactionmanager nsitransactionmanager this is used to tr...
nsINavHistoryService
ri the uri that needs to be added to the history system. return value returns true if this uri would be added to the history, otherwise returns false. addvisit() 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 moziasynchistory.updateplaces() instead. see this code for how a function to add visits and handle errors using the new api could look like. this method adds a visit for a specific page. this will probably not be commonly used other than for backup/restore type operations. if the uri does not have an entry in the history database already, one will be created with no visits, no title, hidden, not typed. adding a visit will automatically increment th...
nsIObserver
n implementation of nsiobserverservice is the xpcom observer service. with this implementation, it's safe (and common practice) for an implementation of nsiobserver to remove itself as an observer during the observe callback, or to add or remove other observers. be careful, though, because other uses of nsiobserver may not support these operations correctly within observe. example the following code is an implementation of nsiobserver that is registered to receive notifications for the "mytopicid" topic. see observer notifications for a list of built-in topics possible. observing preferences works slightly differently. see code snippets:preferences - using preference observers for an example. function myobserver() { this.register(); } myobserver.prototype = { observe: function(subject...
nsIParentalControlsService
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: currently, this interface is only supported on microsoft windows vista and newer as well as android 4.3 and newer. implemented by: @mozilla.org/parental-controls-service;1. ...
nsIParserUtils
ole for everything that gets sanitized. methods converttoplaintext() converts html to plain text. astring converttoplaintext( in astring src, in unsigned long flags, in unsigned long wrapcol ); parameters src the html source to parse (c++ callers are allowed but not required to use the same string for the return value.) flags conversion option flags defined in nsidocumentencoder. wrapcol number of characters per line; 0 for no auto-wrapping. return value the plain text conversion of the html specified in src. parsefragment() parses markup into a sanitized document fragment. nsidomdocumentfragment parsefragment( in astring fragment, in unsigned long flags, in boolean isxml, in nsiuri baseuri, in nsidomelement element ); parameters fragment the inp...
nsIPrintingPrompt
service is automatically registered at start up. historically, platform toolkits with native dialogs have implemented them in the gfx layer usually they were displayed when a new devicecontextspec specific to that platform was created. windows: the gfx layer no longer supports default toolkit behavior for displaying the native print dialog. if an embedder implemented service returns any error code (other than ns_error_abort) printing will terminate. returning ns_ok assumes that the printsettings object was correctly filled in and if it does not have valid fields for printer name, and so on. it may also terminate. defaults for platform service: showprintdialog - displays a native dialog showpagesetup() - displays a xul dialog showprogress() - displays a xul dialog summary for windo...
nsIPropertyBag
ameters name the name to return the matching property. return value the property matching the given name. exceptions thrown ns_error_failure if a property with that name doesn't exist. examples get user agent information (operating system specifics. the window scope is not always accessible so the window.navigator cannot be accessed. ...
nsIProtocolProxyCallback
est the value returned from asyncresolve. auri the uri passed to asyncresolve. aproxyinfo the resulting proxy info or null if there is no associated proxy info for auri. as with the result of nsiprotocolproxyservice's resolve method, a null result implies that a direct connection should be used. astatus the status of the callback. this is a failure code if the request could not be satisfied, in which case the value of astatus indicates the reason for the failure and aproxyinfo will be null. the value returned from asyncresolve. see also nsicancelable nsiuri nsiproxyinfo nsiprotocolproxyservice ...
nsIProtocolProxyService
ay be used instead. as a side-effect, this method may affect future result values from resolve/asyncresolve as well as from getfailoverforproxy. nsiproxyinfo getfailoverforproxy( in nsiproxyinfo aproxyinfo, in nsiuri auri, in nsresult areason ); parameters aproxyinfo the proxy that was unavailable. auri the uri that was originally passed to resolve/asyncresolve. areason the error code corresponding to the proxy failure. this value may be used to tune the delay before this proxy is used again. the proxy that was unavailable. return value an nsiproxyinfo object or null for a direct connection. exceptions thrown ns_error_not_available if there is no alternate proxy available. registerfilter() this method may be used to register a proxy filter instance. each proxy filte...
nsIRequest
f the status attribute. implementations must not send any notifications (for example via nsirequestobserver) synchronously from this function. similarly, removal from the load group (if any) must also happen asynchronously. requests that use nsistreamlistener must not call ondataavailable anymore after cancel has been called. note: most nsirequest implementations expect astatus to be a failure code; however, some implementations may allow astatus to be a success code such as ns_ok. in general, astatus should be a failure code. void cancel( in nsresult astatus ); parameters astatus the reason for canceling this request. ispending() indicates whether the request is pending. ispending is true when there is an outstanding asynchronous event that will make the request no longer be pe...
nsIResumableChannel
esn't support this. this error may occur even if startpos is 0, so that the front end can warn the user. similarly, the status of this channel during onstartrequest may be ns_error_entity_changed, which indicates that the entity has changed, as indicated by a changed entityid. in both of these cases, no ondataavailable will be called, and onstoprequest will immediately follow with the same status code. void resumeat( in unsigned long long startpos, in acstring entityid ); parameters startpos the starting offset, in bytes, to use to download. entityid information about the file, to match before obtaining the file. pass an empty string to use anything. see also implementing download resuming ...
nsISSLErrorListener
ror(in nsiinterfacerequestor socketinfo, in print32 error, in autf8string targetsite); methods notifysslerror() called in case of an ssl error. boolean notifysslerror( in nsiinterfacerequestor socketinfo, in print32 error, in autf8string targetsite ); parameters socketinfo a network communication context that can be used to obtain more information about the active connection. error the code associated with the error. the ssl status object that describes the problem(s). targetsite the site name that was used to open the current connection. return value the consumer shall return true if it wants to suppress the error message related to the error (the connection will still get canceled). see also nsisockettransport ...
nsIScriptError2
providing that line. you may pass null if you are lazy; that will prevent showing the source line in javascript console. linenumber the number of the line where the error occurred. columnnumber the column number where the error occurred. this is used to draw an arrow pointing to the problem character. flags one of the script error flag constants. category a string indicating what kind of code caused the message. there are quite a few category strings and they don't seem to be listed in a single place. see categories for a partial list. innerwindowid the id of the inner window associated with the error. prior to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), this was the outer window id. ...
nsIScriptableUnescapeHTML
nsidomelement to be used as the context node for the purposes of the fragment parsing algorithm. return value an nsidomdocumentfragment of the element with the new text appended. exceptions thrown ns_error_failure unable to append the text to the element. unescape() convents html source into plain text. this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0). you should call nsiparserutils::converttoplaintext() instead of calling this method. astring unescape( in astring src ); parameters src the html string to convert into plain text. return value the result of the plain text conversion. exceptions thrown ns_error_failure unable to convert the string. see also ...
nsISimpleEnumerator
alled without subsequent getnext() calls. ...
nsIStreamConverter
you could implement this interface to allow everyone else to use your conversion logic using a standard api. stream converter users there are currently two ways to use a stream converter: synchronous: stream to stream. you can supply the service with a stream of type x and it will convert it to your desired output type and return a converted (blocking) stream to you. ...
nsISupportsString
inherits from: nsisupportsprimitive last changed in gecko 1.2 method overview string tostring(); attributes attribute type description data astring provides access to the native type represented by the object. methods tostring() this methods returns a string valued representation of the object. string tostring(); parameters none. return value a string valued representation of the object. remarks this interface was frozen for gecko 1.2. ...
nsISupportsVoid
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for generic pointers. inherits from: nsisupportsprimitive last changed in gecko 1.0 method overview string tostring(); attributes attribute type description data voidptr this attribute provides access to the native type represented by the object. native code only! methods tostring() string tostring(); parameters none. return value a string valued representation of the object. ...
nsITaskbarPreviewController
humbnail() for more information. read only. width unsigned long the width in pixels of the preview image. this value may change at any time. see drawpreview() for more information. read only. note: although these attributes are read only, that indicates that the previews controlled by an nsitaskbarpreviewcontroller cannot alter these values. the controller and its supporting code, however, may change this values at any time. methods drawpreview() invoked by nsitaskbarpreview when it needs to render the preview. the specified context is attached to a surface with the controller's width and height, the values of which are obtained immediately prior to calling this method. boolean drawpreview( in nsidomcanvasrenderingcontext2d ctx ); parameters ctx an nsidomcanva...
nsIThread
ses the next pending event. if there aren't any pending events, this method may wait -- depending on the value of the maywait parameter -- until an event is dispatched to the thread. this method is re-entrant but may only be called if this thread is the current thread. warning: calling nsithread.processnextevent allows network and ui events to run which can modify data structures that your code isn't expecting to be modified during a synchronous method call. this can cause random crashes and other bugs that may be hard to find and fix. consider use asynchronous callbacks instead. boolean processnextevent( in boolean maywait ); parameters maywait if true, this method blocks until an event is available to process if the event queue is empty. if false, this method returns immedia...
nsIToolkitProfileService
toolkit/profile/public/nsitoolkitprofileservice.idlscriptable the profile service manages user profiles. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) note: starting in gecko 1.9.1, this service is implemented by @mozilla.org/toolkit/profile-service;1. to access the service, you can use the following code: var toolkitprofileservice = components.classes["@mozilla.org/toolkit/profile-service;1"] .createinstance(components.interfaces.nsitoolkitprofileservice); prior to gecko 1.9.1 only the built-in profile manager was able to access the toolkit profile service. to access the built-in profile manager in versions of firefox up to 4.0 and thunderbird up to 3.3 you can launch with the -profilemana...
nsITransport
ize, in unsigned long asegmentcount); nsioutputstream openoutputstream(in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount); void seteventsink(in nsitransporteventsink asink, in nsieventtarget aeventtarget); constants open flags. constant value description open_blocking 1<<0 open flags. open_unbuffered 1<<1 generic nsitransporteventsink status codes. nsitransport implementations may override these status codes with their own more specific status codes (for example, see nsisockettransport). constant value description status_reading 0x804b0008 status_writing 0x804b0009 methods close() close the transport and any open streams. void close( in nsresult areason ); parameters areason the reason for closing the stream. openinputs...
nsITransportEventSink
transportstatus() transport status notification. void ontransportstatus( in nsitransport atransport, in nsresult astatus, in unsigned long long aprogress, in unsigned long long aprogressmax ); parameters atransport the transport sending this status notification. astatus the transport status (resolvable to a string using nsierrorservice). see nsisockettransport for socket specific status codes and more comments. aprogress the amount of data either read or written depending on the value of the status code. this value is relative to aprogressmax. aprogressmax the maximum amount of data that will be read or written. if unknown, 0xffffffff will be passed. see also nsitransport nsisockettransport ...
nsIURI
on is case-insensitive. ...
nsIURIFixup
allow the fixup to use a keyword lookup service to complete the uri. the fixup object implementer should honour this flag and only perform any lengthy keyword (or search) operation if it is set. fixup_flags_make_alternate_uri 2 tell the fixup to make an alternate uri from the input uri, for example to turn foo into www.foo.com. fixup_flag_use_utf8 4 use utf-8 to encode the uri instead of the platform character set. fixup_flag_fix_scheme_typos 8 fix common scheme typos. methods createexposableuri() converts an internal uri (for example a wysiwyg uri) into one which we can expose to the user, for example on the url bar. nsiuri createexposableuri( in nsiuri auri ); parameters auri the uri to be converted. return value the conve...
nsIUpdate
l astring the url to a page which offers details about the content of this update. ideally, this page is not the release notes but some other page that summarizes the differences between this update and the previous, which also links to the release notes. displayversion astring the string to display in the user interface for the version. if you want a real version number use appversion. errorcode long a numeric error code that conveys additional information about the state of a failed update or failed certificate attribute check during an update check. if the update is not in the "failed" state, this value is zero. ok (0) no error. mem_error (1) a memory error occurred. usage_error (3) a usage error occurred; this needs to be described in more detail. crc_error (4) a checksum error occur...
nsIUpdateItem
ust be in the format of "type:hash" (see the types in nsicryptohash and nsixpinstallmanager.initmanagerwithhashes(). read only. xpiurl astring the url of the xpi where this item can be downloaded. read only. constants item type constants constants representing types of update checks. constants that callers can use to indicate the reason for an add-on update check. internal code uses other constants in nsextensionmanager.js.in. constant gecko version description 1.8 1.8.1 1.9 1.9.1 1.9.2 type_app 0x01 type_extension 0x02 type_theme 0x04 type_locale 0x08 type_multi_xpi 0x20 type_addon type_extension + type_theme + type_locale + type_plugin ...
nsIUploadChannel
we have a special meaning for the acontenttype parameter. void setuploadstream( in nsiinputstream astream, in acstring acontenttype, in long acontentlength ); parameters astream the stream to be uploaded by this channel. acontenttype if acontenttype is empty, the protocol will assume that no content headers are to be added to the uploaded stream and that any required headers are already encoded in the stream. in the case of http, if this parameter is non-empty, then its value will replace any existing content-type header on the http request. in the case of ftp and file, this parameter is ignored. acontentlength a value of -1 indicates that the length of the stream should be determined by calling the stream's available method. ...
nsIWebBrowser
siweakreference might also need to be implemented by the chrome object. contentdomwindow nsidomwindow the top-level dom window. the embedder may walk the entire dom starting from this value. read only. isactive boolean indicates whether this web browser is active. active means that it's visible enough that we want to avoid certain optimizations like discarding decoded image data and throttling the refresh driver. in firefox, this corresponds to the visible tab. defaults to true. for optimal performance, set it to false when appropriate. parenturicontentlistener nsiuricontentlistener uri content listener parent. the embedder may set this property to their own implementation if they intend to override or prevent how certain kinds of con...
nsIWebappsSupport
; boolean isapplicationinstalled(in wstring uri); methods installapplication() this method installs a web application. void installapplication( in wstring title, in wstring uri, in wstring iconuri, in wstring icondata ); parameters title the user-friendly name of the application. uri the uri of the web application. iconuri the uri of icon of the web application. icondata a base64 encoded representation of the application's icon. isapplicationinstalled() checks is a web application is already installed. boolean isapplicationinstalled( in wstring uri ); parameters uri the uri of the web application. return value true if the web application is installed, false if it's not installed. ...
nsIXFormsNSModelElement
nsixformsnsmodelelement is implemented by all xforms <model/> elements. it defines mozilla extensions to the nsixformsmodelelement interface. extensions/xforms/nsixformsnsmodelelement.idlscriptable please add a summary to this article. last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) interface code [scriptable, uuid(85fd60c7-1db7-40c0-ae8d-f723fdd1eea8)] interface nsixformsnsmodelelement : nsisupports { nsidomnodelist getinstancedocuments(); }; methods getinstancedocuments nsidomnodelist getinstancedocuments(); getinstancedocuments returns a nsidomnodelist containing all the instance documents for the model, making it possible to enumerate over instances in the model without knowing their names. related interfaces nsixformsmodelelement example c...
nsIXPCScriptable
turn pr_false to indicate failure. newresolve() this method is called when the want_newresolve flag is set. when this method is called, xpconnect is attempting to resolve a lazy property named by id on obj. the js engine will check if the property named by id is defined after this method has been called. this is very similar to jsnewresolveop. if an implementation of this method throws an error code, the prototype chain will not be checked for the property. prbool newresolve( in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in pruint32 flags, out jsobjectptr objp ); parameters wrapper cx the pointer to the jscontext newresolve is being called from. obj the pointer to the jsobject that the property named by id that is being ...
nsIXULAppInfo
o;1"] .getservice(components.interfaces.nsixulappinfo); alert("application version: " + info.version + "\n" + "gecko version: " + info.platformversion); example this example here uses nsixulappinfo to get the version of the current browser and then compares it: example - compare current browser version see also using nsixulappinfo nsixulruntime get thunderbird version firefox code snippets ...
nsIXULBrowserWindow
the browser area to tell the containing xul window to update its user interface. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the xulbrowserwindow attribute exists on the nsixulwindow interface although both firefox and seamonkey also store their nsixulbrowserwindow reference in the global xulbrowserwindow object accessible from javascript code. note: the xulbrowserwindow object offered to javascript code provides a great many more methods and attributes than those listed here, which are only the ones available to c++ code. see the documentation for xulbrowserwindow for details. method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); void setjsdefault...
nsIXULSortService
idlscriptable a service used to sort the contents of a xul widget. inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void insertcontainernode(in nsirdfcompositedatasource db, in nsrdfsortstate sortstateptr, in nsicontent root, in nsicontent trueparent, in nsicontent container, in nsicontent node, in boolean anotify); native code only! obsolete since gecko 1.9 void sort(in nsidomnode anode, in astring asortkey, in astring asorthints); constants constant value description sort_comparecase 0x0001 sort_integer 0x0100 methods native code only!insertcontainernode 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...
nsIXmlRpcClient
n whether or not a call is in progress fault readonly nsixmlrpcfault the most recent xml-rpc fault from returned from this server. null if the last call didn't return an xml-rpc fault. result readonly nsisupports the most recent xml-rpc call result returned from this server. null if the last call didn't return a valid result. responsestatus readonly unsigned long the most recent http status code returned from this server. null if the server was unreachable or not yet contacted. responsestring readonly unsigned long the most recent http status code returned from this server. null if the server was unreachable or not yet contacted. constants constant type description int unsigned long nsisupportsprint32 boolean unsigned long nsisupportsprbool string unsigned long nsisupportsc...
XPCOM Interface Reference by grouping
cessiblehypertext nsiaccessibleimage nsiaccessibleprovider nsiaccessibleretrieval nsiaccessiblerole nsiaccessiblescrolltype nsiaccessibleselectable nsiaccessiblestates nsiaccessibletable nsiaccessibletext nsiaccessibletreecache nsiaccessiblevalue nsiaccessnode nsisyncmessagesender script nsiscriptableunescapehtml nsiscriptableunicodeconverter nsiscripterror nsiscripterror2 stylesheet nsistylesheetservice url nsiuri nsiurl util nsidomserializer nsidomxpathevaluator nsidomxpathexception nsidomxpathexpression nsidomxpathresult xslt nsixsltexception nsixsltprocessor download nsidownload nsidownloadmanager nsidownloadprogresslistene...
NS_CStringAppendData
n] a nsacstring instance to be modified. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. return values the ns_cstringappenddata function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringappenddata(str, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this function was frozen for mo...
NS_CStringContainerInit2
pointer. the caller must have allocated the data array using the xpcom memory allocator. this flag should not be combined with ns_cstring_container_init_depend. ns_cstring_container_init_substring data passed into ns_cstringcontainerinit2 is a substring that is not null-terminated. return values the ns_cstringcontainerinit function returns ns_ok if successful. otherwise, it returns an error code. remarks after a nscstringcontainer object has been initialized via ns_cstringcontainerinit2, it may be used as an ordinary nsacstring object. when the string object is no longer needed, it should be passed to ns_cstringcontainerfinish to free any extra memory that the string object may have allocated. it is generally better to use one of the helper classes, such as nscstring, instead of codin...
NS_CStringCopy
o another. this is a low-level api. #include "nsstringapi.h" nsresult ns_cstringcopy( nsacstring& adeststring, const nsacstring& asrcstring ); parameters adeststring [in] a nsacstring instance to be modified. asrcstring [in] a nsacstring instance containing the new string value. return values the ns_cstringcopy function returns ns_ok if successful. otherwise, it returns an error code. remarks this function is designed to allow the implementation to efficiently assign the same value to two string objects. the implementation may employ reference counting techniques to optimize this operation. example /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsacstring& avalue) { return ns_cstringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const...
NS_CStringGetData
ng [in] a nsacstring instance to inspect. adata [out] a const pointer to the string's internal buffer. aterminated [out] this optional result parameter indicates whether or not adata is null-terminated. it may be null if the caller is not interested in this information. return values the ns_cstringgetdata function returns the length of adata, measured in storage units (bytes). example code // count the number of times a particular character appears in a string. pruint32 countchar(const nsacstring& str, char c) { const char* data; pruint32 len = ns_cstringgetdata(str, &data); pruint32 count = 0; for (pruint32 i = 0; i < len; ++i) { if (data[i] == c) ++count; } return count; } history this function was finalized for mozilla 1.7. see bug 239123 for detai...
NS_CStringSetData
ring [in] a nsacstring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null-terminated. return values the ns_cstringsetdata function returns ns_ok if successful. otherwise, it returns an error code. example nscstringcontainer str; rv = ns_cstringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_cstringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsacstring&| parameter. } ns_cstringcontainerfinish(str); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsacstring ...
NS_CStringSetDataRange
to replace, measured in storage units. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_cstringsetdatarange function returns ns_ok if successful. otherwise, it returns an error code. example // replace all occurances of |matchval| with |newval| void replacesubstring(nsacstring& str, const nsacstring& matchval, const nsacstring& newval) { const char* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_cstringgetdata(str, &sp); ml = ns_cstringgetdata(matchval, &mp); nl = ns_cstringgetdata(newval, &np); for (const char* iter ...
NS_StringContainerFinish
« xpcom api reference summary the ns_stringcontainerfinish function releases any memory allocated by a nsstringcontainer instance. this is a low-level api. #include "nsstringapi.h" void ns_stringcontainerfinish( nsstringcontainer& astring ); parameters astring [in] a nsstringcontainer instance that is no longer needed. return values this function does not return a value. example code see ns_stringcontainerinit for an example. history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringcontainerinit ...
NS_StringGetData
, const prunichar** adata, prbool* aterminated ); parameters astring [in] a nsastring instance to inspect. adata [out] a const pointer to the string's internal buffer. aterminated [out] this optional result parameter indicates whether or not adata is null-terminated. return values the ns_stringgetdata function returns the length of adata, measured in storage units (bytes). example code pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* data; pruint32 len = ns_stringgetdata(str, &data); pruint32 count = 0; for (pruint32 i = 0; i < len; ++i) { if (data[i] == c) ++count; } return count; } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsastring ...
NS_StringSetData
ters astring [in] a nsastring instance to modify. adata [in] a raw character array to copy into this string. adatalength [in] the length of adata, measured in storage units. if equal to pr_uint32_max, then adata is assumed to be null-terminated. otherwise, adata need not be null terminated. return values the ns_stringsetdata function returns ns_ok if successful. otherwise, it returns an error code. example code nsstringcontainer str; rv = ns_stringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_stringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsastring&| parameter. } ns_stringcontainerfinish(str); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see als...
The Thread Manager
the thread manager, introduced in firefox 3, offers an easy to use mechanism for creating threads and dispatching events to them for processing. only c++ code may use the thread manager and xpcom thread. application/extension javascript should consider using a chromeworker instead.") interfaces there are several interfaces that provide threading support: nsithreadmanager the thread manager itself lets you create threads. nsithread the nsithread interface encapsulates an operating system thread, providing easy cross-platform access to multithreading in your code. nsithreadpool a thread pool provides a limited set of worker threads. when you dispatch an event to the pool, the pool selects an available worker thread to process the event. nsithreadinternal a subclass of nsithread tha...
Using IndexedDB in chrome
this method was removed in firefox 33. ...
Using nsIClassInfo
what is nsiclassinfo good for? if you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly call queryinterface on the javascript object to access the object's interfaces. nsiclassinfo is good for other things too, but they're dark xpcom magic. how do i use it? if you're writing javascript code which uses a c++ class implementing nsiclassinfo, you don't need to do anything to activate the auto-interface magic which makes calling queryinterface unnecessary. it just happens. how do i make my c++ class implement nsiclassinfo? see nsiclassinfoimpl.h for instructions. how does nsiclassinfo work? that's also detailed in nsiclassinfoimpl.h. original document information authors: mike shaver, justin lebar last updated date: july 25, 201...
Using nsISimpleEnumerator
simpleenumerator(enum, interface) { while (enum.hasmoreelements()) { yield enum.getnext().queryinterface(interface); } } var b = document.getelementbyid("stringbundleset").firstchild var props = generatorfromenumerator(b.strings, components.interfaces.nsipropertyelement); var s = ""; for (let property in props) { s += property.key + ' = ' + property.value + ';\n'; } alert(s); links code based on using_nsipasswordmanager nsisimpleenumerator xul:property:strings ...
Working with out parameters
from javascript via xpconnect, you have to follow a specific rule. to get at the out parameters, you have to pass in an object. after the call, this object will have a new property called value, which contains the out values. assuming you have an object called transferable, you would invoke gettransferdata() as follows: var adata = {}; var adatalen = {}; transferable.gettransferdata("text/unicode", adata, adatalen); var data = adata.value; var datalen = adatalen.value; as you can see, after the call to gettransferdata(), the out values are then contained in the value properties of adata and adatalen. implementation when implementing a method which has out parameters in javascript, you have to set a new property called value to the out parameter which will hold the required value. you...
XPCOM ABI
- ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmatically by using the nsixulruntime interface. to retrieve the abi of your firefox or thunderbird, open the error console (accessible through tools | error console) and evaluate the following javascript code: components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime) .xpcomabi if either the cpu architecture or the c++ compiler are unknown, the application wouldn't have an xpcom abi string and attempts to get it will result in error ns_error_not_available. it would still be a distinct abi, but we just wouldn't have a name for it. note: pl...
XPCOM ownership guidelines
eeding it isn't, by itself, a valid reason for owning it. you don't own an object because you need it. in fact often you own it because it needs you. if you own it, it shouldn't own you. even transitively. or put another way: the ownership graph for any system should be acyclic. anytime there is a cycle of ownership, there is a situation that isn't automatically handled by destructors. special code must be provided and called to break the cycle before the participants can be individually released. you don't need to own it if it's lifetime is guaranteed to be longer than yours. as for instance, when it owns you. parents own their children (and not the reverse). though parents may not need to own their children. for instance, a tree may own all the nodes that are in it. all the nodes in t...
Clang static analysis
moved to https://firefox-source-docs.mozilla.org/code-quality/static-analysis.html ...
Cached compose window FAQ
s imported from mozilla.org and last updated in 2003. seth spitzer (sspitzer@mozilla.org) what is the "cached" compose window? instead of destroying the mail compose window on send (or close) just to create a new one the next time, mozilla mail will "cache" the compose window on send (or close), and use that instead. the downsides are that we have had some bugs, it complicates and bloats the code, and it requires more testing. the upside is that is has been a major performance win why did you do this? back 0.9.7, we hit a wall with the compose window. any new window performance problems that mozilla has are especially painful in mail compose, as we need to create a new compose window on every new mail message or reply. but we noticed that the common usage pattern is to compose, s...
Events
this reference will help you track those events down and learn how to use them. composition event name event type fired when... compose-send-message a message gets sent compose-window-close a compose window gets closed compose-window-init a compose window has been opened compose-window-reopen a cached compose window has been reopened. no load event is fired in this case. folders event name event type fired when... ...
LDAP Support
facsimiletelephonenumber pagernumber pager pagernumber pagerphone cellularnumber mobile cellularnumber cellphone cellularnumber carphone workaddress postofficebox workaddress streetaddress workcity l workcity locality workstate st workstate region workzipcode postalcode workzipcode zip workcountry countryname jobtitle title department ou department orgunit department department department departmentnumber company o company company workcountry countryname _aimscreenname nscpaimscreenname webpage1 workurl ...
MailNews fakeserver
op, imap, smtp, and nntp) designed for use in automated tests. it can also be used in manual qa tests. basic structure fakeserver is situated entirely under mailnews/test/fakeserver/. it is comprised of three major components: a daemon, a handler, and the server itself. the server itself is found in mailnews/test/fakeserver/maild.js and was largely based off of the httpd fakeserver from network code. it utilizes utf-8 as its transport mechanism and is capable of performing proper pipelining of commands. the other two components are specific to the protocol type and found under similar files in the same directory (e.g., smtpd.js). a daemon is information about the server that can be manipulated. an example of such a manipulation is adding a folder or adding messages. daemons should usually pe...
Mail and RDF
datasource notifies rdf content observers of the changes. content observers update ui. an aside: rational behind the design after reviewing this design, it might seem unnecessary to have the double-levels of notification/registration. why can't folders directly notify the rdf content observers when things change? here is the rational behind this design: it keeps all rdf datasource-related code in one place and out of the messages and folders themselves. this allows the mail code to be mostly free of rdf. the actual dependancies on rdf are small, so it makes sense to keep rdf out of folders and messages. there should be a non-rdf mechanism for folder change notification. there are times (for example, from javascript/xul) where we want folder notifications that have nothing to do with r...
Mail client architecture overview
/message hierarchy. it manages individual accounts on mail servers and the identity of users as used to send mail. folders - mail folders contain messages and folders. all folders have folder indexes. messages - messages are always stored and streamed in rfc822 format. whenever multiple messages are stored in one file, the berkeley mailbox format is used. datasources - datasources are the glue code that reflect mail data such as folders and messages into rdf. rdf will use the datasource to create user interfaces based on this data. datasources are also used to run commands that operate on this mail data. events - as data changes throughout the mail application, the event system notifies key components such as datasources and the url system of these changes. mail window management - each m...
Main Windows
nderbird.net for newer information. the base chrome directory of thunderbird can sometimes appear confusing when you're just beginning to look at it. as such, i've always thought it would be nice to have a list of what xul, js, or other files are that are here, what they do, and where they overlay at different points within the client. things appear confusing for several reasons: much of the code is written to be portable, so instead of duplicating it, its been put in overlays that are loaded over many different types of windows. some of the code was written based off of early firefox code, but is not exactly the same. you’ll sometimes see reimplementations of things that are already in toolkit, written specially for thunderbird. messenger.xul the base mail window that you see when ...
Spam filtering
default file). on spam detection, the user can choose to move spam to a special "junk" folder. the user can configure junk mail can be automatically purged from the "junk" folder. to analyze a message for spam, we need the entire message, not just the headers. spam detection happens after filters are run. white listing happens after filters, but before spam detection. the purge code is implemented as a search of the "junk" folder, looking for "old" message that have the proper junk status. when does purging happens? elaborate on the mime changes that were made for spam. currently, spam filtering is does not work for news, but it would be possible to add support for this. (there is a bug on it.). initial state user action table changes unkno...
Thunderbird Configuration Files
hide extensions for known file types option. now, go to your profile folder and select file > new > text document. the default name new text document.txt should be displayed. change the name to user.js (click yes on the file type warning that appears). linux users: use your own preferred method to create user.js in the profile folder. if you don't already have one, consider running the following code in a terminal. $ cd $profile # where $profile is your profile folder $ touch user.js # create the empty javascript file alternatively, open a files window (if you're on ubuntu. this will depend on which distribution you use), navigate to the profile folder, and right-click in some empty space on the right pane, then select new document > empty document. the default name untitled document sh...
Building a Thunderbird extension 2: extension file layout
uch of it may no longer be relevant. see developer.thunderbird.net for newer information. extensions are packaged and distributed in archive files (also known as bundles), with the xpi (pronounced “zippy”) file extension. at a minimum, they contain an install.rdf, the chrome.manifest and a chrome/ folder. a content/ folder sometimes contains the actual content files. these files contain the code that makes your extension actually do something. when this tutorial is finished, our extension will look like this: myfirstext.xpi: //created in step 8 /install.rdf //created in step 3 /chrome.manifest //created in step 4 /chrome/ /content/ /content/myhelloworl...
Building a Thunderbird extension 6: Adding JavaScript
warning: this content is for older versions of thunderbird. much of it may no longer be relevant. see developer.thunderbird.net for newer information. in this step we will create a small piece of javascript code that inserts the current date into our statusbar widget. the statusbar is usually displayed at the bottom of the thunderbird window. depending on the installed theme the result will look something like this: modify xul elements with javascript save the following javascript code into the content/ folder next to your myhelloworld.xul file and name it overlay.js. window.addeventlistener("load", function(e) { startup(); }, false); window.setinterval( function() { startup(); }, 60000); //update date every minute function startup() { var mypanel = document.getelementbyi...
Creating a Custom Column
. this function is a simple one liner along the lines of: function addcustomcolumnhandler() { gdbview.addcolumnhandler("colreplyto", columnhandler); } wrap up as you have seen it is quite easy to add your own custom column handler. most of the dirty tasks (displaying and sorting) are done for you in the background - so that all that's left to you, the extension developer is to populate the code with your feature. don't forget that columns aren't restricted to text - they can also load images (via getimagesrc()) so that your extension can display a new visual cue to the user. as you develop your custom extension, please revisit this article and add any helpful hints that you find along the way! caveats some weird behaviors have been witnessed, namely failing to be notified of the msg...
Styling the Folder Pane
since thunderbird 3, the folder pane is designed in a more modular and extensible fashion. it is now possible to place non-mail entities in the folder pane. treeview row/cell properties css property equivalent call explanation foldernamecol -- a property for indicating that a column is the folder name column. hasunreadmessages-true afolder.getnumunread(false) > 0 indicates that the folder (but not subfolders) has unread messages. ...
Using the Multiple Accounts API
need to pass it the server type as a string, from the list above. assign values to the various server properties as necessary. the most important properties here are the username and the hostname. create a fresh account with createaccount(); assign the server to the account with the incomingserver attribute. assign the identity to the account with the addidentity() method. some sample code: (where accountmanager is the account manager. var identity = accountmanager.createidentity(); identity.email="fred@myisp.com"; var server = accountmanager.createincomingserver("pop3"); server.username = "fred"; server.hostname = "pop.myisp.com"; var account = accountmanager.createaccount(); account.incomingserver = server; account.addidentity(identity); that's it! now you have a wor...
libmime content type handlers
andler plugin overview the libmime module implements a general-purpose mime parser and one of the primary methods provided by the parser is the ability to emit an html representation of an input stream. the primary use of libmime is to parse and render rfc822 messages for use by the messenger component of seamonkey. a necessary capability of this module is to dynamically add the ability to decode and render various content types. this functionality will be accomplished via content type handler plugins for libmime. libmime has a homegrown object system written in c, and since the content type handler plugins need to exist in this module, a description of the libmime object system should be reviewed and understood. api's content type handler plugins are dynamically loaded and need to acce...
Using C struct and pointers
...
Debugging Tips
let { ctypes } = components.utils.import("resource://gre/modules/ctypes.jsm", {}); let i = ctypes.int32_t(10); console.log(i); let point = ctypes.structtype("point", [{ x: ctypes.int32_t }, { y: ctypes.int32_t }]) let p = point(10, 20); console.log(p); let pp = p.address(); console.log(pp); the result will be as following: cdata { value: 10 } cdata { x: 10, y: 20 } cdata { contents: cdata } to see more descriptive information, you can use .tosource(). ...
Type conversion
onsole.log(mystruct.v.tostring()); // 'false' mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' mystruct.v = 0; console.log(mystruct.v.tostring()); // 'false' mystruct.v = 10; // throws error mystruct.v = "a"; // throws error integer types target type source converted value ctypes.char16_t js string (only if its length == 1) src.charcodeat(0) any integer types js number (only if fits to the size) src js boolean if src == true: 1 if src == false: 0 var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.char16_t } ])(); mystruct.v = 0x41; console.log(mystruct.v.tostring()); // "a" mystruct.v = true; console.log(mystruct.v.tostring()); // "\x01" mystruct.v = "x"; console.log(mys...
Library
ovided if the api is an exported data symbol rather than a function. return value a functiontype cdata object representing the declared api. exceptions thrown ctypes ctype functiontype abi typeerror the return type was specified as an array. alternative syntax another use for ctypes.declare is to get non-function/non-methods from libraries. the syntax for this is seen in firefox codebase here: //github.com/realityripple/uxp/blob/master/js/src/ctypes/library.cpp?offset=0#271 this shows that we can also supply only two arguments to the declare function. the first being the same as in the above example, name, which is the name of the symbol to export. and in place of the abi argument, we will pass in the type of this export. for example, from the objective-c library we can exp...
ctypes
t64 javascript objects; see 64-bit integers for details. type description size_t a platform-dependent size type. ssize_t a platform-dependent size type. intptr_t a platform-dependent integer representation of a pointer. uintptr_t a platform-dependent unsigned integer representation of a pointer. javascript characters 16-bit c unicode characters are handled by js-ctypes using the jschar type. type description jschar a 16-bit unsigned character. this is different from uint16_t in that c jschar values are automatically converted into 1-character javascript strings. these are unicode characters. special c types these types represent c types that have special meanings. type description...
js-ctypes
js-ctypes allows application and extension code to call back and forth to native code written in c. c++ support is possible through vtable pointers see using com from js-ctypes. for a discussion on extended c++ support see bug 505907. other work made possible by js-ctypes is jni, this is elaborated on in the jni.jsm section and not the js-ctypes section due to the jsm abstracting away all of the js-ctypes. unlike binary xpcom components, it allows developers to ship a single binary for use with multiple versions of firefox. note: js-ctypes is only available from chrome code; that is, ctypes is not available to websites, only application and extension code. documentation if you are brand new to js-ctypes, and have no idea about it, the pages you should read first is - ct...
Preferences System
that display and operate appropriately on various platforms (windows, macos x and gnome). the system is implemented through a few xul elements and attributes. reference information about them is available below: preferences system documentation: introduction: getting started | examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes use code for a typical preferences window may look like this: <prefwindow id="apppreferences" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <prefpane id="pane1" label="&pane1.title;"> <preferences> <preference id="pref1" name="pref.name" type="bool"/> </preferences> .. ui elements that refer to the preferences above, e.g.: <checkbox id="check1" ...
DOM Inspector internals - Firefox Developer Tools
he xul, css, or js. another convenient consequence of this is that if you use a properly set up development profile, then for the most part, the effects of development changes can be seen by simply switching away from the current viewer and back. knowing this about the way viewers are written, we should now be at a place where we can look at the way the dom inspector source is organized. ...
DOM Inspector - Firefox Developer Tools
...
Browser Toolbox - Firefox Developer Tools
the browser toolbox's context is the whole browser rather than just single page on a single tab. note: if you want to debug a specific add-on that is restartless or sdk-based then try the add-on debugger. use the browser toolbox for add-ons that are neither. enabling the browser toolbox the browser toolbox is not enabled by default. to enable it you need to check the settings "enable chrome and addon debugging" and "enable remote debugging". ...
Breaking on exceptions - Firefox Developer Tools
a tooltip describes the exception. starting in firefox 80, a disclosure triangle within the tooltip reveals a stack trace. ...
Debug eval sources - Firefox Developer Tools
in the video below, we load a page containing a source like this: var script = `function foo() { console.log('called foo'); } //# sourceurl=my-foo.js`; eval(script); var button = document.getelementbyid("foo"); button.addeventlistener("click", foo, false); the evaluated string is given the name "my-foo.js" using the //# sourceurl directive. this source is then listed in the source list pane, and can be opened and debugged like any other source. the name of the source will also appear in stack traces appearing in the web console. ...
Highlight and inspect DOM nodes - Firefox Developer Tools
hen you are working with dom notes in the debugger, you can easily highlight the node on the page or view it in the page inspector. a dom object in the watch expressions area, for example, includes a target. hover over the target to highlight the item on the page, click on the target to switch to the page inspector with the item highlighted. also, when you view the details of a dom node in the code panel, objects that you can highlight in the list will also have a target next to them. you can click any one of these targets to switch to the page inspector with this item highlighted. ...
Ignore a source - Firefox Developer Tools
in modern web development, we often rely on libraries like jquery, ember, or angular, and 99% of the time we can safely assume that they “just work”. we don’t care about the internal implementation of these libraries. however, a library’s abstraction leaks during debugging sessions when you are forced to step through its stack frames in order to reach your own code. however, you can tell the debugger to ignore the details of selected sources. you can enable or disable ignoring a source file in a couple of ways: in the source list pane, right-click the filename and choose ignore source (or unignore source). if the source file is displayed in the source pane, click the "eye" icon at the bottom. when a source file is ignored: any breakpoints it may have defined are disabled. ...
Pretty-print a minified file - Firefox Developer Tools
to prettify a minified file, click the pretty print source icon () at the bottom of the source pane. the debugger formats the source and displays it as a new file with a name like: "{ } [original-name]". after you click the icon, the source code looks like this: the pretty print source icon is available only if the source file is minified (i.e., not an original file), and is not already "prettified". note: if you want to prettify some inline javascript code, just double click the code in the inspector pane. ...
Search - Firefox Developer Tools
matching files as you type. you can use the up and down arrows to move through the list, and return to open the file you want: searching within a file to search for a particular substring in the file currently loaded into the source pane, press control + f (or command + f on a mac) while the source pane is focused. press return to search. the debugger will display the number of matches in the code and highlight each result: using the outline tab if you are searching for a specific function within the current javascript file, you can use the outline tab in the debugger to find it quickly. the outline tab lists the functions in the current file. the default sort order is by the order in the file but you can simplify the search by click on "sort by name" at the bottom of the tab. you c...
How to - Firefox Developer Tools
these articles describe how to use the debugger. access debugging in add-onsbreaking on exceptionsdebug eval sourcesdisable breakpointsexamine, modify, and watch variableshighlight and inspect dom nodesignore a sourceopen the debuggerpretty-print a minified filesearchset a breakpointset a conditional breakpointset watch expressionsstep through codeuse a source mapuse watchpoints ...
Basic operations - Firefox Developer Tools
amera icon (before firefox 47, this looked like a "+/-" icon): you'll be prompted to select the snapshot to use as a baseline, then the snapshot to compare. the tool then shows you the differences between the two snapshots: when you're looking at a comparison, you can't use the dominators view or the tree map view. recording call stacks the memory tool can tell you exactly where in your code you are allocating memory. however, recording this information has a run-time cost, so you must ask the tool to record memory calls before the memory is allocated, if you want to see memory call sites in the snapshot. to do this, check "record call stacks" (before firefox 49 this was labeled "record allocation stacks"): ...
Tree map view - Firefox Developer Tools
size of the rectangle corresponds to the proportion of the heap occupied by items in that category. this means you can quickly get an idea of roughly what sorts of things allocated by your site are using the most memory. within top-level categories: objects is further divided by the object's type. scripts is further subdivided by the script's origin. it also includes a separate rectangle for code that can't be correlated with a file, such as jit-optimized code. other is further subdivided by the object's type. here are some example snapshots, as they appear in the tree map view: this treemap is from the dom allocation example, which simply runs a script that creates a large number of dom nodes (200 htmldivelement objects and 4000 htmlspanelement objects). you can see how almost all ...
Sorting algorithms comparison - Firefox Developer Tools
you can also download the specific profile we discuss - just import it to the performance tool if you want to follow along. of course, you can generate your own profile, too, but the numbers will be a little different. ...
Cache Storage - Firefox Developer Tools
...
Style Editor - Firefox Developer Tools
ke changes to the other sheets. you can load a style sheet from disk and apply it to the page by clicking the import button. source map support web developers often create css files using a preprocessor like sass, less, or stylus. these tools generate css files from a richer and more expressive syntax. if you do this, being able to see and edit the generated css is not so useful, because the code you maintain is the preprocessor syntax, not the generated css. so you'd need to edit the generated css, then manually work out how to reapply that to the original source. source maps enable the tools to map back from the generated css to the original syntax, so they can display, and allow you to edit, files in the original syntax. from firefox 29 onwards, the style editor can understand css sou...
Validators - Firefox Developer Tools
firefox extensions for validation quick reference sidebar tabs install devedge toolbox sidebars for quick access to web development references. ...
View Source - Firefox Developer Tools
. view source features view source has three additional features, which can be accessed from the context menu in the view source tab: go to line scrolls to the specified line. if the number is higher than the lines in a file, you receive an error message. wrap long lines (toggle) wraps long lines to the width of the page. syntax highlighting (toggle) applies syntax highlighting to the code.when syntax highlighting is on, view source also highlights parsing errors in red. hovering your mouse over errors displays a tooltip explaining the error. this feature is useful when you're looking for html errors. to access go to line from the keyboard, press control + option + l on macos, or alt + shift + l on windows or linux. link to a line number it is possible to link to a particula...
Web Console Helpers - Firefox Developer Tools
mand line provided by the web console offers a few built-in helper functions that make certain tasks easier. $(selector, element) looks up a css selector string selector , returning the first node descended from element that matches. if unspecified, element defaults to document. equivalent to document.queryselector() or calls the $ function in the page, if it exists. see the queryselector code snippet. $$(selector, element) looks up a css selector string selector, returning an array of dom nodes descended from element that match. if unspecified, element defaults to document. this is like for document.queryselectorall(), but returns an array instead of a nodelist. $0 the currently-inspected element in the page. $_ stores the result of the last expression executed in the console'...
Web Console UI Tour - Firefox Developer Tools
th an indicator of the number of occurrences. enable autocompletion: when enabled, the javascript interpreter attempts to autocomplete while you type. instant evaluation: when enabled, the interpreter displays the evaluated results of an expression, when possible, before you press enter to submit it. message display pane this is where the messages appear, both those generated by the code in the page, and those generated by the commands entered on the command line. see console messages for a lot more detail on what the messages can contain. note: you can clear the contents of the console by entering the keyboard command ctrl + shift + l (windows, macos, and linux) or cmd + k on macos. command line the command line starts with double angle brackets (>>). use it to enter javas...
Web Console - Firefox Developer Tools
the javascript input interpreter how to interact with a document using the console. split console use the console alongside other tools. ...
Firefox Developer Tools
onnecting to other browsers connect the developer tools to chrome on android and safari on ios. debugging the browser by default, the developer tools are attached to a web page or web app. but you can also connect them to the browser as a whole. this is useful for browser and add-on development. browser console see messages logged by the browser itself and by add-ons, and run javascript code in the browser's scope. browser toolbox attach the developer tools to the browser itself. migrating from firebug firebug has come to the end of its lifespan (see firebug lives on in firefox devtools for details of why), and we appreciate that some people will find migrating to another less familiar set of devtools to be challenging. to ease a transition from firebug to the firefox developer...
AbsoluteOrientationSensor - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
AbsoluteOrientationSensor - Web APIs
the absoluteorientationsensor interface of the sensor apis describes the device's physical orientation in relation to the earth's reference coordinate system. to use this sensor, the user must grant permission to the 'accelerometer', 'gyroscope', and 'magnetometer' device sensors through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor absoluteorientationsensor.absoluteorientationsensor() creates a new absoluteorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event h...
AbstractWorker.onerror - Web APIs
the abstractworker.onerror property of the abstractworker interface represents an eventhandler, that is a function to be called when the error event occurs and bubbles through the worker. syntax myworker.onerror = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor and setting up of an onerror handler on the resulting object: var myworker = new worker('worker.js'); myworker.onerror = function() { console.log('there is an error with your worker!'); } specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification. living standard ...
Accelerometer.Accelerometer() - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
Accelerometer.x - Web APIs
Web › API › Accelerometer › x
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var xacceleration = accelerometer.x value a number. example acceleration is typically read in the sensor.onreading event callback. ...
Accelerometer.y - Web APIs
Web › API › Accelerometer › y
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var yacceleration = accelerometer.y value a number. example acceleration is typically read in the sensor.onreading event callback. ...
Accelerometer.z - Web APIs
Web › API › Accelerometer › z
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var zacceleration = accelerometer.z value a number. example acceleration is typically read in the sensor.onreading event callback. ...
Accelerometer - Web APIs
this is not something that would ever be shown to a user. ...
AmbientLightSensor.AmbientLightSensor() - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
AmbientLightSensor.illuminance - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation insfructions. syntax var level = ambientlightsensor.illuminance value a number indicating the current light level in lux. ...
AmbientLightSensor - Web APIs
this is not something that would ever be shown to a user. ...
AnalyserNode.fftSize - Web APIs
e indexsizeerror is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount ; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationfra...
AnalyserNode.frequencyBinCount - Web APIs
048, 4096, 8192, and 16384. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisua...
AnalyserNode.getByteFrequencyData() - Web APIs
lements are ignored. return value none. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefreq...
AnalyserNode.getByteTimeDomainData() - Web APIs
return value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). const audioctx = new (window.audiocontext || window.webkitaudiocontext)(); const analyser = audioctx.createanalyser(); ... analyser.fftsize = 2048; const bufferlength = analyser.fftsize; const dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw);...
AnalyserNode.getFloatFrequencyData() - Web APIs
ectrum the following example shows basic usage of an audiocontext to connect a mediaelementaudiosourcenode to an analysernode. while the audio is playing, we collect the frequency data repeatedly with requestanimationframe() and draw a "winamp bargraph style" to a <canvas> element. for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too). <!doctype html> <body> <script> const audioctx = new audiocontext(); //create audio source //here, we use an audio file, but this could also be e.g. microphone input const audioele = new audio(); audioele.src = 'my-audio.mp3';//insert file name here audioele.autoplay = true; audioele.preload = 'auto'; const audiosourcenode = audioctx.createmediaelementsource(audioele); //create analyser ...
AnalyserNode.getFloatTimeDomainData() - Web APIs
ements are ignored. return value none. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... analyser.fftsize = 1024; var bufferlength = analyser.fftsize; console.log(bufferlength); var dataarray = new float32array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getfloattimedom...
AnalyserNode.maxDecibels - Web APIs
eerror exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisua...
AnalyserNode.minDecibels - Web APIs
e_err exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisua...
AnalyserNode.smoothingTimeConstant - Web APIs
e_err exception is thrown. example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). if you are curious about the effect the smoothingtimeconstant() has, try cloning the above example and setting analyser.smoothingtimeconstant = 0; instead. you'll notice that the value changes are much more jarring. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; analyser...
AnalyserNode - Web APIs
audio visualizations. basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new(window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // get a canvas defined with id "oscilloscope" var canvas = document.getelementbyid("oscilloscope"); var canvas...
Animation.finished - Web APIs
nished playing. every time the animation leaves the finished play state (that is, when it starts playing again), a new promise is created for this property. the new promise will resolve once the new animation sequence has completed. syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. ...
AudioBuffer.getChannelData() - Web APIs
ts 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 buffer at the // sample rate of the audiocontext var framec...
AudioBufferSourceNode.buffer - Web APIs
y back audio using an audiobuffer as the source of the sound data. if the buffer property is set to the value null, the node generates a single channel containing silence (that is, every sample is 0). syntax audiobuffersourcenode.buffer = soundbuffer; value an audiobuffer which contains the data representing the sound which the node will play. example for a full working example, see this code running live, or view the source. var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneld...
AudioContext.close() - Web APIs
this function does not automatically release all audiocontext-created objects, unless other references have been released as well; however, it will forcibly release any system audio resources that might prevent additional audiocontexts from being created and used, suspend the progression of audio time in the audio context, and stop processing audio data. ...
AudioContext.createMediaStreamDestination() - Web APIs
mediarecorder.stop(); osc.stop(0); e.target.disabled = true; } }); mediarecorder.ondataavailable = function(evt) { // push each chunk (blobs) in an array chunks.push(evt.data); }; mediarecorder.onstop = function(evt) { // make blob out of our blobs, and open it. var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); document.queryselector("audio").src = url.createobjecturl(blob); }; </script> </body> </html> note: you can view this example live, or study the source code, on github. specifications specification status comment web audio apithe definition of 'createmediastreamdestination()' in that specification. working draft ...
AudioContext.getOutputTimestamp() - Web APIs
audiotimestamp object, which has the following properties. contexttime: a point in the time coordinate system of the currenttime for the baseaudiocontext; the time after the audio context was first created. performancetime: a point in the time coordinate system of a performance interface; the time after the document containing the audio context was first rendered examples in the following code we start to play an audio file after a play button is clicked, and start off a requestanimationframe loop running, which constantly outputs the contexttime and performancetime. you can see full code of this example at output-timestamp (see it live also). play.addeventlistener('click', () => { if(!audioctx) { audioctx = new window.audiocontext(); } getdata(); source.start(0); play...
AudioDestinationNode - Web APIs
long defining the maximum number of channels that the physical device can handle. methods no specific method; inherits methods from its parent, audionode. example there is no complex set up for using an audiodestinationnode — by default, this simply represents the output of the user's system (e.g. their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin. specifications specification status comment web audio apithe definition...
AudioListener.dopplerFactor - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.forwardX - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.forwardY - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.forwardZ - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.positionX - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.positionY - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.positionZ - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.setOrientation() - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.setPosition() - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.speedOfSound - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.upX - Web APIs
Web › API › AudioListener › upX
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.upY - Web APIs
Web › API › AudioListener › upY
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener.upZ - Web APIs
Web › API › AudioListener › upZ
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioListener - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
AudioNode - Web APIs
Web › API › AudioNode
es are "speakers" or "discrete". methods also implements methods from the interface eventtarget. audionode.connect() allows us to connect the output of this node to be input into another node, either as audio data or as the value of an audioparam. audionode.disconnect() allows us to disconnect the current node from another one it is already connected to. example this simple snippet of code shows the creation of some audio nodes, and how the audionode properties and methods can be used. you can find examples of such usage on any of the examples linked to on the web audio api landing page (for example violent theremin.) const audioctx = new audiocontext(); const oscillator = new oscillatornode(audioctx); const gainnode = new gainnode(audioctx); oscillator.connect(gainnode).connec...
AudioParam.exponentialRampToValueAtTime() - Web APIs
ram will ramp to by the given time. endtime a double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. returns a reference to this audioparam object. in some browsers older implementations of this interface return void. examples in this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) when these buttons are pressed, exponentialramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. this is pretty useful for fade in/fade out effects: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = docume...
AudioParam.linearRampToValueAtTime() - Web APIs
m will ramp to by the given time. endtime a double representing the exact time (in seconds) after the ramping starts that the changing of the value will stop. returns a reference to this audioparam object. in some browsers older implementations of this interface return void. example in this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) when these buttons are pressed, linearramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. this is pretty useful for fade in/fade out effects, although audioparam.exponentialramptovalueattime() is often said to be a bit more natural. // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var a...
AudioParam.setTargetAtTime() - Web APIs
// create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); /...
AudioParam.setValueAtTime() - Web APIs
ime (in seconds) after the audiocontext was first created that the change in value will happen. a typeerror is thrown if this value is negative. returns a reference to this audioparam object. in some browsers older implementations of this interface return void. examples this simple example features a media element source with two control buttons (see our webaudio-examples repo for the source code, or view the example live). when the buttons are pressed, the currgain variable is incremented/decremented by 0.25, then the setvalueattime() method is used to set the gain value equal to currgain, one second from now (audioctx.currenttime + 1.) // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables ...
AudioParam.setValueCurveAtTime() - Web APIs
hen the parameter's value finishes following the curve, its value is guaranteed to match the last value in the set of values specified in the values parameter. note: some early implementations of the web audio api did not ensure this to be the case, causing unexpected results. ...
AudioTrack - Web APIs
uman-readable label for the track. for example, an audio commentary track for a movie might have a label of "commentary with director john q. public and actors john doe and jane eod." this string is empty if no label is provided. language read only a domstring specifying the audio track's primary language, or an empty string if unknown. the language is specified as a bcp 47 (rfc 5646) language code, such as "en-us" or "pt-br". sourcebuffer read only the sourcebuffer that created the track. returns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source. usage notes to get an audiotrack for a given media element, use the element's audiotracks property, which returns an audiotracklis...
AudioWorklet - Web APIs
access the audio context's instance of audioworklet through the baseaudiocontext.audioworklet property. properties the audioworklet interface does not define any properties of its own, but does inherit properties of worklet. ...
AudioWorkletProcessor() - Web APIs
instead, they are created only internally by the creation of an associated audioworkletnodes. ...
AuthenticatorAssertionResponse.authenticatorData - Web APIs
s of the authenticator by looking up its metadata statement. credentialidlength (2 bytes) - the length of the credential id that immediately follows these bytes. credentialid (variable length) - a unique identifier for this credential so that it can be requested for future authentications. the credential is "credentialidlength" bytes long. credentialpublickey (variable length) - a cose encoded public key. this public key will be stored on the server associated with a user's account and be used for future authentications. extensions (variable length) - an optional cbor map of extensions. examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options })...
BaseAudioContext.createAnalyser() - Web APIs
ser(); returns an analysernode. example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationfram...
BaseAudioContext.createBiquadFilter() - Web APIs
rface creates a biquadfilternode, which represents a second order filter configurable as several different common filter types. syntax baseaudiocontext.createbiquadfilter(); returns a biquadfilternode. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source ...
BaseAudioContext.createBufferSource() - Web APIs
the createbuffersource() method of the baseaudiocontext interface is used to create a new audiobuffersourcenode, which can be used to play audio data contained within an audiobuffer object. audiobuffers 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('but...
BaseAudioContext.createChannelMerger() - Web APIs
the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
BaseAudioContext.createChannelSplitter() - Web APIs
e following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. ...
BaseAudioContext.createDelay() - Web APIs
ime optional the maximum amount of time, in seconds, that the audio signal can be delayed by. must be less than 180 seconds, and defaults to 1 second if not specified. returns a delaynode. the default delaynode.delaytime is 0 seconds. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... ...
BaseAudioContext.createDynamicsCompressor() - Web APIs
ll, a louder, richer, and fuller sound can be achieved. it is especially important in games and musical applications where large numbers of individual sounds are played simultaneously, where you want to control the overall signal level and help avoid clipping (distorting) of the audio output. syntax baseaudioctx.createdynamicscompressor(); returns a dynamicscompressornode. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicsco...
BaseAudioContext.createOscillator() - Web APIs
terface creates an oscillatornode, a source representing a periodic waveform. it basically generates a constant tone. syntax var oscillatornode = audioctx.createoscillator(); returns an oscillatornode. example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information. // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currenttime); // value in hertz oscillator.connect(audioctx.destination); oscillato...
BaseAudioContext.createPanner() - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
BaseAudioContext.createStereoPanner() - Web APIs
the createstereopanner() method of the baseaudiocontext interface creates a stereopannernode, which can be used to apply stereo panning to an audio source. it positions an incoming audio stream in a stereo image using a low-cost equal-power panning algorithm. syntax baseaudiocontext.createstereopanner(); returns a stereopannernode. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value. in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving ...
BaseAudioContext.createWaveShaper() - Web APIs
nterface creates a waveshapernode, which represents a non-linear distortion. it is used to apply distortion effects to your audio. syntax baseaudioctx.createwaveshaper(); returns a waveshapernode. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount...
BasicCardResponse.billingAddress - Web APIs
s successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr. dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'billingaddress' in that specification. working draft initial definition. browser compatibility the compatibility...
BasicCardResponse.cardNumber - Web APIs
s successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr. dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'cardnumber' in that specification. working draft initial definition. browser compatibility the compatibility tab...
BasicCardResponse.cardholderName - Web APIs
s successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr. dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'cardholdername' in that specification. working draft initial definition. browser compatibility the compatibility...
BasicCardResponse.expiryMonth - Web APIs
s successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr. dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'expirymonth' in that specification. working draft initial definition. browser compatibility the compatibility ta...
BasicCardResponse.expiryYear - Web APIs
s successfully, the paymentresponse object available inside the fulfilled promise (instrumentresponse above) will have a paymentresponse.details property that will contain response details. this has to conform to the structure defined by the basiccardresponse dictionary, and may look something like this: { "cardnumber' : '9999999999999999", "cardholdername' : 'mr. dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc. billing address is a paymentaddress object } } specifications specification status comment basic card paymentthe definition of 'expiryyear' in that specification. working draft initial definition. browser compatibility the compatibility tab...
BatteryManager - Web APIs
vent; this event is sent when the battery level is updated. methods inherited from eventtarget: eventtarget.addeventlistener() registers an event handler of a specific event type on the eventtarget. eventtarget.removeeventlistener() removes an event listener from the eventtarget. eventtarget.dispatchevent() dispatches an event to this eventtarget. additional methods in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties. see also webidl bindings. void seteventhandler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) specifications specification status comment battery status api candidate recommendation initial definitio...
BiquadFilterNode.Q - Web APIs
new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.q.value = 100; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source ...
BiquadFilterNode.detune - Web APIs
text(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.detune.value = 100; note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source ...
BiquadFilterNode.frequency - Web APIs
context(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.frequency.value = 3000; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source ...
BiquadFilterNode.gain - Web APIs
w audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.gain.value = 25; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source ...
BiquadFilterNode.type - Web APIs
ere the center of the phase transition occurs. controls how sharp the transition is at the medium frequency. the larger this parameter is, the sharper and larger the transition will be. not used example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source ...
BiquadFilterNode - Web APIs
dionode. biquadfilternode.getfrequencyresponse() from the current filter parameter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies. example the following example shows basic usage of an audiocontext to create a biquad filter node. for a complete working example, check out our voice-change-o-matic demo (look at the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source ...
Blob() - Web APIs
Web › API › Blob › Blob
the blob() constructor returns a new blob object. the content of the blob consists of the concatenation of the values given in the parameter array. syntax var newblob = new blob(array, options); parameters array an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the blob. usvstring objects are encoded as utf-8. options optional an optional object of type blobpropertybag which may specify any of the following properties: type optional the mime type of the data that will be stored into the blob. the default value is the empty string, (""). endings optional how to interpret newline characters (\n) within the contents, if the data is text. the default value, transparent, copies newline characters int...
BlobEvent.BlobEvent() - Web APIs
the blobevent() constructor returns a newly created blobevent object with an associated blob. syntax blobevent = new blobevent({data: aspecificblob}[, timecode]); arguments the blobevent() constructor also inherits arguments from event(). data is a blob associated with the event. timecode optional a domhighrestimestamp to be used in initializing the blob event. specifications specification status comment mediastream recordingthe definition of 'blobevent: blobevent' in that specification. working draft initial definition. ...
BlobEvent - Web APIs
Web › API › BlobEvent
re typically, but not necessarily, associated with media content. constructor blobevent() creates a blobevent event with the given parameters. properties inherits properties from its parent event. blobevent.data read only a blob representing the data associated with the event. the event was fired on the eventtarget because of something happening on that specific blob. blobevent.timecode read only a domhighrestimestamp indicating the difference between the timestamp of the first chunk in data and the timestamp of the first chunk in the first blobevent produced by this recorder. note that the timecode in the first produced blobevent does not need to be zero. methods no specific method; inherits methods from its parent event. specifications specification statu...
manufacturerData - Web APIs
syntax varmanufacturerdata = bluetoothadvertisingdata.manufacturerdata; ...
BluetoothAdvertisingData - Web APIs
is broadcasting, measured in dbm. this is used to compute the path loss as this.txpower - this.rssi. bluetoothadvertisingdata.rssi read only returns the power at which the device’s packets are being received, measured in dbm. this is used to compute the path loss as this.txpower - this.rssi. bluetoothadvertisingdata.manufacturerdata read only returns a map that relates company identifier codes to arraybuffers. bluetoothadvertisingdata.servicedata read only returns a map that relates uuids to arraybuffers. methods none. ...
Body.text() - Web APIs
Web › API › Body › text
syntax response.text().then(function (text) { // do something with the text response }); parameters none. return value a promise that resolves with a usvstring. ...
Body - Web APIs
Web › API › Body
nse stream and reads it to completion. it returns a promise that resolves with a formdata object. body.json() takes a response stream and reads it to completion. it returns a promise that resolves with the result of parsing the body text as json. body.text() takes a response stream and reads it to completion. it returns a promise that resolves with a usvstring (text). the response is always decoded using utf-8. examples the example below uses a simple fetch call to grab an image and display it in an <img> tag. you'll notice that since we are requesting an image, we need to run body.blob() (response implements body) to give the response its correct mime type. html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content const myimage = ...
BroadcastChannel: messageerror event - Web APIs
the messageerror event is fired on a broadcastchannel object when a message arrives on the channel that can't be deserialized. ...
Broadcast Channel API - Web APIs
nel'); sending a message it is enough to call the postmessage() method on the created broadcastchannel object, which takes any object as an argument. an example string message: // example of sending of a very simple message bc.postmessage('this is a test message.'); any kind of object can be sent, not just a domstring. the api doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with them. receiving a message when a message is posted, a message event is dispatched to each broadcastchannel object connected to this channel. a function can be run for this event with the onmessage event handler: // a handler that only logs the event to the console: bc.onmessage = function (ev) { console.log(ev); } disconnecting a ch...
CSSNumericValue.sub() - Web APIs
icvalue.sub(number); parameters number either a number or a cssmathsum. return value a cssmathsum exceptions typeerror indicates that an invalid type was passed to the method. examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification. working draft initial definition. ...
CSSNumericValue.sum() - Web APIs
ricvalue.sub(number); parameters number either a number or a cssmathsum return value a cssmathsum exceptions typeerror indicates that an invalid type was passed to the method. examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification. working draft initial definition. ...
CSSPrimitiveValue.getFloatValue() - Web APIs
the getfloatvalue() method of the cssprimitivevalue interface is used to get a float value in a specified unit. if this css value doesn't contain a float value or can't be converted into the specified unit, a domexception is raised. syntax var floatvalue = cssprimitivevalue.getfloatvalue(unit); parameters unittype an unsigned short representing the code for the unit type, in which the value should be returned. valid values are: constant description css_cm the value is a <length> in centimeters. css_deg the value is an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. css_exs the value is a <length> in ex units. ...
CSSPrimitiveValue.setFloatValue() - Web APIs
the setfloatvalue() method of the cssprimitivevalue interface is used to set a float value. if the property attached to this value can't accept the specified unit or the float value, the value will be unchanged and a domexception will be raised. syntax cssprimitivevalue.setfloatvalue(unittype, floatvalue); parameters unittype an unsigned short representing the code for the unit type, in which the value should be returned. valid values are: constant description css_cm the value is a <length> in centimeters. css_deg the value is an <angle> in degrees. css_dimension the value is a <number> with an unknown dimension. css_ems the value is a <length> in em units. css_exs the value is a <length> i...
CSSRule - Web APIs
Web › API › CSSRule
ese constants and the interfaces are: type value rule-specific interface comments and examples cssrule.style_rule 1 cssstylerule the most common kind of rule: selector { prop1: val1; prop2: val2; } cssrule.import_rule 3 cssimportrule an @import rule. ...
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
if the property name is a shorthand property. you should use cssstyledeclaration.getpropertyvalue() instead. syntax var value = style.getpropertycssvalue(property); parameters property is a domstring representing the property name to be retrieved. return value value is a cssvalue containing the css value for a property. if none exists, returns null. example the following javascript code gets an object containing the computed rgb values of the color css property: var style = window.getcomputedstyle(elem, null); var rgbobj = style.getpropertycssvalue('color').getrgbcolorvalue(); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssstyledeclaration' in that specification. obsolete...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
tring that provides all explicitly set priorities on the css property. syntax var priority = style.getpropertypriority(property); parameters property is a domstring representing the property name to be checked. return value priority is a domstring that represents the priority (e.g. "important") if one exists. if none exists, returns the empty string. example the following javascript code checks whether margin is marked as important in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var isimportant = declaration.getpropertypriority('margin') === 'important'; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertypriority()' in that specification. work...
CSSStyleDeclaration.getPropertyValue() - Web APIs
on.getpropertyvalue() method interface returns a domstring containing the value of a specified css property. syntax var value = style.getpropertyvalue(property); parameters property is a domstring representing the property name to be checked. return value value is a domstring containing the value of the property. if not set, returns the empty string. example the following javascript code queries the value of the margin property in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var value = declaration.getpropertyvalue('margin'); // "1px 2px" specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertyvalue()' in that specification. working draft ...
CSSStyleDeclaration.length - Web APIs
the number of style declarations in this css declaration block. syntax var num = styles.length; value an integer that provides the number of styles explictly set on the parent of the instance. example the following gets the number of explicitly set styles on the following html element: <div id="div1" style="margin: 0 10px; background-color: #ca1; font-family: monospace"></div> javascript code: var mydiv = document.getelementbyid('div1'); var divstyle = mydiv.style; var len = divstyle.length; // 6 specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.length' in that specification. working draft document object model (dom) level 2 style specificationthe definition of 'cssstyledeclaration'...
CSSStyleDeclaration.parentRule - Web APIs
the cssstyledeclaration.parentrule read-only property returns a cssrule that is the parent of this style block, e.g. a cssstylerule representing the style for a css selector. syntax var rule = styles.parentrule; value the css rule that contains this declaration block or null if this cssstyledeclaration is not attached to a cssrule. example the following javascript code gets the parent css style rule from a cssstyledeclaration: var declaration = document.stylesheets[0].rules[0].style; var rule = declaration.parentrule; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.parentrule' in that specification. working draft document object model (dom) level 2 style specificationthe definitio...
CSSStyleDeclaration.removeProperty() - Web APIs
eters property is a domstring representing the property name to be removed. note that multi-word property names are hyphenated and not camel-cased. return value oldvalue is a domstring equal to the value of the css property before it was removed. exceptions domexception no_modification_allowed_err: if the property or declaration block is read only. example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.removeproperty()' in that specification. working draft doc...
CSSStyleSheet.addRule() - Web APIs
returns -1. note that due to somewhat estoteric rules about where you can legally insert rules, it's possible that an exception may be thrown. see insertrule() for more information. usage notes this method is implemented by browsers by constructing a string using the template literal `${selector}{${styleblock}}`, then passing it into the standard insertrule() method. therefore, given existing code such as the following: cssstylesheet.addrule(selector, styles, 0); you can rewrite this to use the more standard insertrule() like this: cssstylesheet.insertrule(`${selector} {${styles}}`, 0); specifications specification status comment css object model (cssom)the definition of 'cssstylesheet.addrule()' in that specification. working draft ...
CSSStyleSheet.ownerRule - Web APIs
esheet into the document. if the stylesheet wasn't imported into the document using @import, the returned value is null. syntax var ownerrule = cssstylesheet.ownerrule; value a cssimportrule corresponding to the @import rule which imported the stylesheet into the document. if the stylesheet wasn't imported into the document using @import, the returned value is null. examples this snippet of code looks for rules which were not imported into the document using an @import at-rule. let rulelist = document.stylesheets[0].cssrules; for (let rule of rulelist) { if (!rule.ownerrule) { /* rule is not imported */ } } this snipped obtains a reference to the stylesheet associated with the @import and processes it in some manner: let rulelist = document.stylesheets[0].cssrules; for (let...
CSSStyleValue.parse() - Web APIs
rface sets a specific css property to the specified values and returns the first value as a cssstylevalue object. syntax cssstylevalue.parse(property, csstext) parameters property a css property to set. csstext a comma-separated string containing one or more values to apply to the provided property. return value a cssstylevalue object containing the first supplied value. example the code below parses a set of declarations for the transform property. the second code block shows the structure of the returned object as it would be rendered in a developer tools console. const css = cssstylevalue.parse( 'transform', 'translate3d(10px,10px,0) scale(0.5)'); csstransformvalue {0: csstranslate, 1: cssscale, length: 2, is2d: false} specifications specification status ...
CSSValue.cssValueType - Web APIs
possible values are: constant description css_custom the value is a custom value. css_inherit the value is inherited and the csstext contains "inherit". ...
CSSValue - Web APIs
Web › API › CSSValue
possible values are: constant description css_custom the value is a custom value. css_inherit the value is inherited and the csstext contains "inherit". ...
Managing screen orientation - Web APIs
layout based on the orientation one of the most common cases for orientation changes is when you want to revise the layout of your content based on the orientation of the device. for example, perhaps you want a button bar to stretch along the longest dimension of the device's display. by using a media query, you can do this easily and automatically. let's have an example with the following html code <ul id="toolbar"> <li>a</li> <li>b</li> <li>c</li> </ul> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. duis lacinia nisi nec sem viverra vitae fringilla nulla ultricies. in ac est dolor, quis tincidunt leo. cras commodo quam non tortor consectetur eget rutrum dolor ultricies. ut interdum tristique dapibus. nullam quis malesuada est.</p> css relies on the orientation media ...
Using dynamic styling information - Web APIs
initially defined in the dom level 2 style recommendation, these interfaces forms now a specification, css object model (cssom) which aims at superseding it. in many cases, and where possible, it really is best practice to dynamically manipulate classes via the classname property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. one's javascript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. however, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further detail ...
Using the CSS Typed Object Model - Web APIs
ike 20px, 40%, 200ms, or 7. it is returned with two properties: a value and a unit. with this type we can access the numeric value — cssunitvalue.value — and its unit — cssunitvalue.unit. let's write a plain paragraph, apply no styles, and inspect a few of its css properties by returning a table with the unit and value: <p> this is a paragraph with some content. open up this example in codepen or jsfiddle, and change some features. try adding some css, such as a width for this paragraph, or adding a css property to the ofinterst array. </p> <table id="regurgitation"> <thead> <tr> <th>property</th> <th>value</th> <th>unit</th> </tr> </table> for each property of interest, we list the name of the property, use .get(propertyname).value to return the v...
CSS Typed Object Model API - Web APIs
e reflected with actual js numbers, and have unit-aware mathematical operations defined for them). it is also generally faster, as values can be directly manipulated and then cheaply translated back into underlying values without having to both build and parse strings of css. css typed om both allows for the performant manipulation of values assigned to css properties while enabling maintainable code that is both more understand and easier to write. interfaces cssstylevalue the cssstylevalue interface of the the css typed object model api is the base class of all css values accessible through the typed om api. an instance of this class may be used anywhere a string is expected. cssstylevalue.parse(property, csstext) the parse() method of the cssstylevalue interface allows a cssnumer...
Cache.add() - Web APIs
Web › API › Cache › add
ndefined. exceptions exception happens when typeerror the url scheme is not http or https. the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then calls waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using cache.add to add an asset to it. this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add('/sw-test/index.html'); }) ); }); s...
Cache.addAll() - Web APIs
Web › API › Cache › addAll
ndefined. exceptions exception happens when typeerror the url scheme is not http or https. the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then runs waituntil() to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it. this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '...
Cache.match() - Web APIs
Web › API › Cache › match
will be cached. if our if() condition is false, then this fetch handler won't intercept the request. if there are any other fetch handlers registered, they will get a chance to call event.respondwith(). if no fetch handlers call event.respondwith(), the request will be handled by the browser as if there were no service worker involvement. if fetch() returns a valid http response with an response code in the 4xx or 5xx range, the catch() will not be called. self.addeventlistener('fetch', function(event) { // we only want to call event.respondwith() if this is a get request for an html document. if (event.request.method === 'get' && event.request.headers.get('accept').indexof('text/html') !== -1) { console.log('handling fetch event for', event.request.url); event.respondwith...
CacheStorage.delete() - Web APIs
he object is found, it resolves to false. you can access cachestorage through the 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.
CacheStorage.keys() - Web APIs
Web › API › CacheStorage › keys
rage object in the order they were created. use this method to iterate over a list 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 usin...
CanvasRenderingContext2D.clearRect() - Web APIs
), 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. positive values are to the right, and negative to the left. height the rectangle's height. positive values are down, and negative are up. examples erasing the whole canvas this code snippet erases the entire canvas. this is commonly required at the start of each frame in an animation. the dimensions of the cleared area are set to equal the <canvas> element's width and height attributes. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.clearrect(0, 0, canvas.width, canvas.height); erasing part of a canvas this example draws a blue ...
CanvasRenderingContext2D.fillRect() - Web APIs
s example draws a filled green rectangle using the fillrect() method. html <canvas id="canvas"></canvas> javascript the rectangle's top-left corner is at (20, 10). it has a width of 150 and a height of 100. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(20, 10, 150, 100); result filling the whole canvas this code snippet fills the entire canvas with a rectangle. this is often useful for creating a background, on top of which other things may then be drawn. to achieve this, the dimensions of the rectangle are set to equal the <canvas> element's width and height attributes. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillrect(0, 0, canvas.width, canvas.height)...
CanvasRenderingContext2D.measureText() - Web APIs
enderingcontext2d.measuretext() method returns a textmetrics object that contains information about the measured text (such as its width, for example). syntax ctx.measuretext(text); parameters text the text string to measure. return value a textmetrics object. example given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('hello world'); console.log(text.width); // 56; specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.measuretext' in that specification. living standard ...
CanvasRenderingContext2D.stroke() - Web APIs
; ctx.rect(10, 10, 150, 100); ctx.stroke(); result re-stroking paths typically, you'll want to call beginpath() for each new thing you want to stroke. if you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. in some cases, however, this may be the desired effect. html <canvas id="canvas"></canvas> javascript this code strokes the first path three times, the second path two times, and the third path only once. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first sub-path ctx.linewidth = 26; ctx.strokestyle = 'orange'; ctx.moveto(20, 20); ctx.lineto(160, 20); ctx.stroke(); // second sub-path ctx.linewidth = 14; ctx.strokestyle = 'green'; ctx.moveto(20, 80); ctx.linet...
CanvasRenderingContext2D - Web APIs
instance, you must first have an html <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> to get the canvas' 2d rendering context, call getcontext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getelementbyid('my-house'); const ctx = canvas.getcontext('2d'); with the context in hand, you can draw anything you like. ...
Advanced animations - Web APIs
« previousnext » in the last chapter we made some basic animations and got to know ways to get things moving. in this part we will have a closer look at the motion itself and are going to add some physics to make our animations more advanced. drawing a ball we are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. the following code will set us up. <canvas id="canvas" width="600" height="300"></canvas> as usual, we need a drawing context first. to draw the ball, we will create a ball object which contains properties and a draw() method to paint it on the canvas. var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function(...
Basic usage of canvas - Web APIs
epresenting the <canvas> element by calling the document.getelementbyid() method. once you have the element node, you can access the drawing context using its getcontext() method. checking for support the fallback content is displayed in browsers which do not support <canvas>. scripts can also check for support programmatically by simply testing for the presence of the getcontext() method. our code snippet from above becomes something like this: var canvas = document.getelementbyid('tutorial'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); // drawing code here } else { // canvas-unsupported code here } a skeleton template here is a minimalistic template, which we'll be using as a starting point for later examples. note: it is not good practice to embed a script ...
Hit regions and accessibility - Web APIs
on({id: 'circle'}); canvas.addeventlistener('mousemove', function(event) { if (event.region) { alert('hit region: ' + event.region); } }); </script> the addhitregion() method also takes a control option to route events to an element (that is a descendant of the canvas): ctx.addhitregion({control: element}); this can be useful for routing to <input> elements, for example. see also this codepen demo. focus rings when working with the keyboard, focus rings are a handy indicator to help navigating on a page. to draw focus rings on a canvas drawing, the drawfocusifneeded property can be used. canvasrenderingcontext2d.drawfocusifneeded() if a given element is focused, this method draws a focus ring around the current path. additionally, the scrollpathintoview() method can be us...
Pixel manipulation with canvas - Web APIs
...
Transformations - Web APIs
imilar to what we've done in previous sections. however once we call the first restore() statement, the top drawing state is removed from the stack, and settings are restored. if we hadn't saved the state using save(), we would need to change the fill color and transparency manually in order to return to the previous state. this would be easy for two properties, but if we have more than that, our code would become very long, very fast. when the second restore() statement is called, the original state (the one we set up before the first call to save) is restored and the last rectangle is once again drawn in black. screenshotlive sample translating the first of the transformation methods we'll look at is translate(). this method is used to move the canvas and its origin to a different point ...
Canvas tutorial - Web APIs
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 javascript. the <canvas> element is not supported in some older brow...
ChannelMergerNode - Web APIs
the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify both the index of the channel to connect from and the index of the channel to connect to. ...
ChannelSplitterNode - Web APIs
e following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently. to use them, you need to use the second and third parameters of the audionode.connect(audionode) method, which allow you to specify the index of the channel to connect from and the index of the channel to connect to. ...
ChildNode.after() - Web APIs
Web › API › ChildNode › after
r(span, "text"); console.log(parent.outerhtml); // "<div><p></p><span></span>text</div>" childnode.after() is unscopable the after() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ChildNode.before() - Web APIs
Web › API › ChildNode › before
n, "text"); console.log(parent.outerhtml); // "<div><span></span>text<p></p></div>" childnode.before() is unscopable the before() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ChildNode.remove() - Web APIs
Web › API › ChildNode › remove
document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ChildNode.replaceWith() - Web APIs
ole.log(parent.outerhtml); // "<div><span></span></div>" childnode.replacewith() is unscopable the replacewith() method is not scoped into the with statement. see symbol.unscopables for more information. ...
Clipboard.write() - Web APIs
Web › API › Clipboard › write
the promise is rejected if the clipboard is unable to complete the clipboard access. example this example function replaces the current contents of the clipboard with a specified string. function setclipboard(text) { let data = [new clipboarditem({ "text/plain": text })]; navigator.clipboard.write(data).then(function() { /* success */ }, function() { /* failure */ }); } the code begins by creating a new clipboarditem object into which the text will be placed for sending to the clipboard. the key of the object passed to the clipboarditem constructor indicates the content type, the value indicates the content. the content could be a text or even a blob (e.g. for copying images to the clipboard). then write() is called, specifying both a fulfilment function and an error fun...
Clipboard API - Web APIs
u access the system clipboard through the navigator.clipboard global: navigator.clipboard.readtext().then( cliptext => document.queryselector(".editor").innertext += cliptext); this snippet fetches the text from the clipboard and appends it to the first element found with the class editor. since readtext() (and read(), for that matter) returns an empty string if the clipboard isn't text, this code is safe. interfaces clipboard secure context provides an interface for reading and writing text and data to or from the system clipboard. the specification refers to this as the 'async clipboard api.' clipboardevent secure context represents events providing information related to modification of the clipboard, that is cut, copy, and paste events. the specification refers to this as the 'c...
CloseEvent() - Web APIs
oseevent() constructor creates a new closeevent. syntax var event = new closeevent(typearg, closeeventinit); values typearg is a domstring representing the name of the event. closeeventinit optional is a closeeventinit dictionary, having the following fields: "wasclean", optional and defaulting to false, of type long, indicates if the connection has been closed cleanly or not. "code", optional and defaulting to 0, of type unsigned short, that is the connection close code sent by the server. "reason", optional and defaulting to '', of type domstring, that is a human-readable reason why the server closed the connection. the closeeventinit dictionary also accepts fields from the eventinit dictionary. specifications specification status comment ...
console.assert() - Web APIs
Web › API › Console › assert
ascript objects to output. the string representations of each of these objects are appended together in the order listed and output. msg a javascript string containing zero or more substitution strings. subst1 ... substn javascript objects with which to replace substitution strings within msg. this parameter gives you additional control over the format of the output. ...
console.count() - Web APIs
Web › API › Console › count
hod logs the number of times that this particular call to count() has been called. note: this feature is available in web workers. syntax console.count([label]); parameters label optional a string. if supplied, count() outputs the number of times it has been called with that label. if omitted, count() behaves as though it was called with the "default" label. examples for example, given code like this: let user = ""; function greet() { console.count(); return "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" the label is displayed as default because no explicit label was supplied. if we pass the user variable as the label argument to the...
Console.countReset() - Web APIs
the console.countreset() method resets counter used with console.count(). note: this feature is available in web workers. syntax console.countreset([label]); parameters label optional a string. if supplied, countreset() resets the count for that label to 0. if omitted, countreset() resets the default counter to 0. examples for example, given code like this: let user = ""; function greet() { console.count(); return "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console.countreset(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" note that the call to console.counterreset() resets the value of the default counter to zero. if we pass the user variable as the label ar...
Console.group() - Web APIs
Web › API › Console › group
k, call console.group(). the console.groupcollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it. note: from gecko 9 until gecko 51, the groupcollapsed() method was the same as group(). collapsed groups are fully supported starting in gecko 52. see bug 1088360. to exit the current group, call console.groupend(). for example, given this code: console.log("this is the outer level"); console.group(); console.log("level 2"); console.group(); console.log("level 3"); console.warn("more of level 3"); console.groupend(); console.log("back to level 2"); console.groupend(); console.log("back to the outer level"); the output looks like this: see using groups in the console in the documentation of console for more details. specifications...
Console.timeStamp() - Web APIs
Web › API › Console › timeStamp
you can optionally supply an argument to label the timestamp, and this label will then be shown alongside the marker. ...
Console API - Web APIs
concepts and usage the console api started as a largely proprietary api, with different browsers implementing it, albeit it in inconsistent ways. the console api spec was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior — although some implementations still have their own additional proprietary functions. ...
ConvolverNode.buffer - Web APIs
udiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ... convolver.buffer = concerthallbuffer; specifications specification status comment web audio apithe definition...
ConvolverNode.normalize - Web APIs
udiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ... convolver.normalize = false; // must be set before the buffer, to take effect convolver.buffer = concerthallbuffer; specifications ...
CustomElementRegistry - Web APIs
tom element is not defined. customelementregistry.upgrade() upgrades a custom element directly, even before it is connected to its shadow root. customelementregistry.whendefined() returns an empty promise that resolves when a custom element becomes defined with the given name. if such a custom element is already defined, the returned promise is immediately fulfilled. examples the following code is taken from our word-count-web-component example (see it live also). note how we use the customelementregistry.define() method to define the custom element after creating its class. // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var ...
DOMHighResTimeStamp - Web APIs
was created. in all other cases, the time origin is undefined. methods this type has no methods. usage notes you can get the current timestamp value—the time that has elapsed since the context was created—by calling the performance method now(). this method is available in both window and worker contexts. example to determine how much time has elapsed since a particular point in your code, you can do something like this: let starttime = performance.now(); /* ... do things for a while ... */ let elapsedtime = performance.now() - starttime; upon completion, the value of elapsedtime is the number of milliseconds that have elapsed since you recorded the starting time in line 1. specifications specification status comment high resolution time level 2t...
DOMImplementation.createHTMLDocument() - Web APIs
line 4 uses createhtmldocument() to construct a new html document whose <title> is "new document". lines 5 and 6 create a new paragraph element with some simple content, and then lines 8–12 handle inserting the new paragraph into the new document. line 16 pulls the contentdocument of the frame; this is th...
DOMParser - Web APIs
Web › API › DOMParser
note: xmlhttprequest can parse xml and html directly from a url-addressable resource, returning a document in its response property. you can perform the opposite operation—converting a dom tree into xml or html source—using the xmlserializer interface. in the case of an html document, you can also replace portions of the dom with new dom trees built from html by setting the value of the element.innerhtml and outerhtml properties. these properties can also be read to fetch html fragments corresponding to the corresponding dom subtree. ...
DOMPointInit - Web APIs
ive values are closer to the user and negative values retreat back into the screen. the default value is 0. dompointinit.w the point's w perspective value, given as an unrestricted floating-point number. the default is 1. example this example creates a new dompoint representing the top-left corner of the current window, with a z component added to move the point closer to the user. this same code will work to create a dompointreadonly object; just change the interface name in the code. const pointdesc = { x: window.screenx, y: window.screeny, z: 5.0 }; const windtopleft = dompoint.frompoint(pointdesc) specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly.frompoint()' in that specification. ...
DOMPointReadOnly.x - Web APIs
in general, positive values x mean to the right, and negative values of x means to the left, assuming no transforms have resulted in a reversal. syntax const xpos = somedompointreadonly.x; value a double-precision floating-point value indicating the x coordinate's value for the point. this value is unrestricted, meaning that it is allowed to be infinite or invalid (that is, its value may be nan or ±infinity). ...
DOMRect.DOMRect() - Web APIs
Web › API › DOMRect › DOMRect
the domrect() constructor creates a new domrect object. syntax var mydomrect = new domrect(x, y, width, height); parameters x the x coordinate of the domrect's origin. y the y coordinate of the domrect's origin. width the width of the domrect. height the height of the domrect. examples to create a new domrect, you could run a line of code like so: mydomrect = new domrect(0,0,100,100); // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrect()' in that specification. candidate recommendation initial definition. ...
DOMRectReadOnly() - Web APIs
y() constructor creates a new domrectreadonly object. syntax const mydomrectreadonly = new domrectreadonly(x, y, width, height) parameters x the x coordinate of the domrectreadonly's origin. y the y coordinate of the domrectreadonly's origin. width the width of the domrectreadonly. height the height of the domrectreadonly. examples to create a new dompoint, you could run a line of code like so: const mydomrect = new domrectreadonly(0, 0, 100, 100) // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly()' in that specification. candidate rec...
DOMTokenList.replace() - Web APIs
the javascript: let span = document.queryselector("span"); let classes = span.classlist; let result = classes.replace("c", "z"); console.log(result); if (result) { span.textcontent = classes; } else { span.textcontent = 'token not replaced successfully'; } the output looks like this: polyfill the following polyfill will add the replace method to the domtokenlist class. the following code will only work with ie10-11. to use with earlier versions of ie, refer to the polyfill at element.classlist#polyfill domtokenlist.prototype.replace = function (a, b) { if (this.contains(a)) { this.add(b); this.remove(a); return true; } return false; } specifications specification status comment domthe definition of 'replace()' in ...
DOMTokenList.supports() - Web APIs
ociated attribute's supported tokens. this method is intended to support feature detection. syntax let trueorfalse = element.supports(token) parameters token a domstring containing the token to query for. returns a boolean indicating whether the token was found. example let iframe = document.getelementbyid('display'); if (iframe.sandbox.supports('an-upcoming-feature')) { // support code for mystery future feature } else { // fallback code } if (iframe.sandbox.supports('allow-scripts')) { // instruct frame to run javascript // // (note: this feature is well-supported; this is just an example!) // } specifications specification status comment credential management level 1 working draft initial definition. ...
DataTransfer.effectAllowed - Web APIs
he target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples <code>datatransfer</code>.{<code>dropeffect</code>, <code>effectallowed</code>} properties</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.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> <...
DataTransfer.setData() - Web APIs
) { 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.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> ...
DataTransfer.setDragImage() - Web APIs
ple.gif'; ev.datatransfer.setdragimage(img, 10, 10); } 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)); } </script> <body> <h1>example of <code>datatransfer.setdragimage()</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.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification ...
DataTransferItem.getAsString() - Web APIs
kind is string). syntax datatransferitem.getasstring(callback); parameters callback a callback function that has access to the data transfer item's string data. see callback below for details. return value undefined callback the callback parameter is a callback function which accepts one parameter: domstring the drag data item's string data. the callback return value is undefined. ...
DataTransferItem.kind - Web APIs
the read-only datatransferitem.kind property returns a datatransferitem representing the drag data item kind: some text or some file. syntax var itemkind = datatransferitem.kind; return value a domstring representing the drag data item's kind. it must be one of the following values: 'file' if the drag data item is a file. 'string' if the kind of drag data item is a plain unicode string. example this example shows the use of the kind property. function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild...
DataTransferItem.type - Web APIs
some example types are: text/plain and text/html. syntax dataitem.type; return value a domstring representing the drag data item's type. example this example shows the use of the type property. ...
DataTransferItem.webkitGetAsEntry() - Web APIs
if the item described by the datatransferitem is a file, webkitgetasentry() returns a filesystemfileentry or filesystemdirectoryentry representing it. if the item isn't a file, null is returned. this function is implemented as webkitgetasentry() in non-webkit browsers including firefox at this time; it may be renamed to simply getasentry() in the future, so you should code defensively, looking for both. syntax datatransferitem.webkitgetasentry(); parameters none. return value a filesystementry-based object describing the dropped item. this will be either filesystemfileentry or filesystemdirectoryentry. example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listin...
DataTransferItemList.add() - Web APIs
/plain. file a file object. no type needs to be given in this case. return value a datatransferitem containing the specified data. if the drag item couldn't be created (for example, if the associated datatransfer object has no data store), null is returned. exceptions notsupportederror a string data parameter was provided, and the list already contains an item whose kind is "plain unicode string" and whose type is equal to the specified type parameter. example this example shows the use of the add() 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(even...
DataTransferItemList.remove() - Web APIs
over_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_handler(event);">drop zone</div> css ...
DedicatedWorkerGlobalScope: message event - Web APIs
the message event is fired on a dedicatedworkerglobalscope object when the worker receives a message from its parent (i.e. when the parent sends a message using worker.postmessage()). ...
DedicatedWorkerGlobalScope.onmessage - Web APIs
the onmessage property of the dedicatedworkerglobalscope interface represents an eventhandler to be called when the message event occurs and bubbles through the worker — i.e. when a message is sent to the worker using the worker.postmessage method. syntax self.onmessage = function() { ... }; example the following code snippet shows creation of a worker object using the worker() constructor. messages are passed to the worker when the value inside the form input first changes. a worker.onmessage handler is also present, to deal with messages are passed back from the worker. var myworker = new worker("worker.js"); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } myworker.onmessage = function(e) { result.text...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
includes cyclical references. transferlist optional an optional array of transferable objects to transfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and it becomes available only to the main thread it was sent to. only messageport and arraybuffer objects can be transferred. returns void. example the following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script. inside the handler a calculation is done from which a result message is created; this is then sent back to the main thread using postmessage(workerresult); onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); ...
DelayNode.delayTime - Web APIs
created it. syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not. value an audioparam. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... ...
DelayNode - Web APIs
Web › API › DelayNode
roperties from its parent, audionode. delaynode.delaytime read only is an a-rate audioparam representing the amount of delay to apply, specified in seconds. methods no specific methods; inherits methods from its parent, audionode. example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code). if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ... ...
Using light sensors - Web APIs
on the device if (event.value < 100) { alert('hey, you! you are working in a dark environment'); bodybg.backgroundcolor="lightgrey"; } else { bodybg.backgroundcolor="#fff"; } }); this example shows how the api can actually be used in the wild. if your app contains a lot of white in the ui, it is usually beneficial to the user to change the ui to a darker color in a darker environment. the code alerts the user that they are working in a dark environment and then changes the page's background to a darker color. specifications specification status comment ambient light sensorthe definition of 'ambient light events' in that specification. candidate recommendation initial specification ...
Document: animationcancel event - Web APIs
cancelable no interface animationevent event handler property onanimationcancel the original target for this event is the element that had the animation applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: animationcancel. examples this code adds a listener to the animationcancel event. document.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); the same, but using the onanimationcancel property instead of addeventlistener(): document.onanimationcancel = () => { console.log('animation canceled'); }; see a live example of this event. specifications specification status comment ...
Document: animationiteration event - Web APIs
able no interface animationevent event handler property onanimationiteration the original target for this event is the element that had the animation applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: animationiteration. ...
Document.createEntityReference() - Web APIs
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. prior to gecko 7.0 this method showed up as present, due to bug bug 9850, it always only returned null. the only workaround is to create a text node, cdata section, attribute node value, etc. which has the value referred to by the entity, using unicode escape sequences or fromcharcode() as necessary. specifications createentityreference ...
Document.createTouch() - Web APIs
y the value for touch.clienty. radiusx the value for touch.radiusx. radiusy the value for touch.radiusy. rotationangle the value for touch.rotationangle. force the value for touch.force. return value touch a touch object configured as described by the input parameters. example this example illustrates using the document.createtouch() method to create touch objects. in following code snippet, two touch objects are created for the target element. var target = document.getelementbyid("target"); var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50); specifications specification status comment touch eventsthe definition of 'document.createtouch()' in that specific...
Document.createTouchList() - Web APIs
= documenttouch.createtouchlist([touch1 [, touch2 [, ...]]]); parameters touches zero or more touch objects. note: firefox also accepts an array of touch objects. return value list a touchlist object containing the touch objects specified by the touches parameter. example this example illustrates using the document.createtouchlist() method to create touchlist objects. in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects. var target = document.getelementbyid("target"); // create some touch points var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50); // create an empty touchlist objects var list0...
Document.currentScript - Web APIs
the document.currentscript property returns the <script> element whose script is currently being processed and isn't a javascript module. (for modules use import.meta instead.) it's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed. syntax var curscriptelement = document.currentscript; example this example checks to see if the script is being executed asynchronously: if (document.currentscript.async) { console.log("executing asynchronously"); } else { console.log("executing synchronously"); } view live examples specifications specification status comment html living standardthe definition o...
Document: drag event - Web APIs
the drag event is fired every few hundred milliseconds as an element or text selection is being dragged by the user. bubbles yes cancelable yes default action continue the drag & drop operation. interface dragevent event handler property ondrag examples see this code in a jsfiddle demo or interact with it below. html <div class="dropzone"> <div id="draggable" draggable="true" ondragstart="event.datatransfer.setdata('text/plain',null)"> this div is draggable </div> </div> <div class="dropzone"></div> <div class="dropzone"></div> <div class="dropzone"></div> css #draggable { width: 200px; height: 20px; text-align: center; background: white; } .dropzone { width: 200px; height: 20px; background: bluev...
Document: dragend event - Web APIs
the dragend event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key). bubbles yes cancelable no default action varies interface dragevent event handler property ondragend examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'dragend' in that specification. living standard ...
Document: dragenter event - Web APIs
arget object is the immediate user selection (the element directly indicated by the user as the drop target), or the <body> element. bubbles yes cancelable yes default action reject immediate user selection as potential target element. interface dragevent event handler property ondragenter examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'dragenter' in that specification. living standard ...
Document: dragexit event - Web APIs
the dragexit event is fired when an element is no longer the drag operation's immediate selection target. bubbles yes cancelable no default action none. interface dragevent event handler property ondragexit examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'dragexit' in that specification. living standard ...
Document: dragleave event - Web APIs
the dragleave event is fired when a dragged element or text selection leaves a valid drop target. bubbles yes cancelable no default action none. interface dragevent event handler property ondragleave examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'dragleave' in that specification. living standard ...
Document: dragover event - Web APIs
en an element or text selection is being dragged over a valid drop target (every few hundred milliseconds). the event is fired on the drop target(s). bubbles yes cancelable yes default action reset the current drag operation to "none". interface dragevent event handler property ondragover examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'dragover' in that specification. living standard ...
Document: dragstart event - Web APIs
the dragstart event is fired when the user starts dragging an element or text selection. bubbles yes cancelable yes default action initiate the drag-and-drop operation. interface dragevent event handler property ondragstart examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'dragstart' in that specification. living standard ...
Document: drop event - Web APIs
the drop event is fired when an element or text selection is dropped on a valid drop target. bubbles yes cancelable yes default action varies interface dragevent event handler property ondrop examples see the drag event for example code or this jsfiddle demo. specifications specification status comment html living standardthe definition of 'drop event' in that specification. living standard ...
Document.evaluate() - Web APIs
Web › API › Document › evaluate
full support 4.2samsung internet android full support 1.0legend full support full support no support no support see also document.createexpression() xpathresult xpath code snippets check for browser support ...
Document.execCommand() - Web APIs
a boolean true/false as a value argument. note: this argument is logically backwards (i.e. use false to use css, true to use html) and unsupported by internet explorer. this has been deprecated in favor of stylewithcss. stylewithcss replaces the usecss command. true modifies/generates style attributes in markup, false generates presentational elements. example an example of how to use it on codepen. specifications specification status comment execcommand unofficial draft ...
Document.getAnimations() - Web APIs
hose target elements are descendants of the document. this array includes css animations, css transitions, and web animations. syntax var allanimations = document.getanimations(); parameters none. return value an array of animation objects, each representing one animation currently associated with elements which are descendants of the document on which it's called. examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate. document.getanimations().foreach( function (animation) { animation.playbackrate *= .5; } ); specifications specification status comment web animationsthe definition of 'document.getanimations()' in that specification. working draft ...
Document.getElementById() - Web APIs
unlike some other element-lookup methods such as document.queryselector() and document.queryselectorall(), getelementbyid() is only available as a method of the global document object, and not available as a method on all element objects in the dom. because id values must be unique throughout the entire do...
Document.mozSetImageElement() - Web APIs
ackground. var c = 0x00; function clicked() { var canvas = document.createelement("canvas"); canvas.setattribute("width", 100); canvas.setattribute("height", 100); var ctx = canvas.getcontext('2d'); ctx.fillstyle = "#" + c.tostring(16) + "0000"; ctx.fillrect(25, 25, 75, 75); c += 0x11; if (c > 0xff) { c = 0x00; } document.mozsetimageelement("canvasbg", canvas); } the code here is called each time the user clicks the <div> element. it creates a new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square. each time the function is called, the square is a different color (its red component is increased each time), so each time the user clicks the element, the background is filled with a brighter and brighter pattern of red til...
Document.onbeforescriptexecute - Web APIs
does not fire if the element is added dynamically, eg with appendchild(). syntax document.onbeforescriptexecute = funcref; funcref is a function reference, called when the event is fired. the event's target attribute is set to the script element that is about to be executed. ...
Document.open() - Web APIs
Web › API › Document › open
ent.open() method opens a document for writing. this does come with some side effects. for example: all event listeners currently registered on the document, nodes inside the document, or the document's window are removed. all existing nodes are removed from the document. syntax document.open(); parameters none. return value a document object instance. examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again. document.open(); document.write("<p>hello world!</p>"); document.write("<p>i am a fish</p>"); document.write("<p>the number is 42</p>"); document.close(); notes an automatic document.open() call happens when document.write() is called after the page has loaded. for years firefox an...
Document.requestStorageAccess() - Web APIs
erence to 1. syntax var promise = document.requeststorageaccess(); parameters none. return value a promise that fulfills with undefined if the access to first-party storage was granted, and rejects if access was denied. when the promise gets resolved, the resolve handler will run as if a user gesture is being processed, whether the promise was fulfilled or rejected: in the former case, code can then start to call apis that require user activation and things can move forward. in the latter case, code can run to inform the user of why the request failed and what they can do to continue (for example asking them to log in, if that is a requirement). examples document.requeststorageaccess().then( () => { console.log('access granted') }, () => { console.log('access denied') } ); ...
Document.styleSheetSets - Web APIs
the stylesheetsets read-only property returns a live list of all of the currently-available style sheet sets. syntax var sets = document.stylesheetsets; on return, sets is a list of style sheet sets that are available. ...
Document: touchcancel event - Web APIs
the touchcancel event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created). bubbles yes cancelable no interface touchevent event handler property ontouchcancel examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
Document: touchend event - Web APIs
the touchend event fires when one or more touch points are removed from the touch surface. bubbles yes cancelable yes interface touchevent event handler property ontouchend examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
Document: touchmove event - Web APIs
the touchmove event is fired when one or more touch points are moved along the touch surface. bubbles yes cancelable yes interface touchevent event handler property ontouchmove examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
Document: touchstart event - Web APIs
the touchstart event is fired when one or more touch points are placed on the touch surface. bubbles yes cancelable yes interface touchevent event handler property ontouchstart examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
Document: transitioncancel event - Web APIs
interface transitionevent event handler property globaleventhandlers.ontransitioncancel the original target for this event is the element that had the transition applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitioncancel. examples this code adds a listener to the transitioncancel event: document.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): document.ontransitioncancel = () => { console.log('transition canceled'); }; see a live example of this event. specifications specification status com...
Document: transitionend event - Web APIs
f the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. the original target for this event is the element that had the transition applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionend. examples this code adds a listener to the transitionend event: document.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend property instead of addeventlistener(): document.ontransitionend = () => { console.log('transition ended'); }; see a live example of this event. specifications specification status comment ...
Document: transitionrun event - Web APIs
cancelable no interface transitionevent event handler property ontransitionrun the original target for this event is the element that had the transition applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionrun. examples this code adds a listener to the transitionrun event: document.addeventlistener('transitionrun', () => { console.log('transition is running but hasn't necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): document.ontransitionrun = () => { console.log('transition started running'); }; see a live example of this event. specifica...
Document: transitionstart event - Web APIs
interface transitionevent event handler property globaleventhandlers.ontransitionstart the original target for this event is the element that had the transition applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionstart. examples this code adds a listener to the transitionstart event: document.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): document.ontransitionrun = () => { console.log('started transitioning'); }; see a live example of this event. specifications specification status comme...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
urns a caretposition object, containing the dom node, along with the caret and caret's character offset within that node. syntax var caretposition = document.caretpositionfrompoint(float x, float y); parameters x the horizontal coordinate of a point. y the vertical coordinate of a point. returns a caretposition object. example this example inserts line breaks wherever you click. the code for it is below the demo. demo html content <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. at vero eos et accusam et justo duo dolores et ea rebum. stet clita kasd gubergren, no sea takimata sanctus est lorem ipsum dolor sit amet.</p> javascript content function insertbreakatpoin...
DocumentTimeline.DocumentTimeline() - Web APIs
ted option is the origintime member which specifies the zero time for the documenttimeline as a real number of milliseconds relative to the navigationstart moment of the active document for the current browsing context. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
DocumentTimeline - Web APIs
wsing context. properties this interface inherits its property from its parent, animationtimeline. animationtimeline.currenttime returns the time value in milliseconds for this timeline or null if it is inactive. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
Events and the DOM - Web APIs
method you should use in modern web pages. note: internet explorer 6–8 didn't support this method, offering a similar eventtarget.attachevent api instead. for cross-browser compatibility, use one of the many javascript libraries available. more details can be found on the eventtarget.addeventlistener reference page. html attribute <button onclick="alert('hello world!')"> the javascript code in the attribute is passed the event object via the event parameter. the return value is treated in a special way, described in the html specification. warning: this method should be avoided! it inflates the markup, and makes it less readable. concerns of content/structure and behavior are not well-separated, making a bug harder to find. dom element properties // assuming mybutton is a butto...
Examples of web and XML development using the DOM - Web APIs
lay all the properties of the window.onload event object and their values in a table. it also shows a useful technique of using a for..in loop to iterate over the properties of an object to get their values. the properties of event objects differs greatly between browsers, the whatwg dom standard lists the standard properties, however many browsers have extended these greatly. put the following code into a blank text file and load it into a variety of browsers, you'll be surprised at the different number and names of properties. you might also like to add some elements in the page and call this function from different event handlers. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <title>show event properties</title> <style> table { border-collapse: collapse; } thead { font...
How to create a DOM tree - Web APIs
this page describes how to use the dom core api in javascript to create and modify dom objects. it applies to all gecko-based applications (such as firefox) both in privileged (extensions) and unprivileged (web pages) code. dynamically creating a dom tree consider the following xml document: <?xml version="1.0"?> <people> <person first-name="eric" middle-initial="h" last-name="jung"> <address street="321 south st" city="denver" state="co" country="usa"/> <address street="123 main st" city="arlington" state="ma" country="usa"/> </person> <person first-name="jed" last-name="brown"> <address street="321 north st" city="atlanta" state="ga" country="usa"/> <address street="123 west st" city="seattle" state="wa" country="usa"/> <address street="321 south avenue" city...
DynamicsCompressorNode.attack - Web APIs
quickly the signal is adapted when its volume is increased. the attack property's default value is 0.003 and it can be set between 0 and 1. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.attack.value = 0; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicsco...
DynamicsCompressorNode.knee - Web APIs
where the curve smoothly transitions to the compressed portion. the knee property's default value is 30 and it can be set between 0 and 40. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.knee.value = 40; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicsco...
DynamicsCompressorNode.ratio - Web APIs
, in db, needed in the input for a 1 db change in the output. the ratio property's default value is 12 and it can be set between 1 and 20. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.ratio.value = 12; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicsco...
DynamicsCompressorNode.release - Web APIs
quick the signal is adapted when its volume is reduced. the release property's default value is 0.25 and it can be set between 0 and 1. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.release.value = 0.25; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicsco...
DynamicsCompressorNode.threshold - Web APIs
e which the compression will start taking effect. the threshold property's default value is -24 and it can be set between -100 and 0. syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.threshold.value = -50; value an audioparam. note: though the audioparam returned is read-only, the value it represents is not. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicsco...
DynamicsCompressorNode - Web APIs
. dynamicscompressornode.attack read only is a k-rate audioparam representing the amount of time, in seconds, required to reduce the gain by 10 db. dynamicscompressornode.release read only is a k-rate audioparam representing the amount of time, in seconds, required to increase the gain by 10 db. methods no specific methods; inherits methods from its parent, audionode. example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track. for a more complete example, have a look at our basic compressor example (view the source code). // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicsco...
Element.attachShadow() - Web APIs
ent you are trying to attach to is already a shadow host. notsupportederror you are trying to attach a shadow root to an element outside the html namespace, or the element cannot have a shadow attached to it (see above). examples the following example is taken from our word-count-web-component demo (see it live also). you can see that we use attachshadow() in the middle of the code to create a shadow root, which we then attach our custom element's contents to. // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // count words in element's parent element var wcparent = this.parentnode; function countwords(node){ var text = node.innertext || node.text...
Element: auxclick event - Web APIs
the default behavior of the contextmenu event. examples in this example we define functions for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). javascript let button = document.queryselector('button'); let html = document.queryselector('html'); function random(number) { return math.floor(math.random() * number); } function randomcolor() { return `rgb(${random(255)}, ${random(255)}, ${random(255)})`; } button.onclick = function() { button.style.backgroundcolor = randomcolor(); }; button.onauxclick = function(e) { e.preve...
Element.classList - Web APIs
Web › API › Element › classList
document.documentelement.firstchild.appendchild(document.createelement('style')).stylesheet.csstext=( '_*{x-uclp:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' + // ie6 '[class]{x-uclp/**/:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' ...
Element: fullscreenchange event - Web APIs
be placed into full-screen mode. remember that by the time the fullscreenchange event is handled, the status of the element has already changed. so if the change is to full-screen mode, document.fullscreenelement will point to the element that is now in full-screen mode. on the other hand, if document.fullscreenelement is null, full-screen mode has been canceled. what that means to the example code is that, if an element is currently in full-screen mode, the fullscreenchange handler logs the id of the full-screen element to the console. if document.fullscreenelement is null, the code logs a message that the change is to leave full-screen mode. html <h1>fullscreenchange event example</h1> <div id="fullscreen-div"> <button id="toggle-fullscreen">toggle fullscreen mode</button> </div> ...
Element.getAnimations() - Web APIs
element to be returned as well. this includes animations that target any css pseudo-elements attached to element or one of its descendents. defaults to false. return value an array of animation objects, each representing an animation currently targetting the element on which this method is called, or one of its descendant elements if { subtree: true } is specified. examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. promise.all( elem.getanimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); specifications specification status comment web animationsthe definition of 'animatable.getanimations()' in that specification...
Element.getBoundingClientRect() - Web APIs
he top and left properties (these can be obtained using window.scrollx and window.scrolly) to get a bounding rectangle which is independent from the current scrolling position. cross-browser fallback scripts requiring high cross-browser compatibility can use window.pagexoffset and window.pageyoffset instead of window.scrollx and window.scrolly. ...
Element.getClientRects() - Web APIs
d the paragraph and the <span> inside each <div> block for the first example, around the <ol> and <li> for the second example, and around <table>, <th>, and <td> elements for the third example. strong { text-align: center; } div { display: inline-block; width: 150px; } div p, ol, table { border: 1px solid blue; } span, li, th, td { border: 1px solid green; } javascript the javascript code draws the client rects for all html elements that have css class withclientrectsoverlay assigned. function addclientrectsoverlay(elt) { /* absolutely position a div over each client rect so that its border width is the same as the rectangle's width. note: the overlays will be out of place if the user resizes or zooms. */ var rects = elt.getclientrects(); for (var i = 0; i != rect...
Element.insertAdjacentElement() - Web APIs
when one is clicked, it becomes selected and you can then press the insert before and insert after buttons to insert new divs before or after the selected element using insertadjacentelement(). specification specification status comment domthe definition of 'insertadjacentelement()' in that specifica...
Element: keypress event - Web APIs
event has been deprecated, you should look to use beforeinput or keydown instead. interface keyboardevent bubbles yes cancelable yes default action varies: keypress event; launch text composition system; blur and focus events; domactivate event; other event examples addeventlistener keypress example this example logs the keyboardevent.code value whenever you press a key after focussing the <input> element. <div> <label for="sample">focus the input and type something:</label> <input type="text" name="text" id="sample"> </div> <p id="log"></p> const log = document.getelementbyid('log'); const input = document.queryselector('input'); input.addeventlistener('keypress', logkey); function logkey(e) { log.textcontent += ` ${e.co...
Element: mousewheel event - Web APIs
ly, old mouse wheel which cannot be turned smoothly), the value is computed from non-accelerated scroll amount (120 per notch). in this case, the value is different from safari. this difference makes a serious issue for web application developers. that is, web developers cannot know if mousewheel event is caused by which device. see webinputeventfactory::mousewheelevent of the chromium's source code for the detail. safari the value is always computed from accelerated scroll amount. this is really different from other browsers except chrome with continuous scroll supported device. opera (presto) the value is always the detail attribute value ✕ 40. on windows, since the detail attribute value is computed from actual scroll amount, the value is different from other browsers except the sc...
Element.scrollTop - Web APIs
Web › API › Element › scrollTop
not generate a vertical scrollbar, then its scrolltop value is 0. when scrolltop is used on the root element (the <html> element), the scrolly of the window is returned. this is a special case of scrolltop. on systems using display scaling, scrolltop may give you a decimal value. syntax // get the number of pixels scrolled. var intelemscrolltop = someelement.scrolltop; after running this code, intelemscrolltop is an integer corresponding to the number of pixels that the element's content has been scrolled upwards. // set the number of pixels scrolled. element.scrolltop = intvalue; scrolltop can be set to any integer value, with certain caveats: if the element can't be scrolled (e.g. it has no overflow or if the element has a property of "non-scrollable"), scrolltop is 0. scroll...
Element: touchcancel event - Web APIs
the touchcancel event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created). bubbles yes cancelable no interface touchevent event handler property ontouchcancel examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
Element: touchend event - Web APIs
the touchend event fires when one or more touch points are removed from the touch surface. bubbles yes cancelable yes interface touchevent event handler property ontouchend examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
Element: touchmove event - Web APIs
the touchmove event is fired when one or more touch points are moved along the touch surface. bubbles yes cancelable yes interface touchevent event handler property ontouchmove examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
Element: touchstart event - Web APIs
the touchstart event is fired when one or more touch points are placed on the touch surface. bubbles yes cancelable yes interface touchevent event handler property ontouchstart examples code samples for those events are available on the dedicated page: touch events. specifications specification status touch events recommendation ...
ElementCSSInlineStyle.style - Web APIs
useful for completely learning about the styles applied on the element, since it represents only the css declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. to get the values of all css properties for an element you should use window.getcomputedstyle() instead. ...
Encoding API - Web APIs
the encoding api provides a mechanism for handling text in various character encodings, including legacy non-utf-8 encodings. the api provides four interfaces: textdecoder, textencoder, textdecoderstream and textencoderstream. interfaces textdecoder textencoder textdecoderstream textencoderstream tutorials & tools a shim allowing to use this interface in browsers that don't support it. stringview – a c-like representation of strings based on typed arrays. specifications specification status comment encoding living standard initial definition. ...
Event.cancelable - Web APIs
Web › API › Event › cancelable
nt to check cancelable before invoking their preventdefault() methods. most browser-native events that can be canceled are the ones that result from the user interacting with the page. canceling the click, scroll, or beforeunload events would prevent the user from clicking on something, scrolling the page, or navigating away from the page, respectively. custom events created by other javascript code control if they can be canceled when they are created. syntax bool = event.cancelable; value the result is a boolean, which is true if the event can be canceled. example for example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is called — any following wheel events cannot be canceled. function preventscrollwheel(event) { if (type...
Event.currentTarget - Web APIs
value of event.currenttarget is only available while the event is being handled. if you console.log() the event object, storing it in a variable, and then look for the currenttarget key in the console, its value will be null. instead, you can either directly console.log(event.currenttarget) to be able to view it in the console or use the debugger statement, which will pause the execution of your code thus showing you the value of event.currenttarget. specifications specification status comment domthe definition of 'event.currenttarget' in that specification. living standard dom4the definition of 'event.currenttarget' in that specification. obsolete document object model (dom) level 3 events specificationthe definition of 'current even...
Event.originalTarget - Web APIs
the original target of the event before any retargetings. (mozilla-specific) in presence of xbl anonymous content this will be the anonymous node the event originally fired on. see anonymous content#event_flow_and_targeting for more details. note: originaltarget may also be native anonymous content (see bug 208427), in which case it's useless for non-privileged code. see also comparison of event targets example need an example that makes sense here specification this is a mozilla-specific property. defined in /dom/public/idl/events/nsidomnsevent.idl this event property is not defined in the w3.org dom level 2 events ...
Event.returnValue - Web APIs
Web › API › Event › returnValue
you should use preventdefault(), and defaultprevented instead of this historical property. ...
EventSource - Web APIs
the eventsource interface is web content's interface to server-sent events. an eventsource instance opens a persistent connection to an http server, which sends events in text/event-stream format. the connection remains open until closed by calling eventsource.close(). once the connection is opened, incoming messages from the server are delivered to your code in the form of events. if there is an event field in the incoming message, the triggered event is the same as the event field value. if no event field is present, then a generic message event is fired. unlike websockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). that makes them an excellent choice when there's no need to se...
EventTarget.dispatchEvent() - Web APIs
as uncaught exceptions. the event handlers run on a nested callstack; they block the caller until they complete, but exceptions do not propagate to the caller. notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event loop, dispatchevent() invokes event handlers synchronously. all applicable event handlers will execute and return before the code continues on after the call to dispatchevent(). dispatchevent() is the last step of the create-init-dispatch process, which is used for dispatching events into the implementation's event model. the event can be created using event constructor. see also the event object reference. example see creating and triggering events. specifications specification status comment ...
EventTarget.removeEventListener() - Web APIs
of the event handler to remove from the event target. options optional an options object that specifies characteristics about the event listener. the available options are: capture: a boolean which indicates that events of this type will be dispatched to the registered listener before being dispatched to any eventtarget beneath it in the dom tree. mozsystemgroup: available only in code running in xbl or in firefox' chrome, it is a boolean defining if the listener is added to the system group. usecapture optional specifies whether the eventlistener to be removed is registered as a capturing listener or not. if this parameter is absent, a default value of false is assumed. if a listener is registered twice, one with capture and one without, remove each one separately. remo...
EventTarget - Web APIs
ts: all;} constructor eventtarget() creates a new eventtarget object instance. methods eventtarget.addeventlistener() registers an event handler of a specific event type on the eventtarget. eventtarget.removeeventlistener() removes an event listener from the eventtarget. eventtarget.dispatchevent() dispatches an event to this eventtarget. additional methods in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties. see also webidl bindings. void seteventhandler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) example simple implementation of eventtarget var eventtarget = function() { this.listeners = {}; }; eventtarget.prototype.listeners = n...
ExtendableMessageEvent.data - Web APIs
the data read-only property of the extendablemessageevent interface returns the event's data. it can be any data type. syntax var mydata = extendablemessageevent.data; value any data type. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.data); port = e.ports[0]; } ...
ExtendableMessageEvent.lastEventId - Web APIs
the lasteventid read-only property of the extendablemessageevent interface represents, in server-sent events, the last event id of the event source. this is an empty string. syntax var mylasteventid = extendablemessageevent.lasteventid; value a domstring. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmess...
ExtendableMessageEvent.origin - Web APIs
the origin read-only property of the extendablemessageevent interface returns the origin of the client that sent the message. syntax var myorigin = extendablemessageevent.origin; value a usvstring. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.origin); port = e.po...
ExtendableMessageEvent.ports - Web APIs
the ports read-only property of the extendablemessageevent interface returns the array containing the messageport objects representing the ports of the associated message channel (the channel the message is being sent through.) syntax var myports = extendablemessageevent.ports; value an array of messageport objects. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action ==...
ExtendableMessageEvent.source - Web APIs
the source read-only property of the extendablemessageevent interface returns a reference to the client object from which the message was sent. syntax var mysource = extendablemessageevent.source; value a client, serviceworker or messageport object. examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent. var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = ...
FetchEvent.preloadResponse - Web APIs
the preloadresponse read-only property of the fetchevent interface returns a promise that resolves to the navigation preload response if navigation preload was triggered or undefined otherwise. syntax var expectedresponse = fetchevent.preloadresponse; value a promise that resolves to a response or otherwise to undefined. example this code snippet is from the navigation preload page. the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code checks for a preloaded response. else it fetches a response from the network. addeventlistener('fetch', event => { event.respondwit...
File.File() - Web APIs
Web › API › File › File
name a usvstring representing the file name or the path to the file. options optional an options object containing optional attributes for the file. ...
File.getAsDataURL() - Web APIs
Web › API › File › getAsDataURL
note: this method is obsolete; you should use the filereader method readasdataurl() instead. ...
File.getAsText() - Web APIs
Web › API › File › getAsText
...
File.mozFullPath - Web APIs
Web › API › File › mozFullPath
it is not available to web content. ...
FileList - Web APIs
Web › API › FileList
in only one file. starting with gecko 1.9.2, if the input element's multiple attribute is true, the filelist may contain multiple files. using the file list all <input> element nodes have a files attribute of type filelist on them which allows access to the items in this list. for example, if the html includes the following file input: <input id="fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicating the number of files in the list. methods item() returns a file object representing the file at the sp...
FileReader() - Web APIs
the filereader() constructor creates a new filereader. for details about how to use filereader, see using files from web applications. syntax var reader = new filereader(); parameters none. ...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
callback has no parameters. errorcallback optional a function to be called if an error occurs while attempting to remove the directory subtree. receives a fileerror describing the error which occurred as input. return value undefined. errors if an error occurs and an errorcallback was specified, it gets called with a single parameter: a fileerror object describing the error. the fileerror.code specifies what type of error occurred, as follows: fileerror.invalid_modification_err an attempt was made to remove the root directory; this is not permitted. fileerror.no_modification_allowed_err the file system's state doesn't permit modification. fileerror.not_found_err the directory represented by the filesystemdirectoryentry no longer exists. fileerror.not_readable_err the director...
FileSystemDirectoryEntry - Web APIs
sic concepts you can create a new directory by calling getdirectory(). if you want to create subdirectories, create each child directory in sequence. if you try creating a directory using a full path that includes parent directories that do not exist yet, an error is returned. so create the hierarchy by recursively adding a new path after creating the parent directory. example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes. window.requestfilesystem = window.requestfilesystem || window.webkitrequestfilesystem; window.directoryentry = window.directoryentry || window.webkitdirectoryentry; ... function onfs(fs){ fs.root.getdirectory('documents', {create:true}, function(directoryentry){ //directoryentry.isfile ===...
FileSystemFileEntry - Web APIs
new file object which can be used to read the file. obsolete methods createwriter() creates a new filewriter object which allows writing to the file represented by the file system entry. basic concepts to write content to file, create a filewriter object by calling createwriter(). to read a file, obtain a file object representing its contents by calling file(). example the following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "meow". inside the success callback, event handlers are set up to handle the error error and writeend events. the text data is written to the file by creating a blob, appending text to it, and passing the blob to filewriter.write(). function oninitfs(fs) { fs.root.getfile('log.txt', {create: true}, function...
FileSystemFlags.create - Web APIs
n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is pass...
FileSystemFlags.exclusive - Web APIs
n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is pass...
FileSystemFlags - Web APIs
n/a[1] path exists and matches the desired type (depending on whether the function called is getfile() or getdirectory() the successcallback is called with a filesystemfileentry if getfile() was called or a filesystemdirectoryentry if getdirectory() was called. false n/a[1] path exists but doesn't match the desired type the errorcallback is called with an appropriate error code (if the callback was provided). true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate. true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is pass...
FileHandle API - Web APIs
ents: a name and an optional type. both of these are just descriptive and are not used by the database. however, they are important for the filehandle object as it can generate file objects which inherit their own name and type from those values. that said, as the name does not match any real filename it can be an empty string, for example, and it doesn't even have to be unique. note: the above code only creates a "temporary file" that exists only while you hold the filehandle instance. if you want a file to survive a page refresh/app relaunch, you need to store the handle in a more permanent location, like the database itself. see file storage below to learn more about this. perform read and write operations to read or write within a handled file, it is required to get a lockedfile. the ...
File and Directory Entries API support in Firefox - Web APIs
rectoryentry filesystemdirectoryentrysync directoryentrysync filesystemdirectoryreader directoryreader filesystemdirectoryreadersync directoryreadersync filesystementry entry filesystementrysync entrysync filesystemfileentry fileentry filesystemfileentrysync fileentrysync be sure to account for this in your code by allowing for both names. hopefully chrome will be updated soon to use the newer names! to ensure your code will work in both chrome and other browsers, you can include code similar to the following: var filesystemdirectoryentry = window.filesystemdirectoryentry || window.directoryentry; var filesystementry = window.filesystementry || window.entry; limitations in firefox next, let's look a...
Introduction to the File and Directory Entries API - Web APIs
hods are members of both the window object and the worker global scope. the synchronous api, on the other hand, uses the following methods: requestfilesystemsync() and resolvelocalfilesystemsyncurl(). these synchronous methods are members of the worker's global scope only, not the window object. the synchronous api can be simpler for some tasks. its direct, in-order programming model can make code easier to read. the drawback of synchronous api has to do with its interactions with web workers, which has some limitations. when using the asynchronous api, always use the error callbacks when using the asynchronous api, always use the error callbacks. although the error callbacks for the methods are optional parameters, they are not optional for your sanity. you want to know why your calls f...
FontFace - Web APIs
Web › API › FontFace
tatus read only returns an enumerated value indicating the status of the font, one of "unloaded", "loading", "loaded", or "error". fontface.stretch a cssomstring that retrieves or sets how the font stretches. it is equivalent to the font-stretch descriptor. fontface.style a cssomstring that retrieves or sets the style of the font. it is equivalent to the font-style descriptor. fontface.unicoderange a cssomstring that retrieves or sets the range of unicode codepoints encompassing the font. it is equivalent to the unicode-range descriptor. fontface.variant a cssomstring that retrieves or sets the variant of the font. it is equivalent to the font-variant descriptor. fontface.weight a cssomstring that contains the weight of the font. it is equivalent to the font-weight descriptor. m...
FontFaceSet.check() - Web APIs
Web › API › FontFaceSet › check
hod of the fontfaceset returns whether all fonts in the given font list have been loaded and are available. syntax bool = afontfaceset.check(font); bool = afontfaceset.check(font, text); returns a boolean that is true if the font list is available parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. examples document.fonts.check("12px courier"); // returns true if the font courier is available at 12px document.fonts.check("12px myfont", "ß"); // returns true if the font 'myfont' has a ß character. specifications specification status comment css font loadi...
FontFaceSet.load() - Web APIs
Web › API › FontFaceSet › load
loaded. syntax result = afontfaceset.load(font); result = afontfaceset.load(font, text); returns a promise of an array of fontface loaded. the promise is fulfilled when all the fonts are loaded; it is rejected if one of the fonts failed to load. parameters font: a font specification using the css value syntax, e.g. "italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text. this does not check for individual glyph coverage. examples // returns a promise that will be fulfilled or rejected according the success to load myfont // the code in 'then' can assume the availability of that font. document.fonts.load("12px myfont", "ß").then(…); specifications specification status comment ...
FormData() - Web APIs
Web › API › FormData › FormData
ata() constructor creates a new formdata object. note: this feature is available in web workers. syntax var formdata = new formdata(form) parameters form optional an html <form> element — when specified, the formdata object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. it will also encode file input content. example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you could add a key/value pair to this using formdata.append: formdata.append('username', 'chris'); or you can specify the optional form argument when creating the formdata object, to prepopulate it with values from the specified form: <form id="myform" name=...
Using FormData Objects - Web APIs
pe="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br /> <label>custom file label:</label> <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>file to stash:</label> <input type="file" name="file" required /> <input type="submit" value="stash the file!" /> </form> <div></div> then you can send it using code like the following: var form = document.forms.nameditem("fileinfo"); form.addeventlistener('submit', function(ev) { var ooutput = document.queryselector("div"), odata = new formdata(form); odata.append("customfield", "this is some extra data"); var oreq = new xmlhttprequest(); oreq.open("post", "stash.php", true); oreq.onload = function(oevent) { if (oreq.status == 200) { ...
Frame Timing API - Web APIs
ess a frame in about 16.7 ms. an application can register a performanceobserver for "frame" performance entry types. the observer (callback) will be notified when new "frame" events are added to the browser's performance timeline and the frame's duration (length of time) will be available. this data can be used to help identify areas that take too long to provide a good user experience. example code of the interfaces described in this document is included in using the frame timing api. performance frames the performanceframetiming interface extends the following performanceentry properties (for "frame" performance entry types) by qualifying and constrainting the properties as follows: performanceentry.entrytype set to "frame". performanceentry.name set to the document's address. per...
Geolocation.clearWatch() - Web APIs
tion.watchposition() method when installing the handler you wish to remove. example var id, target, option; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulation, you reach the target'); navigator.geolocation.clearwatch(id); } }; function error(err) { console.warn('error(' + err.code + '): ' + err.message); }; target = { latitude : 0, longitude: 0, } options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success, error, options); specifications specification status comment geolocation api recommendation initial specification. ...
Geolocation.getCurrentPosition() - Web APIs
...
Geolocation.watchPosition() - Web APIs
can be passed to the geolocation.clearwatch() to unregister the handler. examples var id, target, options; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulations, you reached the target'); navigator.geolocation.clearwatch(id); } } function error(err) { console.warn('error(' + err.code + '): ' + err.message); } target = { latitude : 0, longitude: 0 }; options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success, error, options); specifications specification status comment geolocation apithe definition of 'watchposition()' in that specification. recommendation initial spe...
GeolocationCoordinates.longitude - Web APIs
which meridian that most people think of. it is, instead, the iers reference meridian, which is located 5.3 arcseconds (102 meters / 335 feet) east of the greenwich meridian. this is the same standard used by the global positioning system (gps). examples in this simple example, we fetch the user's location and display the resulting coordinates once they're returned. javascript the javascript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed. let button = document.getelementbyid("get-location"); let lattext = document.getelementbyid("latitude"); let longtext = document.getelementbyid("longitude"); button.addeventlistener("click", function() { navigator.geolocation.getcurrentposition(function(position) { ...
GeolocationPositionError - Web APIs
the geolocationpositionerror interface represents the reason of an error occurring when using the geolocating device. properties the geolocationpositionerror interface doesn't inherit any property. geolocationpositionerror.code read only secure context returns an unsigned short representing the error code. the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position returned an internal error. 3 timeout the time allowed to acquire the geolocation,...
Using the Geolocation API - Web APIs
a geolocationcoordinates object, including altitude, speed, what direction the device is facing, and an accuracy measure of the altitude, longitude, and latitude data. handling errors the error callback function, if provided when calling getcurrentposition() or watchposition(), expects a geolocationpositionerror object instance as its first parameter. this object type contains two properties, a code indicating what type of error has been returned, and a human-readable message that describes what the error code means. you could use it like so: function errorcallback(error) { alert(`error(${error.code}): ${error.message}`); }; examples in the following example the geolocation api is used to retrieve the user's latitude and longitude. if sucessful, the available hyperlink is populated wi...
Geolocation API - Web APIs
oncoordinates object instance. geolocationcoordinates represents the coordinates of a user's position; a geolocationcoordinates instance contains latitude, longitude, and other important related information. geolocationpositionerror a geolocationpositionerror is returned by an unsuccessful call to one of the methods contained inside geolocation, inside an error callback, and contains an error code and message. navigator.geolocation the entry point into the api. returns a geolocation object instance, from which all other functionality can be accessed. dictionaries positionoptions represents an object containing options to pass in as a parameter of geolocation.getcurrentposition() and geolocation.watchposition(). examples in the following example the geolocation api is used to ret...
GlobalEventHandlers.onauxclick - Web APIs
tlistener() method instead, since it's more flexible. example in this example we define functions for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). var button = document.queryselector('button'); var html = document.queryselector('html'); function random(number) { return math.floor(math.random() * number); } button.onclick = function() { var rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; button.style.backgroundcolor = rndcol; }; button.onauxclick = function() { var rndcol = 'rgb(' + random(255) + ',...
GlobalEventHandlers.ondrag - Web APIs
t"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <!-- <div class="source"> --> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" on...
GlobalEventHandlers.ondragend - Web APIs
reen to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</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.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> ...
GlobalEventHandlers.ondragenter - Web APIs
reen to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</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.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> ...
GlobalEventHandlers.ondragexit - Web APIs
reen to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</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.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> ...
GlobalEventHandlers.ondragleave - Web APIs
reen to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</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.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> ...
GlobalEventHandlers.ondragover - Web APIs
t"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(eve...
GlobalEventHandlers.ondragstart - Web APIs
t"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(eve...
GlobalEventHandlers.ondrop - Web APIs
t"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div class="source"> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="drago...
GlobalEventHandlers.onloadend - Web APIs
the onloadend property of the globaleventhandlers mixin is an eventhandler representing the code to be called when the loadend event is raised (when progress has stopped on the loading of a resource.) syntax img.onloadend = funcref; value funcref is the handler function to be called when the resource's loadend event fires. examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); ...
GlobalEventHandlers.onloadstart - Web APIs
the onloadstart property of the globaleventhandlers mixin is an eventhandler representing the code to be called when the loadstart event is raised (when progress has begun on the loading of a resource.) syntax img.onloadstart = funcref; value funcref is the handler function to be called when the resource's loadstart event fires. examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); specifications specification status comment htm...
Gyroscope.Gyroscope() - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
Gyroscope.x - Web APIs
Web › API › Gyroscope › x
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var x = gyroscope.x value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Gyroscope.y - Web APIs
Web › API › Gyroscope › y
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var y = gyroscope.y value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Gyroscope.z - Web APIs
Web › API › Gyroscope › z
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var z = gyroscope.z value a number. example the gyroscope is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Gyroscope - Web APIs
Web › API › Gyroscope
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
msAudioCategory - Web APIs
microsoft edge. msaudiocategory specifies the purpose of the audio or video media, such as background audio or alerts. syntax <audio controls="controls" msaudiocategory="backgroundcapablemedia"> </audio> the msaudiocategory property offers a variety of values that can enhance the behavior of your audio-aware app. note that you must set the msaudiocategory before setting the src property in code. value include a description of the property's value, including data type and what it represents. value description background capable? alert looping or longer running alert sounds: alarms ring tones ringing notification sounds that need to attenuate existing audio no backgroundcapablemedia for audio that needs t...
HTMLCanvasElement.getContext() - Web APIs
for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" or imagebitmaprenderingcontext for "bitmaprenderer". if the contexttype doesn't match a possible drawing context, null is returned. examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get a 2d context of the canvas with the following code: var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); console.log(ctx); // canvasrenderingcontext2d { ... } now you have the 2d rendering context for a canvas and you can draw within it. specifications specification status comment html living standardthe definition of 'htmlcanvaselement.getcontext' in that specification. living standar...
HTMLCanvasElement.height - Web APIs
et to an invalid value, like a negative, the default value of 150 is used. this is one of the two properties, the other being htmlcanvaselement.width, that controls the size of the canvas. syntax var pxl = canvas.height; canvas.height = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the height of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.height); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.height' in that specification. living standard no change since the latest snapshot, html5 html 5.1the definition of 'htmlcanvaselement.height' in that specification. re...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
it saves to the desktop it uses fileutils.jsm. ...
HTMLCanvasElement.mozGetAsFile() - Web APIs
le's data is entirely located in memory until such time as it is explicitly written to disk. examples this example creates an image file from the <canvas> element on the page, then uses a filereader to read the image data from the file. html <canvas id="canvas" width="100" height="100"></canvas> <p><a href="#" id="link">click here to try out mozgetasfile()</a>.</p> javascript the following code uses mozgetasfile() to create a file object from the canvas and appends it as an image to the page by loading it as a data url using the readasdataurl() method. then a new <img> element is created using the new data url. function draw() { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(200, 0, 0)'; ctx.fillrect(10, 10, 55, 50); ...
HTMLCanvasElement.toDataURL() - Web APIs
r (defaults to png). the returned image is in a resolution of 96 dpi. if the height or width of the canvas is 0 or larger than the maximum canvas size, the string "data:," is returned. if the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported. chrome also supports the image/webp type. syntax canvas.todataurl(type, encoderoptions); parameters type optional a domstring indicating the image format. the default format type is image/png. encoderoptions optional a number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. if this argument is anything else, the default value for image quality is used. the default value is 0.92. othe...
HTMLCanvasElement.width - Web APIs
set to an invalid value, like a negative, the default value of 300 is used. this is one of the two properties, the other being htmlcanvaselement.height, that controls the size of the canvas. syntax var pxl = canvas.width; canvas.width = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the width of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.width); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.width' in that specification. living standard no change since the latest snapshot, html5 html 5.1the definition of 'htmlcanvaselement.width' in that specification. recom...
HTMLElement: animationcancel event - Web APIs
the animating node is hidden using css. therefore, either directly or because any of its containing nodes are hidden. an event handler for this event can be added by setting the onanimationcancel property, or using addeventlistener(). bubbles yes cancelable no interface animationevent event handler property onanimationcancel examples this code gets an element that's currently being animated and adds a listener to the animationcancel event. it then sets the element's display property to none, which will trigger the animationcancel event. const animated = document.queryselector('.animated'); animated.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); animated.style.display = 'none'; the same, but usi...
HTMLElement: animationiteration event - Web APIs
t is fired when an iteration of a css animation ends, and another one begins. this event does not occur at the same time as the animationend event, and therefore does not occur for animations with an animation-iteration-count of one. ...
HTMLElement.lang - Web APIs
Web › API › HTMLElement › lang
common examples include "en" for english, "ja" for japanese, "es" for spanish and so on. the default value of this attribute is unknown. note that this attribute, though valid at the individual element level described here, is most often specified for the root element of the document. this also only works with the lang attribute and not with xml:lang. ...
HTMLElement: transitioncancel event - Web APIs
the transitioncancel event is fired when a css transition is canceled. see globaleventhandlers.ontransitioncancel for more information. ...
HTMLElement: transitionend event - Web APIs
fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. if there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. ...
HTMLElement: transitionrun event - Web APIs
the transitionrun event is fired when a css transition is first created, i.e. before any transition-delay has begun. ...
HTMLElement: transitionstart event - Web APIs
the transitionstart event is fired when a css transition has actually started, i.e., after any transition-delay has ended. ...
HTMLFormElement.enctype - Web APIs
the htmlformelement.enctype property is the mime type of content that is used to submit the form to the server. possible values are: application/x-www-form-urlencoded: the initial default type. multipart/form-data: the type that allows file <input> element(s) to upload file data. text/plain: a type introduced in html5. this value can be overridden by a formenctype attribute on a <button> or <input> element. syntax var string = form.enctype; form.enctype = string; example form.enctype = 'application/x-www-form-urlencoded'; specifications specification status comment html living standardthe definition of 'htmlformelement: enctype' in that specification. living standard ...
HTMLFormElement.requestSubmit() - Web APIs
form object. examples in the example below, the form is submitted by attempting to send the request using requestsubmit() if it's available. if a submit button with the id main-submit is found, that's used to submit the form. otherwise, the form is submitted with no submitter parameter, so it's submitted directly by the form itself. if, on the other hand, requestsubmit() isn't available, this code falls back to calling the form's submit() method. let myform = document.queryselector("form"); let submitbutton = myform.queryselector("#main-submit"); if (myform.requestsubmit) { if (submitbutton) { myform.requestsubmit(submitbutton); } else { myform.requestsubmit(); } } else { myform.submit(); } specifications specification status comment html li...
HTMLHyperlinkElementUtils.hash - Web APIs
if the url does not have a fragment identifier, this property contains an empty string, "". ...
HTMLHyperlinkElementUtils.origin - Web APIs
e.g "blob:https://mozilla.org" will have "https://mozilla.org". note: this feature is available in web workers. ...
HTMLImageElement.align - Web APIs
e is to be aligned vertically with the current text baseline. default value. middle the center of the object should be aligned vertically with the current baseline. top the top edge of the object should be aligned vertically with the current baseline. it may be worth noting that vertical-align offers several additional options for its value; you may wish to consider these when changing your code to use it. floating images horizontally the left and right properties don't affect the baseline-relative alignment. instead, they cause the image to "float" to the left or right margin, allowing the following text to flow around the image. you should instead use the css float property, specifying as the value either left or right. left floats the image over to place the left edge flush agai...
HTMLImageElement.crossOrigin - Web APIs
ge requests by the element will use cors, regardless of what domain the fetch is from. if crossorigin is an empty string (""), the anonymous mode is selected. example in this example, a new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads. javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a newly-created image. const imageurl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.queryselector(".container"); function loadimage(url) { const image = new image(200, 200); image.addeventlistener("load", () => container.prepen...
HTMLImageElement.height - Web APIs
to 400px wide, the image is drawn at a width of 200px; otherwise, it's drawn at 300px. <p>image height: <span class="size">?</span>px (resize to update)</p> <img src="/files/17373/clock-demo-200px.png" alt="clock" srcset="/files/17373/clock-demo-200px.png 200w, /files/17374/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 300px"> javascript the javascript code looks at the height to determine the height of the image given the width at which it's currently drawn. var clockimage = document.queryselector("img"); let output = document.queryselector(".size"); const updateheight = event => { output.innertext = clockimage.height; }; window.addeventlistener("load", updateheight); window.addeventlistener("resize", updateheight); result this example may ...
HTMLImageElement.naturalHeight - Web APIs
this is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. result specifications specification status comment html living standardthe definition of 'htmlimageelement.naturalheight'...
HTMLImageElement.naturalWidth - Web APIs
this is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. result specifications specification status comment html living standardthe definition of 'htmlimageelement.naturalwidth' ...
HTMLImageElement.sizes - Web APIs
let image = document.queryselector("article img"); let break40 = document.getelementbyid("break40"); let break50 = document.getelementbyid("break50"); break40.a...
HTMLImageElement.width - Web APIs
to 400px wide, the image is drawn at a width of 200px; otherwise, it's drawn at 400px. <p>image width: <span class="size">?</span>px (resize to update)</p> <img src="/files/16864/clock-demo-200px.png" alt="clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 400px"> javascript the javascript code looks at the width to determine the width of the image at the moment. this is done in the window's load and resize event handlers, in order to always provide this information. var clockimage = document.queryselector("img"); let output = document.queryselector(".size"); const updatewidth = event => { output.innertext = clockimage.width; }; window.addeventlistener("load", updatewidth); window.ad...
HTMLImageElement.x - Web APIs
name, and their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>...
HTMLImageElement.y - Web APIs
name, and their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>...
HTMLInputElement.webkitEntries - Web APIs
entry objects. example this example shows how to create a file selection <input> element and process the selected files. html <input id="files" type="file" multiple> javascript document.getelementbyid("files").addeventlistener("change", function(event) { event.target.webkitentries.foreach(function(entry) { /* do stuff with the entry */ }); }); each time a change event occurs, this code iterates over the selected files, obtaining their filesystementry-based objects and acting on them. specifications specification status comment file and directory entries apithe definition of 'webkitentries' in that specification. draft initial specification. this api has no official w3c or whatwg specification. browser compatibility the compatibility ...
HTMLLinkElement - Web APIs
is a domstring that corresponds to the cors setting for this link element. see cors settings attributes for details. htmllinkelement.disabled is a boolean which represents whether the link is disabled; currently only used with style sheet links. htmllinkelement.href is a domstring representing the uri for the target resource. htmllinkelement.hreflang is a domstring representing the language code for the linked resource. htmllinkelement.media is a domstring representing a list of one or more media formats to which the resource applies. htmllinkelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use. htmllinkelement.rel is a domstring representing the forward relationship of the linked resource from the document to the ...
HTMLMediaElement.audioTracks - Web APIs
list of tracks can be accessed using array notation, or using the object's gettrackbyid() method. each track is represented by a audiotrack object which provides information about the track. examples in this example, all of the audio tracks on a given element are muted. html the html establishes the element itself. <video id="video" src="somevideo.mp4"></video> javascript the javascript code handles muting the video element's audio tracks. var video = document.getelementbyid("video"); for (var i = 0; i < video.audiotracks.length; i += 1) { video.audiotracks[i].enabled = false; } specifications specification status comment html living standardthe definition of 'htmlmediaelement.audiotracks' in that specification. living standard no change from html...
HTMLMediaElement.captureStream() - Web APIs
nterface returns a mediastream object which is streaming a real-time capture of the content being rendered in the media element. this can be used, for example, as a source for a webrtc rtcpeerconnection. syntax var mediastream = mediaelement.capturestream() parameters none. return value a mediastream object which can be used as a source for audio and/or video data by other media processing code, or as a source for webrtc. example in this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the id "playback" into a mediastream. the stream can then be used for other purposes—like a source for streaming over webrtc, to allow sharing prerecorded videos with another person during a video call. document.queryselector('.p...
HTMLMediaElement.error - Web APIs
; value a mediaerror object describing the most recent error to occur on the media element or null if no errors have occurred. example this example establishes a video element and adds an error handler to it; the error handler simply logs the details to console. var videoelement = document.createelement('video'); videoelement.onerror = function() { console.log("error " + videoelement.error.code + "; details: " + videoelement.error.message); } videoelement.src = "https://example.com/bogusvideo.mp4"; specifications specification status comment html living standardthe definition of 'htmlmediaelement.error' in that specification. living standard html5the definition of 'htmlmediaelement.error' in that specification. recommendation ...
HTMLMediaElement.play() - Web APIs
d not present a user interface that assumes playback has begun automatically, but should instead update their ui based on whether the returned promise is resolved or rejected. see the example below for more information. note: the play() method may cause the user to be asked to grant permission to play the media, resulting in a possible delay before the returned promise is resolved. be sure your code doesn't expect an immediate response. for even more in-depth information about autoplay and autoplay blocking, see our article autoplay guide for media and web audio apis. example this example demonstrates how to confirm that playback has begun and how to gracefully handle blocked automatic playback: let videoelem = document.getelementbyid("video"); let playbutton = document.getelementbyid("...
HTMLMediaElement.seekToNextFrame() - Web APIs
the htmlmediaelement.seektonextframe() method asynchronously advances the the current play position to the next frame in the media. this non-standard method is part of an experimentation process around support for non-real-time access to media for tasks including filtering, editing, and so forth. you should not use this method in production code, because its implementation may change—or be removed outright—without notice. you are, however, invited to experiment with it. this method lets you access frames of video media without the media being performed in real time. this also lets you access media using frames as a seek unit rather than timecodes (albeit only by seeking one frame at a time until you get to the frame you want). possible uses for this method include filtering and edi...
HTMLScriptElement - Web APIs
cts the referrerpolicy html attribute indicating which referrer to use when fetching the script, and fetches done by that script. methods no specific methods; inherits methods from its parent, htmlelement. examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript). these scripts will be asynchronously executed. for more details, see the defer and async properties. function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function prefixscript(url, onloadfunction) { var newscript = document.createelement("script"); newscript.onerror = loaderror; if (onloadfunc...
HTMLSelectElement.form - Web APIs
ml <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" returns the type of the calling form element. for select, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. ...
HTMLSelectElement.selectedOptions - Web APIs
pepperoni pizza</option> <option value="5">taco</option> </select> <br> <button name="order" id="order"> order now </button> <p id="output"> </p> the <select> element is set to allow multiple items to be selected, and it is 7 rows tall. note also the <button>, whose role it is to trigger fetching the htmlcollection of selected elements using the selected property. ...
HTMLTableCellElement - Web APIs
he cell is in a row group. the empty string ("") the header cell has no predefined scope; the user agent will establish the scope based on contextual clues. methods no specific method; inherits methods from its parent, htmlelement. deprecated properties warning: these properties have been deprecated and should no longer be used. they are documented primarily to help understand older code bases. htmltablecellelement.align a domstring containing an enumerated value reflecting the align attribute. it indicates the alignment of the element's contents with respect to the surrounding context. the possible values are "left", "right", and "center". htmltablecellelement.axis a domstring containing a name grouping cells in virtual. it reflects the obsolete axis attribute. html...
HTMLVideoElement - Web APIs
urce in css pixels, or 0 if no media is available yet. htmlvideoelement.width is a domstring that reflects the width html attribute, which specifies the width of the display area, in css pixels. gecko-specific properties htmlvideoelement.mozparsedframes read only returns an unsigned long with the count of video frames that have been parsed from the media resource. htmlvideoelement.mozdecodedframes read only returns an unsigned long with the count of parsed video frames that have been decoded into images. htmlvideoelement.mozpresentedframes read only returns an unsigned long with the count of decoded frames that have been presented to the rendering pipeline for painting. htmlvideoelement.mozpaintedframes read only returns an unsigned long with the count of presented frames...
Drag Operations - Web APIs
(line => !line.startswith("#")) .foreach(line => { const link = document.createelement("a"); link.href = line; link.textcontent = line; event.target.appendchild(link); }) event.preventdefault(); } this example inserts a link from the dragged data. as the name implies, the text/uri-list type actually may contain a list of urls, each on a separate line. the above code uses split to break the string into lines, then iterates over the list of lines, and inserts each as a link into the document. (note also that links starting with a number sign (#) are skipped, as these are comments.) for simple cases, you can use the special type url just to retrieve the first valid url in the list. for example: const link = event.datatransfer.getdata("url"); this eliminates...
HTML Drag and Drop API - Web APIs
ms. additionally, see the datatransfer reference page for all of the gecko-specific properties and gecko-specific methods. the basics this section is a summary of the basic steps to add drag-and-drop functionality to an application. ...
Headers - Web APIs
Web › API › Headers
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 if you try to pass in a reference to a name that isn't a valid http header name. the mutation operations will throw a typeerror if the header has an immutable guard. in any other failure case they fail silently. note: when header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicat...
History.pushState() - Web APIs
Web › API › History › pushState
in as the current url. in contrast, setting window.location keeps you at the same document only if you modify only the hash. you don't have to change the url if you don't want to. in contrast, setting window.location = "#foo"; only creates a new history entry if the current hash isn't #foo. you can associate arbitrary data with your new history entry. with the hash-based approach, you need to encode all of the relevant data into a short string. note that pushstate() never causes a hashchange event to be fired, even if the new url differs from the old url only in its hash. examples this creates a new browser history state setting the state, title, and url. javascript const state = { 'page_id': 1, 'user_id': 5 } const title = '' const url = 'hello-world.html' history.pushstate(state, ti...
History.state - Web APIs
Web › API › History › state
the history.state property returns a value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. syntax const currentstate = history.state value the state at the top of the history stack. the value is null until the pushstate() or replacestate() method is used. examples the code below logs the value of history.state before using the pushstate() method to push a value to the history. the next line logs the value to the console again, showing that history.state now has a value. // should be null because we haven't modified the history stack yet console.log(`history.state before pushstate: ${history.state}`); // now push something on the stack history.pushstate({name: 'example'}, "pushstate example", 'page3...
Working with the History API - Web APIs
in as the current url. in contrast, setting window.location keeps you at the same document only if you modify only the hash. you don't have to change the url if you don't want to. in contrast, setting window.location = "#foo"; creates a new history entry only if the current hash isn't #foo. you can associate arbitrary data with your new history entry. with the hash-based approach, you need to encode all of the relevant data into a short string. if title is subsequently used by browsers, this data can be utilized (independent of, say, the hash). note that pushstate() never causes a hashchange event to be fired, even if the new url differs from the old url only in its hash. in a xul document, it creates the specified xul element. in other documents, it creates an element with a null names...
IDBDatabase - Web APIs
perty. close fired when the database connection is unexpectedly closed. also available via the onclose property. error fired when a request returns an error and the event bubbles up to the connection object. also available via the onerror property. versionchange fired when a database structure change was requested. also available via the onversionchange property. example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a new object store in the case that an upgrade is needed (idbdatabase). for a complete working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the idbdatabase obj...
IDBEnvironment - Web APIs
roperty, which provides access to indexeddb functionality. it is the top level indexeddb interface implemented by the window and worker objects. note: this feature is available in web workers. properties idbenvironment.indexeddb read only provides a mechanism for applications to asynchronously access capabilities of indexed databases; contains an idbfactory object. ...
IDBFactory.open() - Web APIs
Web › API › IDBFactory › open
related to this request are fired. exceptions this method may raise a domexception of the following types: exception description typeerror the value of version is zero or a negative number or not a number. example example of calling open with the current specification's version parameter: var request = window.indexeddb.open("todolist", 4); in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes // of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkiti...
IDBFactory - Web APIs
the current method to request opening a connection to a database. idbfactory.deletedatabase a method to request the deletion of a database. idbfactory.cmp a method that compares two keys and returns a result indicating which one is greater in value. idbfactory.databases a method that returns a list of all available databases, including their names and versions. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. for a full working example, see our to-do notifications app (view example live.) // in the following line, you should include the prefixes of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use ...
IDBFactorySync - Web APIs
atabase using the specified name and description. idbdatabasesync open ( in domstring name, in domstring description ) raises (idbdatabaseexception); parameters name the name for the database. description the description for the database. returns idbdatabasesync an object to access the open database. exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if the name parameter is not valid. a valid name is any string including the empty string. unknown_err if an error occurs while the database is being opened. ...
IDBObjectStore.add() - Web APIs
invalidstateerror the idbobjectstore has been deleted or removed. datacloneerror the data being stored could not be cloned by the internal structured cloning algorithm. constrainterror an insert operation failed because the primary key constraint was violated (due to an already existing record with the same primary key value). example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.ind...
IDBObjectStore.autoIncrement - Web APIs
is object store. note that every object store has its own separate auto increment counter. note: this feature is available in web workers. syntax var myautoincrement = objectstore.autoincrement; value a boolean: value meaning true the object store auto increments. false the object store does not auto increment. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.autoincrement to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = functi...
IDBObjectStore.clear() - Web APIs
which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. example in the following code snippet, we open a read/write transaction on our database and clear all the current data out of the object store using clear(). for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; /...
IDBObjectStore.createIndex() - Web APIs
it will add one single entry containing the array. locale currently firefox-only (43+), this allows you to specify a locale for the index. any sorting operations performed on the data via key ranges will then obey sorting rules of that locale (see locale-aware sorting.) you can specify its value in one of three ways: string: a string containing a specific locale code, e.g. en-us, or pl. auto: the platform default locale will be used (may be changed by user agent settings.) null or undefined: if no locale is specified, normal javascript sorting will be used — not locale-aware. return value an idbindex object: the newly created index. exceptions this method may raise a domexception of one of the following types: ...
IDBObjectStore.delete() - Web APIs
eption of the following types: exception description transactioninactiveerror this object store's transaction is inactive. readonlyerror the object store's transaction mode is read-only. invalidstateerror the object store has been deleted. dataerror the key is not a valid key or a key range. example in the following code snippet, we open a read/write transaction on our database and delete one specific record out of our object store using delete() — a sample record with the key "walk dog". for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerh...
IDBObjectStore.get() - Web APIs
ions this method may raise a domexception of one of the following types: exception description transactioninactiveerror this idbobjectstore's transaction is inactive. dataerror the key or key range provided contains an invalid key. invalidstateerror the idbobjectstore has been deleted or removed. example in the following code snippet, we open a read/write transaction on our database and get one specific record from object store using get() — a sample record with the key "walk dog". once this data object is retrieved, you could then update it using normal javascript, then put it back into the database using a idbobjectstore.put operation. for a full working example, see our to-do notifications app (view example live...
IDBObjectStore.indexNames - Web APIs
after the object store has been created, we log objectstore.indexnames to the console. ...
IDBObjectStore.keyPath - Web APIs
the keypath read-only property of the idbobjectstore interface returns the key path of this object store. if this property is null, the application must provide a key for each modification operation. note: this feature is available in web workers. syntax var mykeypath = objectstore.keypath; value any value type. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.keypath to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialise...
IDBObjectStore.name - Web APIs
store's name. invalidstateerror either the object store has been deleted or the current transaction is not an upgrade transaction; you can only rename indexes during upgrade transactions; that is, when the mode is "versionchange". transactioninactiveerror the current transaction is not active. constrainterror an object store is already using the specified name. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). after the object store has been created, we log objectstore.name to the console. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event)...
IDBObjectStore.transaction - Web APIs
after the object store has been created, we log objectstore.transaction to the console. ...
IDBOpenDBRequest.onupgradeneeded - Web APIs
note: this feature is available in web workers. ...
IDBRequest - Web APIs
ethods, but inherits methods from eventtarget. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. error fired when an error caused a request to fail. also available via the onerror property. success fired when an idbrequest succeeds. also available via the onsuccess property. example in the following code snippet, we open a database asynchronously and make a request; onerror and onsuccess functions are included to handle the success and error cases. for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being // opened successful...
IDBTransaction.abort() - Web APIs
s created during this transaction have their idbrequest.error attribute set to aborterror. note: this feature is available in web workers. syntax transaction.abort(); exceptions this method may raise a domexception of the following type: exception description invalidstateerror the transaction has already been committed or aborted. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. at the end, we simply abort any activity done under the current transaction using abort(). for a full working example, see our to-do notifications app (...
IDBTransaction.db - Web APIs
Web › API › IDBTransaction › db
the db read-only property of the idbtransaction interface returns the database connection with which this transaction is associated. note: this feature is available in web workers. syntax var mydatabase = transaction.db; value an idbdatabase object. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. at the end, we return the associated database connection using db. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = funct...
IDBTransaction.error - Web APIs
the dom standard. the exact error is one of serveral possibilities. it can be a reference to the same error as the request object that raised it, or a transaction failure (for example quotaexceedederror or unknownerror). this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the idbtransaction.abort method. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.onerror = function(event) { }; block, making use of transaction.error to help in reporting what went wrong when the transaction was...
IDBTransaction.mode - Web APIs
rsionchange allows any operation to be performed, including ones that delete and create object stores and indexes. this mode is for updating the version number of transactions that were started using idbdatabase.setversion(). transactions of this mode cannot run concurrently with other transactions. transactions in this mode are known as "upgrade transactions." example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. at the end, we simply log the mode of the current transaction using mode. for a full working example, see our to-do notifications app (view example live...
IDBTransaction.objectStore() - Web APIs
an object store. exceptions this method may raise a domexception of one of the following types: exception description notfounderror the requested object store is not in this transaction's scope. invalidstateerror the request was made on a source object that has been deleted or removed, or if the transaction has finished. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open(...
IDBTransaction.onabort - Web APIs
the onabort event handler of the idbtransaction interface handles the abort event, fired, when the current transaction is aborted via the idbtransaction.abort method. note: this feature is available in web workers. syntax transaction.onabort = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.onabort = function(event) { }; block, reporting when the transaction has been aborted. for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.index...
IDBTransaction.oncomplete - Web APIs
force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. syntax transaction.oncomplete = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.oncomplete = function(event) { }; block, which reports back when the transaction was successful. for a full working example, see ou...
IDBTransaction.onerror - Web APIs
rror event handler of the idbtransaction interface handles the error event, fired when a request returns an error and bubbles up to the transaction object. note: consider using idbtransaction.onabort instead to handle non- successful completion of the transaction. note: this feature is available in web workers. syntax transaction.onerror = function(event) { ... }; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.onerror = function(event) { }; block, making use of transaction.error to help in reporting what went wrong when the transaction was...
IDBVersionChangeEvent.newVersion - Web APIs
these events are fired via the custom idbversionchangeevent interface. ...
IDBVersionChangeEvent - Web APIs
the new version of the database in a versionchange transaction. warning: while this property is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes. see the compatibility table to know what browsers support them. methods no specific method, but inherits properties from its parent, method. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. upon a version change (after an upgradedneeded event), the success event will implement the idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the ...
IIRFilterNode - Web APIs
ies of its own; however, it inherits properties from its parent, audionode. methods inherits methods from its parent, audionode. it also has the following additional methods: getfrequencyresponse() uses the filter's current parameter settings to calculate the response for frequencies specified in the provided array of frequencies. examples you can find a simple iir filter demo live on codepen. also see the source code on github. it includes some different coefficient values for different lowpass frequencies — you can change the value of the filternumber constant to a value between 0 and 3 to check out the different available effects. also see our using iir filters guide for a full explanation. specifications specification status comment web audio apithe...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
the imagebitmaprenderingcontext.transferfromimagebitmap() method displays the given imagebitmap in the canvas associated with this rendering context. the ownership of the imagebitmap is transferred to the canvas as well. this method was previously named transferimagebitmap(), but was renamed in a spec change. the old name is being kept as an alias to avoid code breakage. syntax void imagebitmaprenderingcontext.transferfromimagebitmap(bitmap) parameters bitmap an imagebitmap object to transfer. examples html <canvas id="htmlcanvas"></canvas> javascript var htmlcanvas = document.getelementbyid("htmlcanvas").getcontext("bitmaprenderer"); // draw a webgl scene offscreen var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ... some dra...
ImageBitmapRenderingContext - Web APIs
is available in both the window and the worker context. methods imagebitmaprenderingcontext.transferfromimagebitmap() displays the given imagebitmap in the canvas associated with this rendering context. ownership of the imagebitmap is transferred to the canvas. this was previously named transferimagebitmap(), but was renamed in a spec change. the old name is being kept as an alias to avoid code breakage. specifications specification status comment html living standardthe definition of 'imagebitmaprenderingcontext' in that specification. living standard ...
ImageCapture - Web APIs
at resolves with a photocapabilities object containing the ranges of available configuration options. imagecapture.getphotosettings() returns a promise that resolves with a photosettings object containing the current photo configuration settings. imagecapture.grabframe() takes a snapshot of the live video in a mediastreamtrack, returning an imagebitmap, if successful. example the following code is taken from chrome's grab frame - take photo sample. since imagecapture requires some place to capture an image from, the example below starts with a device's media device (in other words a camera). this example shows, roughly, a mediastreamtrack extracted from a device's mediastream. the track is then used to create an imagecapture object so that takephoto() and grabframe() can be called. fin...
IndexedDB API - Web APIs
custom interface: idbversionchangeevent the idbversionchangeevent interface indicates that the version of the database has changed, as the result of an idbopendbrequest.onupgradeneeded event handler function. obsolete interfaces an early version of the specification also defined the following, now removed, interfaces. they are still documented in case you need to update previously written code: idbversionchangerequest represents a request to change the version of a database. the way to change the version of the database has since changed (by calling idbfactory.open without also calling idbdatabase.setversion), and the interface idbopendbrequest now has the functionality of the removed idbversionchangerequest. idbdatabaseexception represents exception conditions that can be e...
compareVersion - Web APIs
wer) minor number than version. 4 registryname has a larger (newer) major number than version. the following constants can be used to check the value returned by compareversion: int major_diff = 4; int minor_diff = 3; int rel_diff = 2; int bld_diff = 1; int equal = 0; in communicator 4.5, the following constants are defined and available for checking the value returned by compareversion: <code>installtrigger.major_diff installtrigger.minor_diff installtrigger.rel_diff installtrigger.bld_diff installtrigger.equal </code> description the compareversion method compares the version of an installed file or package with a specified version. it is often used as a check against which to initiate the installation process. if registryname is not found in the client version registry or if regi...
enabled - Web APIs
software installation is enabled for this client machine. method of installtrigger object syntax boolean enabled (); parameters none returns true if software installation is enabled for this client machine; otherwise, false. ...
InstallTrigger - Web APIs
ntations and the behavior may change in the future. the installtrigger interface is an interesting outlier in the apps api; it's included in this api but are inherited from the old mozilla xpinstall technology for installing add-ons. it is used for triggering the download and installation of an add-on (or anything packaged in an .xpi file) from a web page, using javascript code to kick off the install process. note: this article needs to be updated somewhat. overview for very simple installations, the install methods on the installtrigger object may be all that's needed in the installation script. for more complex installations, you may need to use the install and/or file installation objects. in either case, you must trigge...
IntersectionObserverEntry.intersectionRect - Web APIs
ibes the part of the target element that's currently visible within the root's intersection rectangle. this rectangle is computed by taking the intersection of boundingclientrect with each of the target's ancestors' clip rectangles, with the exception of the intersection root itself. example in this simple example, an intersection callback stores the intersection rectangle for later use by the code that draws the target elements' contents, so that only the visible area is redrawn. function intersectioncallback(entries) { entries.foreach(function(entry) { refreshzones.push({ element: entry.target, rect: entry.intersectionrect }); }); } specifications specification status comment intersection observerthe definition of 'intersectionobserverent...
Keyboard.lock() - Web APIs
Web › API › Keyboard › lock
the lock() method of the keyboard interface returns a promise after enabling the capture of keypresses for any or all of the keys on the physical keyboard. this method can only capture keys that are granted access by the underlying operating system. syntax var promise = keyboard.lock([keycodes[]]) parameters keycodes optional an array of one or more key codes to lock. if no keycodes are provided all keys will be locked. a list of valid code values is found in the ui events keyboardevent code values spec. return value a promise. examples capturing all keys the following example captures all keypresses. navigator.keyboard.lock(); capturing specific keys the following example captures the "w", "a", "s", and "d" keys. it captures these keys regardless of which modifiers ...
KeyboardEvent.altKey - Web APIs
rdevent.altkey read-only property is a boolean that indicates if the alt key (option or ⌥ on os x) was pressed (true) or not (false) when the event occured. syntax var altkeypressed = instanceofkeyboardevent.altkey return value boolean examples <html> <head> <title>altkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key keydown: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "alt key keydown: " + e.altkey + "\n" ); } </script> </head> <body onkeydown="showchar(event);"> <p> press any character key, with or without holding down the alt key.<br /> you can also use the shift key together with the alt key. </p> </body> </html> specifications specification status comment document...
KeyboardEvent.location - Web APIs
ssible location on the keyboard. dom_key_location_right 2 the key was the right-hand version of the key; for example, the right-hand control key is pressed on a standard 101 key us keyboard. this value is only used for keys that have more than one possible location on the keyboard. dom_key_location_numpad 3 the key was on the numeric keypad, or has a virtual key code that corresponds to the numeric keypad. note: when numlock is locked, gecko always returns dom_key_location_numpad for the keys on the numeric pad. otherwise, when numlock is unlocked and the keyboard actually has a numeric keypad, gecko always returns dom_key_location_numpad too. on the other hand, if the keyboard doesn't have a keypad, such as on a notebook computer, some keys become numpa...
KeyboardLayoutMap.get() - Web APIs
syntax var value = keyboardlayoutmap.get(key) parameters key the key of the item to return from the map. return value the value of the specified key. example the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard. ...
KeyboardLayoutMap.has() - Web APIs
syntax var aboolean = keyboardlayoutmap.has(key) parameters key the key of an element to search for in the map. ...
KeyboardLayoutMap - Web APIs
properties keyboardlayoutmap.entries read only returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). ...
LinearAccelerationSensor.LinearAccelerationSensor() - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
LinearAccelerationSensor.x - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var xlinearaccelerationsensor = linearaccelerationsensor.x value a number. ...
LinearAccelerationSensor.y - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var yacceleration = accelerometer.y value a number. example linear acceleration is typically read in the sensor.onreading event callback. ...
LinearAccelerationSensor.z - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var zacceleration = accelerometer.z value a number. example linear acceleration is typically read in the sensor.onreading event callback. ...
LinearAccelerationSensor - Web APIs
the linearaccelerationsensor interface of the sensor apis provides on each reading the acceleration applied to the device along all three axes, but without the contribution of gravity. to use this sensor, the user must grant permission to the 'accelerometer' device sensor through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor linearaccelerationsensor.linearaccelerationsensor() creates a new linearaccelerationsensor object. properties linearaccelerationsensor.x read only returns a double containing the linear acceleration of the device along the device's x axis. l...
LocalMediaStream - Web APIs
almediastream interface was part of the media capture and streams api, representing a stream of data being generated locally (such as by getusermedia(). however, getusermedia() now returns a mediastream instead, and this interface has been removed from the specification. warning: this interface is no longer available in any mainstream browser. do not use localmediastream; you need to update any code that does use it as soon as possible or your content or application will stop working. see stopping a video stream in mediastreamtrack to learn how. all other functionality is found in mediastream. the primary reason for this interface to exist was to add a stop() method to its mediastream parent interface. however, control over playback of media has been moved to the individual mediastreamtrac...
Location: hash - Web APIs
Web › API › Location › hash
if the url does not have a fragment identifier, this property contains an empty string, "". ...
Location: origin - Web APIs
Web › API › Location › origin
e.g "blob:https://mozilla.org" will have "https://mozilla.org". note: this feature is available in web workers. ...
Locks.name - Web APIs
Web › API › Lock › name
the name read-only property of the lock interface returns the name passed to lockmanager.request selected when the lock was requested. the name of a lock is passed by script when the lock is requested. the name is selected by the developer to represent an abstract resource for which use is being coordinated across multiple tabs, workers, or other code within the origin. for example, if only one tab of a web application should be synchronizing network resources with an offline database, it could use a lock name such as "net_db_sync". syntax var name = lock.name value a domstring. example the following examples show how the name property passed in the call to lockmanager.request(). lockmanager is the object returned by navigator.locks. navigator.locks.request("net_db_sync", show_lock...
Magnetometer.Magnetometer() - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
Magnetometer.x - Web APIs
Web › API › Magnetometer › x
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometerx = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer.y - Web APIs
Web › API › Magnetometer › y
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometery = magnetometer.x value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer.z - Web APIs
Web › API › Magnetometer › z
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax var magnetometerz = magnetometer.z value a number. example the magnetometer is typically read in the sensor.onreading event callback. in the example below this occurs sixty times a second. ...
Magnetometer - Web APIs
this is not something that would ever be shown to a user. ...
MediaCapabilities - Web APIs
the information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient. the information is accessed through the mediacapabilities property of the navigator interface. ...
MediaDecodingConfiguration - Web APIs
t is meant to be used for a plain file playback. media-source: represents a configuration that is meant to be used for playback of a mediasource. a media configuration — a videoconfiguration or audioconfiguration dictionary. examples //create media configuration to be tested const mediaconfig = { type : 'file', // or 'media-source' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames making up that 1s. } }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this con...
MediaEncodingConfiguration - Web APIs
.g. using mediarecorder. transmission — represents a configuration meant to be transmitted over electronic means (e.g. using rtcpeerconnection). a media configuration — a videoconfiguration audioconfiguration dictionary. examples //create media configuration to be tested const mediaconfig = { type : 'record', // or 'transmission' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames making up that 1s. } }; // check support and performance navigator.mediacapabilities.encodinginfo(mediaconfig).then(result => { console.log('this con...
MediaQueryList.media - Web APIs
query. syntax var media = mediaquerylist.media; value a domstring representing a serialized media query. examples this example runs the media query (max-width: 600px) and displays the value of the resulting mediaquerylist's media property in a <span>. javascript let mql = window.matchmedia('(max-width: 600px)'); document.queryselector(".mq-value").innertext = mql.media; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the result's media property. html <span class="mq-value"></span> a simple <span> to receive the output. css .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } result specifications ...
MediaQueryList - Web APIs
you can find other examples on the individual property and method pages. specifications specification status comment css object model (cssom) view modulethe definition of 'mediaquerylist' in that specification. working draft initial definition ...
MediaRecorder: error event - Web APIs
bubbles no cancelable no interface mediarecordererrorevent event handler property onerror for details of the all the possible errors see the documentation for the event handler property: onerror. ...
MediaRecorder.onerror - Web APIs
s obtained using getusermedia() when the user denies permission to use an input device. this also happens when a mediastreamtrack within the stream is marked as isolated due to the peeridentity constraint on the source stream. notsupportederror an attempt was made to instantiate a mediarecorder using a mime type that isn't supported on the user's device; one or more of the requested container, codecs, or profiles as well as other information may be invalid. unknownerror an non-security related error occurred that cannot otherwise be categorized. recording stops, the mediarecorder's state becomes inactive, one last dataavailable event is sent to the mediarecorder with the remaining received data, and finally a stop event is sent. these errors may occur either directly because of a call t...
MediaRecorder.onpause - Web APIs
the pause event is thrown as a result of the mediarecorder.pause() method being invoked. syntax mediarecorder.onpause = function(event) { ... } mediarecorder.addeventlistener('pause', function(event) { ... }) example ... ...
MediaRecorder.onresume - Web APIs
the resume event is thrown as a result of the mediarecorder.resume() method being invoked. syntax mediarecorder.onresume = function(event) { ... } mediarecorder.addeventlistener('resume', function(event) { ... }) example ... ...
MediaRecorder.onstart - Web APIs
the start event is thrown as a result of the mediarecorder.start() method being invoked. at this point, the data starts being gathered into a blob. syntax mediarecorder.onstart = function(event) { ... } mediarecorder.addeventlistener('start', function(event) { ... }) example ... record.onclick = function() { mediarecorder.start(); console.log("recorder started"); } mediarecorder.onstart = function() { // do something in response to // recording being started } ... ...
MediaRecorder.onwarning - Web APIs
syntax mediarecorder.onwarning = function(event) { ... } mediarecorder.addeventlistener('warning', function(event) { ... }) example ... ...
MediaSession.setPositionState() - Web APIs
call this method on the navigator object's mediasession object. ...
MediaSource.activeSourceBuffers - Web APIs
a sourcebufferlist containing the sourcebuffer objects for each of the active tracks. ...
MediaSource.duration - Web APIs
ebuffers are being updated (i.e. their sourcebuffer.updating property is true.) example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); mediasource.duration = 120; video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; ... specifications specification status comment media source extensionsthe d...
MediaSource.removeSourceBuffer() - Web APIs
bject. syntax mediasource.removesourcebuffer(sourcebuffer); parameters sourcebuffer the sourcebuffer object to be removed. return value undefined exceptions exception explanation notfounderror the supplied sourcebuffer doesn't exist in mediasource.sourcebuffers. examples for (i = 0; i < 10; i++) { var sourcebuffer = mediasource.addsourcebuffer(mimecodec); } mediasource.removesourcebuffer(mediasource.sourcebuffers[0]); specifications specification status comment media source extensionsthe definition of 'removesourcebuffer()' in that specification. recommendation initial definition. ...
MediaSource.sourceBuffers - Web APIs
syntax var mysourcebuffers = mediasource.sourcebuffers; value a sourcebufferlist. example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); console.log(mediasource.sourcebuffers); // will contain the source buffer that was added above video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; ... specifications speci...
MediaStream.onaddtrack - Web APIs
ance. this happens when a new track of any kind is added to the media stream. this event is fired when the browser adds a track to the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source. the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by calling addtrack()). syntax mediastream.onaddtrack = eventhandler; value this should be set to a function which you provide that accepts as input a mediastreamtrackevent object representing the addtrack event which has occurred. the mediastreamtrack representing the track which was added is specified in the event's track property. example this examp...
MediaStream.onremovetrack - Web APIs
is happens when a track of any kind is removed from the media stream. this event is fired when the browser removes a track from the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source. the removetrack event does not get fired when javascript code explicitly removes tracks from the stream (by calling removetrack()). syntax mediastream.onremovetrack = eventhandler; value this should be set to a function which you provide that accepts as input a mediastreamtrackevent object representing the removetrack event which has occurred. the mediastreamtrack representing the track which was removed is specified in the event's track property. exa...
MediaStreamAudioSourceNode - Web APIs
better-defined rules for how it chooses the track to output. if you do chooose to use mediastreamaudiosourcenode, you should keep the following in mind. track ordering for the purposes of the mediastreamtrackaudiosourcenode interface, the order of the audio tracks on the stream is determined by taking the tracks whose kind is audio, then sorting the tracks by their id property's values, in unicode code point order (essentially, in alphabetical or lexicographical order, for ids which are simple alphanumeric strings). the first track, then, is the track whose id comes first when the tracks' ids are all sorted by unicode code point. however, it's important to note that the rule establishing this ordering was added long after this interface was first introduced into the web audio api. as suc...
MediaStreamTrack.getConstraints() - Web APIs
nstraints(). the properties in the returned object are listed in the same order as when they were set, and only properties specifically set by the site or app are included. note: the returned set of constraints doesn't necessarily describe the actual state of the media. even if any of the constraints couldn't be met, they are still included in the returned object as originally set by the site's code. to get the currently active settings for all constrainable properties, you should instead call getsettings(). example this example obtains the current constraints for a track, sets the facingmode, and applies the updated constraints. function switchcameras(track, camera) { const constraints = track.getconstraints(); constraints.facingmode = camera; track.applyconstraints(constraints); ...
MediaStreamTrack.getSettings() - Web APIs
ails on how to work with constrainable properties. syntax const settings = track.getsettings() returns a mediatracksettings object describing the current configuration of the track's constrainable properties. note: the returned object identifies the current values of every constrainable property, including those which are platform defaults rather than having been expressly set by the site's code. to instead fetch the most-recently established constraints for the track's properties, as specified by the site's code, use getconstraints(). specifications specification status comment media capture and streamsthe definition of 'getsettings()' in that specification. candidate recommendation initial definition. ...
MediaStreamTrack - Web APIs
o tracks, but other track types may exist as well. properties in addition to the properties listed below, mediastreamtrack has constrainable properties which can be set using applyconstraints() and accessed using getconstraints() and getsettings(). see capabilities, constraints, and settings to learn how to correctly work with constrainable properties. not doing so correctly will result in your code being unreliable. mediastreamtrack.contenthint a string that may be used by the web application to provide a hint as to what type of content the track contains to guide how it should be treated by api consumers. mediastreamtrack.enabled a boolean whose value of true if the track is enabled, that is allowed to render the media source stream; or false if it is disabled, that is not rendering ...
MediaTrackConstraints.logicalSurface - Web APIs
ia has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's logicalsurface object. for example, if your app needs to know if the selected display surface is a logical one: let islogicalsurface = displaystream.getvideotracks()[0].getsettings().logicalsurface; following this code, islogicalsurface is true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, or may even be entirely offscreen. specifications specification status comment screen capturethe definition of 'mediatrackconstraints.logicalsurface' in that specification. working draft initial specification. ...
MediaTrackSettings.noiseSuppression - Web APIs
e was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.noisesuppression property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). noise suppression automatically filters the audio to remove background noise, hum caused by equipment, and the like from the sound before delivering it to your code. this feature is typically used on microphones, although it is technically possible it could be provided by other input sources as well. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.noisesuppression as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since brows...
MediaTrackSupportedConstraints.frameRate - Web APIs
specifications specification status comment media capture and streamsthe definition of 'framerate' in that specification. candidate recommendation initial specification. ...
Media Source API - Web APIs
lients (such as those using dash or hls) to be built on its extensible api. creating assets that work with mse in modern browsers is a laborious process, taking significant time, computing power, and energy. the usage of external utilities to massage the content into a suitable format is required. while browser support for the various media containers with mse is spotty, usage of the h.264 video codec, aac audio codec, and mp4 container format is a common baseline. mse also provides an api for runtime detection of container and codec support. if you do not require explicit control of video quality over time, the rate at which content is fetched, or the rate at which memory is evicted, then the <video> and <source> tags may well be a simple and adequate solution. dash dynamic adaptive strea...
Media Capture and Streams API (Media Stream) - Web APIs
iastreamtrackevent mediatrackconstraints mediatracksettings mediatracksupportedconstraints overconstrainederror url early versions of the media capture and streams api specification included separate audiostreamtrack and videostreamtrack interfaces—each based upon mediastreamtrack—which represented streams of those types. these no longer exist, and you should update any existing code to instead use mediastreamtrack directly. events addtrack ended muted overconstrained removetrack started unmuted guides and tutorials the articles below provide additional guidance and how-to information that will help you learn to use the api, and how to perform specific tasks that you may wish to handle. capabilities, constraints, and settingsthe twin concepts of cons...
MerchantValidationEvent() - Web APIs
nt method identifier for the payment handler being used. this is an empty string by default. validationurl optional the url from which to retrieve payment handler specific verification information used to validate the merchant. this is an empty string by default. return value a newly-created merchantvalidationevent providing the information that needs to be delivered to the client-side code to present to the user agent by calling complete(). exceptions typeerror the string specified as validationurl could not be parsed as a url. rangeerror the specified methodname does not correspond to a known and supported merchant or is not a well-formed standard payment method identifier. specifications specification status comment payment request apithe definit...
MessageChannel() - Web APIs
the messagechannel() constructor of the messagechannel interface returns a new messagechannel object with two new messageport objects. note: this feature is available in web workers. syntax var channel = new messagechannel(); returns a newly created messagechannel object. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = document.queryselect...
MessageChannel.port1 - Web APIs
port1 read-only property of the messagechannel interface returns the first port of the message channel — the port attached to the context that originated the channel. note: this feature is available in web workers. syntax channel.port1; value a messageport object, the first port of the channel, that is the port attached to the context that originated the channel. example in the following code block, you can see a new channel being created using the messagechannel() constructor. when the <iframe> has loaded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated...
MessageChannel.port2 - Web APIs
ce returns the second port of the message channel — the port attached to the context at the other end of the channel, which the message is initially sent to. note: this feature is available in web workers. syntax channel.port2; value a messageport object representing the second port of the channel, the port attached to the context at the other end of the channel. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check ...
MessageEvent - Web APIs
s anymore — use the messageevent() constructor instead. examples in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows. the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property. if the onmessage event is attached using addeventlistener, the port is manually started using its start() method: myworker.po...
MessagePort.close() - Web APIs
Web › API › MessagePort › close
the close() method of the messageport interface disconnects the port, so it is no longer active. this stops the flow of messages to that port. note: this feature is available in web workers. syntax port.close() returns void. parameters none. example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using eventtarget.addeventlistener. channel.port1.addeventlistener('message', handlemessage, false); function handlemessage(e) { para.innerhtml = e.data; textinput.value = ''; } channel.port1.start(); you could stop messages being sent at any time using channel.port1.close(); specifications specification status comment html living standardthe definition of 'close()' in that specific...
MessagePort.onmessage - Web APIs
the onmessage event handler of the messageport interface is an eventlistener, called whenever an messageevent of type message is fired on the port — that is, when the port receives a message. note: this feature is available in web workers. syntax channel.onmessage = function() { ... }; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. var channel = new messagechannel(); var para = do...
MessagePort.postMessage() - Web APIs
rns void. parameters message the message you want to send through the channel. this can be of any basic data type. multiple data items can be sent as an array. transferlist optional transferable objects to be transferred — these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context. example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using window.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check w...
MessagePort.start() - Web APIs
Web › API › MessagePort › start
the start() method of the messageport interface starts the sending of messages queued on the port. this method is only needed when using eventtarget.addeventlistener; it is implied when using messagechannel.onmessage. note: this feature is available in web workers. syntax port.start() returns void. parameters none. ...
Microsoft API extensions - Web APIs
r 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 msfirstpaint pinned sites apis mssitemodeevent mssitemodejumplistitem...
MouseEvent.button - Web APIs
Web › API › MouseEvent › button
obsolete compared to document object model (dom) level 2 events specification, the return value can be negative. document object model (dom) level 2 events spec...
msRealTime - Web APIs
xplorer and microsoft edge. syntax ptr = object.msrealtime; value boolean value set to true indicates that low-latency playback will be enabled on the media element. low-latency playback is useful in communication and some gaming scenarios, but is more demanding on power consumption and less reliable for smooth media playback. you must set the msrealtime before setting the src property in code. msrealtime should not be used in non-real-time or non-communication scenarios, such as audio and/or video playback, as this can affects playback startup latency of audio and video playback. ...
MutationObserver.MutationObserver() - Web APIs
} }); } the callback() function is invoked when the observer sees changes matching the configuration of the observation request specified when calling observe() to begin watching the dom. the kind of change that took place (either a change to the list of children, or a change to an attribute) is detected by looking at the mutation.type property. creating and starting the observer this code actually sets up the observation process. const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true, // omit (or set to false) to observe only changes to the parent node subtree: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); the desired subtree is located by finding an...
MutationObserver.takeRecords() - Web APIs
ryselector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takerecords(); observer.disconnect(); if (mutations) { callback(mutations); } the code in lines 12–17 fetches any unprocessed mutation records, then invokes the callback with the records so that they can be processed. this is done immediately prior to calling disconnect() to stop observing the dom. specifications specification status comment domthe definition of 'mutationobserver.takerecords()' in that specification. living standard ...
MutationObserver - Web APIs
s called again. observe() configures the mutationobserver to begin receiving notifications through its callback function when dom changes matching the given options occur. takerecords() removes all pending notifications from the mutationobserver's notification queue and returns them in a new array of mutationrecord objects. mutation observer & customize resize event listener & demo https://codepen.io/webgeeker/full/yjrzgg/ example the following example was adapted from this blog post. // select the node that will be observed for mutations const targetnode = document.getelementbyid('some-id'); // options for the observer (which mutations to observe) const config = { attributes: true, childlist: true, subtree: true }; // callback function to execute when mutations are observed const ...
MutationObserverInit.attributeFilter - Web APIs
t when the mutationobserver() constructor is used to create a new mutationobserver, attribute monitoring is enabled regardless of whether or not the attributes property is true. example in this example, a mutation observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room. this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline. function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": switch(mutation.attributename) { case "status": userstatuschanged(mutation.target.username, mutation.target.status); b...
MutationObserverInit.attributeOldValue - Web APIs
n reporting attribute value changes. if true, oldvalue is set accordingly. if false, it is not. when using attributeoldvalue, setting the attributes option to true is optional. example in this example, a mutation observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room. this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline. function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mu...
MutationObserverInit.attributes - Web APIs
arget node (false). if you set either attributefilter or attributeoldvalue to true, attributes is automatically assumed to be true, even if you don't expressly set it as such. example in this example, a mutation observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room. this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline. function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mu...
NDEFRecord.data - Web APIs
Web › API › NDEFRecord › data
the data property of the ndefrecord interface is dataview providing access to the payload data of the record. it provides access to a raw content of the record and thus data consumer might need to decode it. syntax ndefrecord.data value a dataview that contains encoded payload data of the record. specifications specification status comment web nfc, ndefrecord.data draft initial definition. ...
NDEFRecord.encoding - Web APIs
syntax ndefrecord.encoding value a usvstring which can be one of the following: "utf-8", "utf-16", "utf-16le" or "utf-16be". ...
NDEFRecord - Web APIs
e identificator of the record. note: the uniqueness of the identifier is enforced only by the generator of the record. ndefrecord.data read only represents the payload of the record. ndefrecord.encoding read only represents the encoding name used for encoding the payload in the case it is textual data. ndefrecord.lang read only represents a language tag of the content, if it was encoded. methods ndefrecord.torecords() coverts ndefrecord.data to sequence of records. specifications specification status comment web nfc, ndefrecord draft initial definition. ...
Navigator.getBattery() - Web APIs
the getbattery() method provides information about the system's battery. it returns a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status. this implements the battery status api; see that documentation for additional details, a guide to using the api, and sample code. note: in some browsers access to this feature is controlled by feature-policy directive battery. syntax var batterypromise = navigator.getbattery(); return value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state. exceptions this method doesn't throw true exceptions; instead, it rejects the returned promise, pass...
Navigator.getUserMedia() - Web APIs
e video here. }; } errorcallback when the call fails, the function specified in the errorcallback is invokedwith a mediastreamerror object as its sole argument; this object is is modeled on domexception. see {anch("errors")}} below for a list of the errors which can occur. return value undefined. errors examples width and height here's an example of using getusermedia(), including code to cope with various browsers' prefixes. note that this is the deprecated way of doing it: see the examples section under the mediadevices.getusermedia() for modern examples. navigator.getusermedia = navigator.getusermedia || navigator.webkitgetusermedia || navigator.mozgetusermedia; if (navigator.getusermedia) { navigator.getusermedia({ audi...
Navigator.mediaSession - Web APIs
ent can use to share information about media it's playing and its current playback status. this information can include typical metadata such as the title, artist, and album name of the song being played as well as potentially one or more images containing things like album art, artist photos, and so forth. example in this example, metadata is submitted to the mediasession object. note that the code begins by ensuring that the navigator.mediasession property is available before attempting to use it. if ("mediasession" in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); } specifications specification status comment ...
Navigator.oscpu - Web APIs
Web › API › Navigator › oscpu
specifications specification status comment html living standardthe definition of 'navigatorid: oscpu' in that specification. living standard initial definition ...
Navigator.registerProtocolHandler() - Web APIs
om/?burger=%s", "burger handler"); this creates a handler that lets web+burger: links send the user to your site, inserting the accessed burger url into the %s placeholder. this script must be run from the same origin as the handler url (so any page at https://burgers.example.com), and the handler url must be http or https. the user will be notified that your code asked to register the protocol handler, so that they can decide whether or not to allow it. see the screenshot below for an example on google.co.uk: specifications specification status comment html living standardthe definition of 'registerprotocolhandler()' in that specification. living standard living standard ...
Navigator.requestMediaKeySystemAccess() - Web APIs
ribed by keysystem and supportedconfigurations exceptions in case of an error, the returned promise is rejected with a domexception whose name indicates what kind of error occurred. notsupportederror either the specified keysystem isn't supported by the platform or the browser, or none of the configurations specified by supportedconfigurations can be satisfied (if, for example, none of the codecs specified in contenttype are available). typeerror either keysystem is an empty string or the supportedconfigurations array is empty. specifications specification status comment encrypted media extensionsthe definition of 'requestmediakeysystemaccess()' in that specification. recommendation initial definition ...
Navigator.serviceWorker - Web APIs
the navigator.serviceworker read-only property returns the serviceworkercontainer object for the associated document, which provides access to registration, removal, upgrade, and communication with the serviceworker. the feature may not be available in private mode. syntax var workercontainerinstance = navigator.serviceworker; value serviceworkercontainer examples this code checks if the browser supports service workers. if ('serviceworker' in navigator) { // supported! } specifications specification status comment service workersthe definition of 'navigator.serviceworker' in that specification. working draft initial definition. ...
Navigator.share() - Web APIs
Web › API › Navigator › share
d. files: a " frozenarray" representing the array of file to be shared. return value a promise that will be fulfilled once a user has completed a share action (usually the user has chosen an application to share to). it will reject immediately if the data parameter is not correctly specified, and will also reject if the user cancels sharing. examples in our web share test (see the source code) there is a button which, when clicked, invokes the web share api to share mdn's url. the javascript looks like this: const sharedata = { title: 'mdn', text: 'learn web development on mdn!', url: 'https://developer.mozilla.org', } const btn = document.queryselector('button'); const resultpara = document.queryselector('.result'); // must be triggered some kind of "user activation" btn.add...
NavigatorID.appVersion - Web APIs
98; en-us; rv:0.9.2) gecko/20010725 netscape 6/6.1"), but you should be aware of how easy it is to change the user agent string and "spoof" other browsers, platforms, or user agents, and also how cavalier the browser vendor themselves are with these properties. the window.navigator.appversion, window.navigator.appname and window.navigator.useragent properties have been used in "browser sniffing" code: scripts that attempt to find out what kind of browser you are using and adjust pages accordingly. this lead to the current situation, where browsers had to return fake values from these properties in order not to be locked out of some websites. specifications specification status comment html living standardthe definition of 'navigatorid.appversion' in that specific...
NavigatorLanguage.language - Web APIs
the navigatorlanguage.language read-only property returns a string representing the preferred language of the user, usually the language of the browser ui. syntax const lang = navigator.language value a domstring. lang stores a string representing the language version as defined in bcp 47. examples of valid language codes include "en", "en-us", "fr", "fr-fr", "es-es", etc. note that in safari on ios prior to 10.2, the country code returned is lowercase: "en-us", "fr-fr" etc. example if (/^en\b/.test(navigator.language)) { dolangselect(window.navigator.language); } specifications specification status comment html living standardthe definition of 'navigatorlanguage: language' in that specification. living standard initial definition ...
NetworkInformation.onchange - Web APIs
syntax netinfo.onchange = function() { ... } examples // get the connection type. var type = navigator.connection.type; function changehandler(e) { // handle change of connection type here. ...
Node.baseURIObject - Web APIs
g. this property exists on all nodes (html, xul, svg, mathml, etc.), but only if the script trying to use it has universalxpconnect privileges. see node.baseuri for details on what the base url is. syntax uriobj = node.baseuriobject value an nsiuri. this property is read-only; attempting to write to it will throw an exception. in addition, this property may only be accessed from privileged code. specification not in any specification. ...
Node.getRootNode() - Web APIs
Web › API › Node › getRootNode
return an htmldocument object representing the entire page. calling it on an element inside a shadow dom will return the associated shadowroot. examples the first simple example returns a reference to the html/document node: rootnode = node.getrootnode(); this more complex example shows the difference between returning a normal root, and a root incuding the shadow root. ...
Node.isConnected - Web APIs
Web › API › Node › isConnected
* no warranty expressed or implied. use at your own risk. */ if (!('isconnected' in node.prototype)) { object.defineproperty(node.prototype, 'isconnected', { get() { return ( !this.ownerdocument || !( this.owner...
Node.nodePrincipal - Web APIs
specifications not in any specification. this is a firefox-specific property. ...
Node.nodeType - Web APIs
Web › API › Node › nodeType
lement("p"); p.textcontent = "once upon a time…"; p.nodetype === node.element_node; // true p.firstchild.nodetype === node.text_node; // true comments this example checks if the first node inside the document element is a comment, and displays a message if not. var node = document.documentelement.firstchild; if (node.nodetype !== node.comment_node) { console.warn("you should comment your code!"); } specifications specification status comment domthe definition of 'node.nodetype' in that specification. living standard deprecated attribute_node, entity_reference_node and notation_node types. document object model (dom) level 3 core specificationthe definition of 'node.nodetype' in that specification. obsolete no changes. docume...
NodeList.prototype.forEach() - Web APIs
Web › API › NodeList › forEach
div"); let kid1 = document.createelement("p"); let kid2 = document.createtextnode("hey"); let kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); let list = node.childnodes; list.foreach( function(currentvalue, currentindex, listobj) { console.log(currentvalue + ', ' + currentindex + ', ' + this); }, 'mythisarg' ); the above code results in the following: [object htmlparagraphelement], 0, mythisarg [object text], 1, mythisarg [object htmlspanelement], 2, mythisarg polyfill this polyfill adds compatibility to all browsers supporting es5: if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = function (callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < t...
Notification.lang - Web APIs
Web › API › Notification › lang
note: this feature is available in web workers. the lang read-only property of the notification interface indicates the language used in the notification, as specified in the lang option of the notification() constructor. the language itself is specified using a domstring representing a bcp 47 language tag. see the sitepoint iso 2 letter language codes page for a simple reference. syntax var language = notification.lang; value a domstring specifying the language tag. examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor. var options = { body: 'do you like my body?', lang: 'en-us' } var n = new notification('test notification',options); console.log(n.lang) // should re...
NotifyAudioAvailableEvent - Web APIs
lementations and the behavior may change in the future. the non-standard, obsolete, notifyaudioavailableevent interface defines the event sent to audio elements when the audio buffer is full. properties framebuffer read only a float32array containing the raw 32-bit floating-point audio data obtained from decoding the audio (e.g., the raw data being sent to the audio hardware vs. encoded audio). the data is a series of audio samples, each sample containing one 32-bit value per audio channel. all audio frames are normalized to contain 1024 samples by default, but could be any length between 512 and 16384 samples if the user has set a different length using the mozframebufferlength attribute. time a floating-point value indicating the time in seconds at which the first sample in...
OES_fbo_render_mipmap - Web APIs
attach any level of a texture to a framebuffer object. webgl extensions are available using the webglrenderingcontext.getextension() method. for more information, see also using extensions in the webgl tutorial. availability: this extension is only available to webgl 1. in webgl2, the functionality of this extension is available in the webgl 2 context by default. examples see the sample code in the khronos specification. specifications specification status oes_fbo_render_mipmap draft ...
OVR_multiview2 - Web APIs
; const depthstenciltex = gl.createtexture(); gl.bindtexture(gl.texture_2d_array, depthstenciltex); gl.texstorage3d(gl.texture_2d_array, 1, gl.depth32f_stencil8, 512, 512, 2); ext.framebuffertexturemultiviewovr(gl.draw_framebuffer, gl.depth_stencil_attachment, depthstenciltex, 0, 0, 2); gl.drawelements(...); // draw will be broadcasted to the layers of colortex and depthstenciltex. shader code #version 300 es #extension gl_ovr_multiview2 : require precision mediump float; layout (num_views = 2) in; in vec4 inpos; uniform mat4 u_viewmatrices[2]; void main() { gl_position = u_viewmatrices[gl_viewid_ovr] * inpos; } specifications specification status ovr_multiview2 community approved ...
OfflineAudioContext.OfflineAudioContext() - Web APIs
lar audiocontext, an offlineaudiocontext can be the target of events, therefore it implements the eventtarget interface. example const offlinectx = new offlineaudiocontext({ numberofchannels: 2, length: 44100 * 40, samplerate: 44100, }); const source = offlinectx.createbuffersource(); // etc... for a full working example, see our offline-audio-context-promise github repo (see the source code too.) specifications specification status comment web audio apithe definition of 'offlineaudiocontext()' in that specification. working draft ...
OrientationSensor.populateMatrix() - Web APIs
the populatematrix method of the orientationsensor interface populates the given target matrix with the rotation matrix based on the latest sensor reading. the rotation matrix is shown below. where: w = cos(θ/2) x = vx * sin(θ/2) y = vy * sin(θ/2) z = vz * sin(θ/2) if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. syntax orientationinstance.populatematrix(targetmatrix) because orientationsensor is a base class, populatematrix may only be read from one of its derived classes. parameters targetmatrix tbd return value undefined example // tbd specifications specification sta...
OrientationSensor - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
OscillatorNode.detune - Web APIs
illator(); oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in cents note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create an oscillator node. for applied examples/information, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in cents oscillator.start(); specifi...
OscillatorNode.frequency - Web APIs
eateoscillator(); oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz note: though the audioparam returned is read-only, the value it represents is not. value an a-rate audioparam. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe ...
OscillatorNode.onended - Web APIs
atornode interface is used to set the event handler for the ended event, which fires when the tone has stopped playing. syntax var oscillator = audioctx.createoscillator(); oscillator.onended = function() { ... }; example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.value = 440; // value in hertz oscillator.start(); // start the tone playing oscillator.stop(5); // the tone will stop again in 5 seconds. oscillator.onended = functi...
OscillatorNode.start() - Web APIs
n seconds) when the oscillator should start, in the same coordinate system as audiocontext's currenttime attribute. if a value is not included or is less than currenttime, the oscillator starts playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe...
OscillatorNode.stop() - Web APIs
the audio context time when the oscillator should stop. if a value is not included, it defaults to 0. if the time is equal to or before the current audio context time, the oscillator will stop playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.connect(audioctx.destination); oscillator.start(); oscillator.stop(audioctx.currenttime + 2); // stop 2 seconds after the current time specifications specification status comment ...
OscillatorNode.type - Web APIs
oing so automatically sets the type to custom. exceptions invalidstateerror the value custom was specified. to set a custom waveform, just call setperiodicwave(). doing so automatically sets the type for you. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe ...
OscillatorNode - Web APIs
llatornode.setwavetable() method. oscillatornode.start() specifies the exact time to start playing the tone. oscillatornode.stop() specifies the time to stop playing the tone. examples the following example shows basic usage of an audiocontext to create an oscillator node and to start playing a tone on it. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currenttime); // value in hertz oscillator.connect(audioctx.destination); oscillator.start(); specifications specification st...
PannerNode.coneInnerAngle - Web APIs
e') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
PannerNode.coneOuterAngle - Web APIs
e') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
PannerNode.coneOuterGain - Web APIs
e') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
PannerNode.distanceModel - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
PannerNode.maxDistance - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
PannerNode.orientationX - Web APIs
e') to an orientation vector const yrotationtovector = degrees => { // convert degrees to radians and offset the angle so 0 points towards the listener const radians = (degrees - 90) * (math.pi / 180); // using cosine and sine here ensures the output values are always normalised // i.e. ...
PannerNode.panningModel - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
PannerNode.positionX - Web APIs
horizontal axis (left-right). the complete vector is defined by the position of the audio source, given as (positionx, positiony, positionz), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationx, orientationy, orientationz). depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. s...
PannerNode.positionY - Web APIs
he vertical axis (top-bottom). the complete vector is defined by the position of the audio source, given as (positionx, positiony, positionz), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationx, orientationy, orientationz). depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. s...
PannerNode.positionZ - Web APIs
ind-in front of the listener). the complete vector is defined by the position of the audio source, given as (positionx, positiony, positionz), and the orientation of the audio source (that is, the direction in which it's facing), given as (orientationx, orientationy, orientationz). depending on the directionality of the sound (as specified using the attributes coneinnerangle, coneouterangle, and codeoutergain), the orientation of the sound may alter the perceived volume of the sound as it's being played. if the sound is pointing toward the listener, it will be louder than if the sound is pointed away from the listener. the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property. s...
PannerNode.refDistance - Web APIs
working draft ...
PannerNode.rolloffFactor - Web APIs
working draft ...
PannerNode.setOrientation() - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
PannerNode.setPosition() - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
PannerNode.setVelocity() - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
PannerNode - Web APIs
anting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function. to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes! note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc. if it supports those, or older methods (like audiolistener.setorientation()) if...
ParentNode.append() - Web APIs
Web › API › ParentNode › append
// nodelist [ #text "some text", <p> ] parentnode.append() is unscopable the append() method is not scoped into the with statement. see symbol.unscopables for more information. ...
ParentNode.lastElementChild - Web APIs
lastelementchild moved to parentnode. this is a fairly technical change that shouldn't affect compatibility. syntax const element = node.lastelementchild example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> const foo = document.getelementbyid('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari. // overwrites native 'lastelementchild' prototype. // returns array instead of htmlcollection. ;(function(constructor) { if(constructor && constructor.prototype && constructor.prototype.lastelementchild == null) { object.defineproperty(constructor.prototype, 'lastelementchild'...
ParentNode.replaceChildren() - Web APIs
node tree are violated. examples emptying a node replacechildren() provides a very convenient mechanism for emptying a node of all its children. you simply call it on the parent node without any argument specified: mynode.replacechildren(); transferring nodes between parents replacechildren() enables you to easily transfer nodes between parents, without having to resort to verbose looping code. for example, say we have a simple application allowing you to choose what food you want for your party. this html might look something like this: <h2>party food option list</h2> <main> <div> <label for="no">no thanks!</label> <select id="no" multiple size="10"> <option>apples</option> <option>oranges</option> <option>grapes</option> <option>bananas</option> ...
PasswordCredential.passwordName - Web APIs
the passwordname property of the passwordcredential interface returns a usvstring, depicting the name used by the password field, when submitting the current object to a remote endpoint via fetch. this property defaults to 'password', but may be matched to anything your backend service expects. syntax var passwordname = passwordcredential.passwordname passwordcredential.passwordname = "passcode" value a usvstring representing the password field name, used when submitting the current object to a remote endpoint via fetch. example // tbd specifications specification status comment credential management level 1 working draft initial definition. ...
PaymentAddress.country - Web APIs
the country read-only property of the paymentaddress interface is a string identifying the address's country using the iso 3166-1 alpha-2 standard. the string is always in its canonical upper-case form. some examples of valid country values: "us", "gb", "cn", or "jp". syntax var paymentcountry = paymentaddress.country; value a domstring which contains the iso3166-1 alpha-2 code identifying the country in which the address is located, or an empty string if no country is available, which frequently can be assumed to mean "same country as the site owner." usage notes if the payment handler validates the address and determines that the value of country is invalid, a call to paymentrequestupdateevent.updatewith() will be made with a details object containing a shippingaddresserrors field. t...
PaymentRequest.onmerchantvalidation - Web APIs
the paymentrequest, indicating that the payment handler requires the merchant to validate themselves as allowed to use this payment handler. examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. specifications specification status comment payment request apithe definition of 'onmerchantvalidat...
PaymentRequest.onshippingoptionchange - Web APIs
ption.id = 'jp'; shippingoption.label = 'international shipping'; shippingoption.amount.value = '10.00'; details.total.amount.value = '65.00'; // shipping to elsewhere is unsupported } else { // empty array indicates rejection of the address details.shippingoptions = []; return promise.resolve(details); console.log(details.error); } // hardcode for simplicity if (details.displayitems.length === 2) { details.displayitems[2] = shippingoption; } else { details.displayitems.push(shippingoption); } details.shippingoptions = [shippingoption]; return promise.resolve(details); })(details, request.shippingaddress)); }); specifications specification status comment payment request apith...
PaymentRequest: shippingoptionchange event - Web APIs
vent is sent to the paymentrequest whenever the user chooses a shipping option from the list of available options. the string identifying the currently-selected shipping option can be found in the shippingoption property. bubbles no cancelable no interface paymentrequestupdateevent event handler property onshippingoptionchange examples this code snippet sets up a handler for the shippingoptionchange event. the code recalculates the total charge for the payment based on the selected shipping option. for example, if there are three options (such as "free ground shipping", "2-day air", and "next day"), each time the user chooses one of those options, this event handler is called to recalculate the total based on the changed shipping option.
PaymentValidationErrors - Web APIs
the paymentvalidationerrors dictionary represents objects providing information about any and all errors that occurred while processing a payment request. when validation of the paymentresponse returned by the paymentrequest.show() or paymentresponse.retry() methods fails, your code creates a paymentvalidationerrors object to pass into retry() so that the user agent knows what needs to be fixed and what if any error messages to display to the user. properties error optional a general description of a payment error from which the user may attempt to recover by retrying the payment, possibly after correcting mistakes in the payment information. error can be provided all by itself to provide only a generic error message, or in concert with the other properties to serve as an overview whil...
Payment processing concepts - Web APIs
od. payment method the instrument by which payment is submitted, such as a credit card or online payment service. payment method provider an organization that provides the technology needed to submit payments using a given payment method. for example, when using a credit card to pay, the credit card processing service is the payment method provider. payment handler the implementation of the code needed to interface with a particular payment method provider in order to process payments. some payment handlers use merchant validation, which is the process of validating the identity of a merchant in some way, usually using some form of cryptographic response such as a public key. validated merchants are allowed to interface with a payment handler. payment method identifiers payment handl...
PerformanceEventTiming - Web APIs
art; }); }); // register observer for event. observer.observe({entrytypes: ["event"]}); we can also directly query the first input delay. // keep track of whether (and when) the page was first hidden, see: // https://github.com/w3c/page-visibility/issues/29 // note: ideally this check would be performed in the document <head> // to avoid cases where the visibility state changes before this code runs. let firsthiddentime = document.visibilitystate === 'hidden' ? 0 : infinity; document.addeventlistener('visibilitychange', (event) => { firsthiddentime = math.min(firsthiddentime, event.timestamp); }, {once: true}); // sends the passed data to an analytics endpoint. this code // uses `/analytics`; you can replace it with your own url. function sendtoanalytics(data) { const body = json.s...
PerformanceObserver.observe() - Web APIs
together with the entrytypes option. buffered: a boolean flag to indicate whether buffered entries should be queued into the observer's buffer. must be used only with the "type" option. see performanceentry.entrytype for a list of valid performance entry type names. unrecognized types are ignored, though the browser may output a warning message to the console to help developers debug their code. if no valid types are found, observe() has no effect. examples this example creates and configures two performanceobservers; one watches for "mark" and "frame" events, and the other watches for "measure" events. var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events ...
PerformancePaintTiming - Web APIs
the time to first-contentful-paint was 2787.460 milliseconds. specifications specification status comment paint timingthe definition of 'performancepainttiming' in that specification. working draft initial definition. ...
PerformanceResourceTiming - Web APIs
a domhighrestimestamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first. performanceresourcetiming.transfersizeread only a number representing the size (in octets) of the fetched resource. the size includes the response header fields plus the response payload body. performanceresourcetiming.encodedbodysizeread only a number representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. performanceresourcetiming.decodedbodysizeread only a number that is the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. performanceresourcetiming.serve...
Using the Performance API - Web APIs
ion timing is achieved by using the domhighrestimestamp type for time values. the unit is milliseconds and should be accurate to 5 µs (microseconds). however, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond. the following code example shows the use of domhighrestimestamp and the performance.now() method. the now() method returns a timestamp (of type domhighrestimestamp) that is a discrete point in time. by calling this method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var starttime; var endtime; starttime = performance.now(); do_task(); endtime = p...
Performance API - Web APIs
1 candidate recommendation adds the performanceresourcetiming interface. adds the clearresourcetimings() method, the setresourcetimingbuffersize() method, and the onresourcetimingbufferfull event handler to the performance interface. also adds the timing-allow-origin response header. resource timing level 2 working draft adds the nexthopprotocol, workerstart, transfersize, encodedbodysize, and decodedbodysize properties to the performanceresourcetiming interface. resource timing level 3 editor's draft user timing recommendation adds mark(), clearmarks(), measure() and clearmeasures() methods to the performance interface. adds the performancemark and peformancemeasure interfaces. user timing level 2 working draft implem...
Permissions API - Web APIs
issionstatus for a specific api. not all apis' permission statuses can be queried using the permissions api. notable apis that are permissions-aware include: clipboard api notifications api push api web midi api more apis will gain permissions api support over time. examples we have made a simple example available called location finder. you can run the example live, or view the source code on github. read more about how it works in our article using the permissions api. interfaces navigator.permissions and workernavigator.permissions read only provides access to the permissions object from the main context and worker context respectively. permissions provides the core permission api functionality, such as methods for querying and revoking permissions. permissionstatus pr...
PointerEvent.pointerId - Web APIs
event interface is an identifier assigned to a given pointer event. the identifier is unique, being different from the identifiers of all other active pointer events. since the value may be randomly generated, it is not guaranteed to convey any particular meaning. syntax var id = pointerevent.pointerid; return value id the pointer event's unique identifier number. example the following code snippet compares a previously saved pointerid with the one of the pointerdown event that was just fired. let id; // let's assume that this is a previously saved pointerid target.addeventlistener('pointerdown', function(event) { // compare previous event's id that was cached // to current event's id and handle accordingly if (id === event.pointerid) process_event(event); }, false); speci...
PointerEvent - Web APIs
ns a sequence of pointerevent instances that the browser predicts will follow the dispatched pointermove event's coalesced events. pointer event types the pointerevent interface has several event types. to determine which event fired, look at the event's type property. note: it's important to note that in many cases, both pointer and mouse events get sent (in order to let non-pointer-specific code still interact with the user). if you use pointer events, you should call event.preventdefault() to keep the mouse event from being sent as well. pointerover this event is fired when a pointing device is moved into an element's hit test boundaries. pointerenter this event is fired when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including...
Pointer Lock API - Web APIs
menty are valid regardless of the mouse lock state, and are available even when unlocked for convenience. when the mouse is unlocked, the system cursor can exit and re-enter the browser window. if that happens, movementx and movementy could be set to zero. simple example walkthrough we've written a simple pointer lock demo to show you how to use it to set up a simple control system (see source code). the demo looks like this: this demo uses javascript to draw a ball on top of an <canvas> element. when you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. let's see how this works. we set initial x and y positions on the canvas: var x = 50; var y = 50; the pointer lock methods are currently prefixed, so next ...
Multi-touch interaction - Web APIs
od user experience regardless of the user's hardware. pointer events have many similarities to mouse events but they support multiple simultaneous pointers such as multiple fingers on a touch screen. this additional feature can be used to provide richer user interaction models but at the cost of additional complexity in the multi-touch interaction handling. this document demonstrates via example code, using pointer events with different multi-touch interactions. a live version of this application is available on github. the source code is available on github; pull requests and bug reports are welcome. example this example demonstrates using pointer events' various event types (pointerdown, pointermove, pointerup pointercancel, etc.) for different multi-touch interactions. define touch tar...
Pinch zoom gestures - Web APIs
rom the simple single-touch swipe gesture to the more complex multi-touch twist gesture, where the touch points (aka pointers) move in different directions. this example shows how to detect the pinch/zoom gesture, which uses pointer events to detect whether the user moves two pointers closer or farther apart from each other. a live version of this application is available on github. the source code is available on github; pull requests and bug reports are welcome. example in this example, you use the pointer events to simultaneously detect two pointing devices of any type, including fingers, mice, and pens. the pinch in (zoom out) gesture, which moves the two pointers toward each other, changes the target element's background color to lightblue. the pinch out (zoom in) gesture, which move...
PopStateEvent - Web APIs
note: browsers used to handle the popstate event differently on page load, but now they behave the same. firefox never emitted a popstate event on page load. chrome did until version 34, while safari did until version 10.0. syntax window.onpopstate = funcref; funcref is a handler function. ...
PromiseRejectionEvent() - Web APIs
led" or "unhandledrejection", to match the event names of the possible (non-synthetic) promiserejectionevent events that user agents can actually fire). options an object specifying details about the rejection which occurred: promise the promise that was rejected. reason any value or object which represents the reason the promise was rejected. this can be anything from a numeric error code to an error domstring to an object which contains detailed information describing the situation resulting in the promise being rejected. return value a new promiserejectionevent configured as specified by the parameters. examples this example creates a new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire". the reason could just as e...
PromiseRejectionEvent.reason - Web APIs
iserejectionevent reason read-only property is any javascript value or object which provides the reason passed into promise.reject(). this in theory provides information about why the promise was rejected. syntax reason = promiserejectionevent.reason value a value or object which provides information you can use to understand why the promise was rejected. this could be anything from an error code to an object with text, links, and whatever else you might wish to include. examples window.onunhandledrejection = function(e) { console.log(e.reason); } specifications specification status comment html living standardthe definition of 'promiserejectionevent.reason' in that specification. living standard initial definition. ...
PromiseRejectionEvent - Web APIs
script promise that was rejected. promiserejectionevent.reason read only a value or object indicating why the promise was rejected, as passed to promise.reject(). methods this interface has no unique methods; inherits methods from its parent event. events rejectionhandled fired when a javascript promise is rejected, and after the rejection is handled by the promise's rejection handling code. unhandledrejection fired when a javascript promise is rejected but there is no rejection handler to deal with the rejection. examples this simple example catches unhandled promise rejections and logs them for debugging purposes. window.onunhandledrejection = function(e) { console.log(e.reason); } specifications specification status comment html living standa...
PublicKeyCredential.id - Web APIs
the id read-only property of the publickeycredential interface is a domstring, inherited from credential, which represents the identifier of the current publickeycredential instance. this property is a base64url encoded version of publickeycredential.rawid. note: this property may only be used in top-level contexts and will not be available in an <iframe> for example. syntax id = publickeycredential.id value a domstring being the base64url encoded version of publickeycredential.rawid. examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john do...
PublicKeyCredential.rawId - Web APIs
note: this property may only be used in top-level contexts and will not be available in an <iframe> for example. syntax rawid = publickeycredential.rawid value a arraybuffer containing the identifier of the credentials. ...
PublicKeyCredentialCreationOptions.user - Web APIs
is intended for display and may be use to distinguish different account with the same displayname. ...
PushManager.getSubscription() - Web APIs
existing push subscription. it returns a promise that resolves to a pushsubscription object containing details of an existing subscription. if no existing subscription exists, this resolves to a null value. syntax ​pushmanager.getsubscription().then(function(pushsubscription) { ... } ); parameters none. returns a promise that resolves to a pushsubscription object or null. example this code snippet is taken from a push messaging and notification sample. (no live demo is available.) // we need the service worker registration to check for a subscription navigator.serviceworker.ready.then(function(serviceworkerregistration) { // do we already have a push message subscription? serviceworkerregistration.pushmanager.getsubscription() .then(function(subscription) { ...
PushManager.subscribe() - Web APIs
syntax ​pushmanager.subscribe(options).then(function(pushsubscription) { ... } ); parameters options optional an object containing optional configuration parameters. it can have the following properties: uservisibleonly: a boolean indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. applicationserverkey: a base64-encoded domstring or arraybuffer containing an ecdsa p-256 public key that the push server will use to authenticate your application server. if specified, all messages from your application server must use the vapid authentication scheme, and include a jwt signed with the corresponding private key. this key is not the same ecdh key that you use to encrypt the data. for more information, see "using vapid...
RTCDTMFSender.insertDTMF() - Web APIs
he rtcdtmfsender every time a tone starts or ends. as long as the connection is active, you 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 t...
RTCDTMFSender.toneBuffer - Web APIs
he similarly-labeled keys which are typically on the bottom row of the telephone keypad. the comma (",") this character instructs the dialing process to pause for two seconds before sending the next character in the buffer. all other characters are unrecognized and will cause insertdtmf() to throw an invalidcharactererror exception. using tone buffer strings for example, if you're writing code to control a voicemail system by sending dtmf codes, you might use a string such as "*,1,5555". in this example, we would send "*" to request access to the vm system, then, after a pause, send a "1" to start playback of voicemail messages, then after a pause, dial "5555" as a pin number to open the messages. settting the tone buffer to an empty string ("") cancels any pending dtmf codes. exampl...
RTCDataChannel.binaryType - Web APIs
geevent.data property is an object of the type specified by the binarytype. syntax var type = adatachannel.binarytype; adatachannel.binarytype = type; value a domstring that can have one of these values: "blob" received binary messages' contents will be contained in blob objects. "arraybuffer" received binary messages' contents will be contained in arraybuffer objects. example this code configures a data channel to receive binary data in arraybuffer objects, and establishes a listener for message events which constructs a string representing the received data as a list of hexadecimal byte values. var dc = peerconnection.createdatachannel("binary"); dc.binarytype = "arraybuffer"; dc.onmessage = function(event) { let bytearray = new uint8array(event.data); let hexstring = ""...
RTCDataChannel.bufferedAmount - Web APIs
ueued messages. however, even after closing the channel, attempts to send messages continue to add to the bufferedamount value, even though the messages are neither sent nor buffered. whenever this value decreases to fall to or below the value specified in the bufferedamountlowthreshold property, the user agent fires the bufferedamountlow event. this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them. syntax var amount = adatachannel.bufferedamount; value the number of bytes of data currently queued to be sent over the data channel but have not yet been sent. example the snippet below includes a function which changes the contents of a block with the id "buffersize" to a string indicating the number of bytes cur...
RTCDataChannel: close event - Web APIs
se event for the rtcdatachannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started. dc.addeventlistener("close", ev => { messageinputbox.disabled = true; sendbutton.disabled = true; connectbutton.disabled = false; disconnectbutton.disabled = true; }, false); all this code does in response to receiving the close event is to disable an input box and its "send" button, and to enable the button used to start a call (while disabling the one that ends a call). you can also use the onclose event handler property to set a handler for close events: dc.onclose = ev => { messageinputbox.disabled = true; sendbutton.disabled = true; connectbutton.disabled = false; di...
RTCDataChannel.negotiated - Web APIs
pp (true) or by the webrtc layer (false). the default is false. see creating a data channel in using webrtc data channels for further information about this property. syntax var negotiated = adatachannel.negotiated; value true if the rtcdatachannel's connection was negotiated by the web app itself; false if the negotiation was handled by the webrtc layer. the default is false. example the code snippet below checks the value of negotiated; if it's true, a function called shutdownremotechannel() is called with the channel's id; presumably this would be implemented to transmit a shutdown signal to the remote peer prior to terminating the connection. if (datachannel.negotiated) { shutdownremotechannel(datachannel.id); } specifications specification status comment ...
RTCDataChannel.onmessage - Web APIs
vent is fired on the channel. this event is represented by the messageevent interface. this event is sent to the channel when a message is received from the other peer. syntax rtcdatachannel.onmessage = function; value a function which the browser will call to handle the message event. the function receives as its sole input parameter a messageevent object describing the event. example this code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it. the new elements are then attached to the end of the document. let pc = new rtcpeerconnection(); let dc = pc.createdatachannel(); dc.onmessage = function(event) { var el = document.createelement("p"); var...
RTCDataChannel.reliable - Web APIs
the read-only rtcdatachannel property reliable indicates whether or not the data channel is reliable. this property is obsolete. use rtcdatachannel.ordered instead in any new code, and update existing code as soon as possible. syntax var reliable = adatachannel.reliable; value true if the rtcdatachannel's connection is reliable; false if it isn't. example // tbd specifications no longer part of any specification. ...
RTCDataChannel.stream - Web APIs
ification) read-only rtcdatachannel property stream returns an id number (between 0 and 65,535) which uniquely identifies the rtcdatachannel. this id is set at the time the data channel is created, either by the user agent (if rtcdatachannel.negotiated is false) or by the site or app script (if negotiated is true). this property has been replaced with the rtcdatachannel.id property. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. syntax var stream = adatachannel.stream; value an unsigned short value (that is, an integer between 0 and 65,535) which uniquely identifies the data channel. example var datachannel = pc.createdatachannel("samplechannel"); console.log("data channel stream id: " + datachannel.stream); ...
RTCDataChannelEvent.channel - Web APIs
the read-only property rtcdatachannelevent.channel returns the rtcdatachannel associated with the event. syntax var channel = rtcdatachannelevent.channel; value a rtcdatachannel object representing the data channel linking the receiving rtcpeerconnection to its remote peer. example the first line of code in the datachannel event handler shown below takes the channel from the event object and saves it locally for use by the code handling data traffic. pc.ondatachannel = function(event) { inbounddatachannel = event.channel; inbounddatachannel.onmessage = handleincomingmessage; inbounddatachannel.onopen = handlechannelopen; inbounddatachannel.onclose = handlechannelclose; } specifications specification status comment webrtc 1.0: real-time communic...
RTCDtlsTransport.state - Web APIs
specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport.state' in that specification. candidate recommendation initial definition. ...
RTCErrorEvent - Web APIs
nd returns a new rtcerrorevent object. properties in addition to the standard properties available on the event interface, rtcerrorevent also includes the following: error read only an rtcerror object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the sdp or what sctp cause code was at issue). methods no additional methods are provided beyond any found on the parent interface, event. description there are other data types used for error events in webrtc, as needed for errors with special information sharing requirements. the most common of these is probably rtcpeerconnectioniceerrorevent, used by the icecandidateerror event, which signals an error that has occurred ...
RTCIceCandidate.address - Web APIs
ip address is the peer's own ip address) are left out of the pool of candidates, as are any other candidates which aren't relay candidates. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the fifth field, "192.168.0.56" is the ip address in this candidate's a-line string. example this code snippet uses the value of address to implement an ip address based ban feature. if (ipbanlist.includes(candidate.address)) { rejectcandidate(candidate); } else { acceptcandidate(candidate); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate: address' in that specification. candidat...
RTCIceCandidate.component - Web APIs
candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host this is an ice candidate a-line, whose foundation is 4234997325. the next field on the a-line, "1", is the component id. a value of "1" indicates rtp, which is recorded in the component property as "rtp". if this value were instead "2", the a-line would be describing an rtcp candidate, and compoment would be "rtcp". example this code snippet examines a candidate's component type and dispatches the candidate to different handlers depending on the value. if (candidate.component == "rtp") { handlertpcandidate(candidate); } else if (candidate.component == "rtcp") { handlertcpcandidate(candidate); } else { handleunknowncandidate(candidate); } specifications specification status comment webrtc 1.0: ...
RTCIceCandidate.foundation - Web APIs
it is available. note: if port is null — and port is supported by the user agent — passing the candidate to addicecandidate() will fail, throwing an operationerror exception. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the field "4234997325" is the foundation. example this code snippet uses the foundation of two candidates to determine if they're actually the same candidate. if (candidate1.foundation == candidate2.foundation) { /* the two candidates are the same, even if they're on different transports */ } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.
RTCIceCandidate.port - Web APIs
ecandidate() will fail, throwing an operationerror exception. this applies only if the candidate implements port. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the port number is found in the sixth field, which is "44323". in this case, the value of port will be 44323. example this code snippet fetches the ip address and port number of the candidate, storing them into an object for future use. var candidateloc = { address: candidate.ip, port: candidate.port } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.port' in that specification. candidate recommendation ...
RTCIceCandidate.protocol - Web APIs
s supported by the user agent — passing the candidate to addicecandidate() will fail, throwing an operationerror exception. usage notes here's an example candidate a-line from an ice transaction: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the third field, "udp", is the protocol type, indicating that the candidate would use the udp transport protocol. example this code snippet examines the value of protocol to decide if it should look at the value of tcptype to see if it's a simultaneous-open (s-o) candidate. if (candidate.protocol == "tcp") { if (candidate.tcptype == "so") { adjustforsimultaneousopen(candidate); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of ...
RTCIceCandidate.usernameFragment - Web APIs
andidate(). there's not typically a need to manually worry about filtering the candidates. however, let's imagine that we do need to minimize traffic. the function below, ssnewcandidate(), is called when a message, signalmsg, arrives from the signaling server that contains an ice candidate to be added to the rtcpeerconnection. ...
RTCIceCandidateInit.candidate - Web APIs
043278322 192.168.0.56 44323 typ host". the user agent always prefers candidates with the highest priority, all else being equal. in the example above, the priority is 2043278322. the attributes are all separated by a single space character, and are in a specific order. the complete list of attributes for this example candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" example when a new ice candidate is received by your signaling code from the remote peer, you need to construct the rtcicecandidate object that encapsulates it. this is done in the event handler for the icecandidate event. if your client-side signaling layer builds and ...
RTCIceCandidateStats.mozLocalTransport - Web APIs
...
RTCIceCandidateStats - Web APIs
ndidate. const isusablenetworktype = stats => { switch(stats.networktype) { case "ethernet": case "vpn": return true; case "bluetooth": case "cellular": case "wimax": case "unknown": default: return false; } } if (rtcstats && rtcstats.type === "local-candidate") { if (!isusablenetworktype(rtcstats)) { abortconnection(); return; } } this code calls a function called abortconnection() if the rtcstats object represents information about a local candidate is which would be using a network connection other than ethernet or a vpn. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatestats' in that specification. candidate recommendation init...
RTCIceServer.url - Web APIs
Web › API › RTCIceServer › url
the obsolete rtciceserver dictionary's url property specifies the url of a single ice server to be used while negotiating connections. it was removed from the specification in june 2013 but is still broadly used in older examples and books, so we include documentation here to help adapt old code to new browsers. this property has been removed from the specification; while it's still supported by many browsers, it should no longer be used. you should instead use the newer urls property, which allows you to optionally specify multiple urls for the server. try to update any existing code to use that property instead. syntax var iceserver = { ... url = iceserverurl, ... }; var serverurl = iceserver.url; iceserver.u...
RTCIceServer - Web APIs
for each server in the list, as shown in the example below. obsolete properties the following properties have been removed from the specification and should not be used. url this obsolete property is a string specifies a single ice server's url. do not use this property; use urls instead. because many older books and examples still use this, we include it to help developers update their code or make sense of older examples. example the configuration below establishes two ice servers. the first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided. the second server has two urls: stun:stun.example.com and stun:stun-1.example.com. var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", ...
RTCIceTransport.getLocalCandidates() - Web APIs
the rtcicetransport method getlocalcandidates() returns an array of rtcicecandidate objects, one for each of the candidates that have been gathered by the local device during the current ice agent session. the local candidates are placed in this list by the ice agent prior to being delivered to the local client's code in an icecandidate event so that the client can forward the candidates to the remote peer. syntax localcandidates = rtcicetransport.getlocalcandidates(); parameters none. return value a javascript array containing one rtcicecandidate object for each candidate that has been identified so far during the ice candidate gathering session. you can't correlate these local candidates with matching remote candidates. to find the best match found so far, call rtcicetransport.getse...
RTCIceTransport.getRemoteCandidates() - Web APIs
syntax remotecandidates = rtcicetransport.getremotecandidates(); parameters none. ...
RTCIceTransport.state - Web APIs
hecks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" the ice agent has determined that connectivity has been lost for this rtcicetransport. this is not a failure state (that's "failed"). a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automatically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gathering process, has received the "no more candidates" notification from the remote peer, and has finished checking pairs of candidates, without successfully finding a pair that is both valid and for which consent can be obtained. this is a terminal state, indicating tha...
RTCIceTransportState - Web APIs
hecks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" the ice agent has determined that connectivity has been lost for this rtcicetransport. this is not a failure state (that's "failed"). a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automatically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gathering process, has received the "no more candidates" notification from the remote peer, and has finished checking pairs of candidates, without successfully finding a pair that is both valid and for which consent can be obtained. this is a terminal state, indicating tha...
RTCIdentityEvent.assertion - Web APIs
firefox implements the interface this property belongs to under the following name: rtcpeerconnectionidentityevent. it is likely that it will correct this name when it will unprefix rtcpeerconnection, once spec and implementation will have been stabilized. ...
RTCInboundRtpStreamStats.firCount - Web APIs
stream falls behind and needs to skip frames in order to catch up. syntax var fircount = rtcinboundrtpstreamstats.fircount; value an integer value indicating how many fir packets have been received by the sender during the current connection. this statistic is available only for video tracks. the receiver sends a fir packet to the sender any time it falls bahind or loses packets and cannot decode the incoming stream any longer because of the lost data. this tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up. the higher fircount is, the more often frames were dropped, which may be an indication that the media's bit rate is too high for the available bandwidth, or that the receiving device is overburdened and is therefore unable to process the...
RTCInboundRtpStreamStats.perDscpPacketsReceived - Web APIs
the perdscppacketsreceived property of the rtcinboundrtpstreamstats dictionary is a record comprised of key/value pairs in which each key is a string representation of a differentiated services code point and the value is the number of packets received for that dcsp. note: not all operating systems make data available on a per-dscp basis, so this property shouldn't be relied upon on those systems. syntax var perdscppacketsreceived = rtcinboundrtpstreamstats.perdscppacketsreceived; value a record comprised of string/value pairs. each key is the string representation of a single differentiated services code point (dscp)'s id number. note: due to network bleaching and remapping, the numbers seen on this record are not necessarily going to match the values as they were when the data was ...
RTCInboundRtpStreamStats.pliCount - Web APIs
the plicount property of the rtcinboundrtpstreamstats dictionary states the number of times the rtcrtpreceiver described by these statistics sent a picture loss indication (pli) packet to the sender. a pli packet indicates that some amount of encoded video data has been lost for one or more frames. syntax var plicount = rtcinboundrtpstreamstats.plicount; value an integer value indicating the number of times a pli packet was sent by the rtcrtpreceiver to the sender. these are sent by the receiver's decoder to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. this information is only available for video streams. this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since...
RTCOfferAnswerOptions - Web APIs
as the base type for the options parameter when calling createoffer() or createanswer() on an rtcpeerconnection. each of createoffer() and createanswer() use rtcofferansweroptions as the base type for their options parameter's dictionary. createoffer() uses rtcofferoptions and createanswer() uses rtcansweroptions. properties voiceactivitydetection optional for configurations of systems and codecs that are able to detect when the user is speaking and toggle muting on and off automatically, this option enables and disables that behavior. the default value is true, enabling this functionality specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcofferansweroptions' in that specification. candidate...
RTCOutboundRtpStreamStats.firCount - Web APIs
l frame instead of a delta frame. available only on video media. syntax var fircount = rtcoutboundrtpstreamstats.fircount; value an integer value indicating how many fir packets have been received by the sender during the current connection. this statistic is available only for video tracks. the receiver sends a fir packet to the sender any time it falls bahind or loses packets and cannot decode the incoming stream any longer because of the lost data. this tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up. the higher fircount is, the more often frames were dropped, which may be an indication that the media's bit rate is too high for the available bandwidth, or that the receiving device is overburdened and is therefore unable to process the...
RTCOutboundRtpStreamStats.perDscpPacketsSent - Web APIs
the perdscppacketssent property of the rtcoutboundrtpstreamstats dictionary is a record comprised of key/value pairs in which each key is a string representation of a differentiated services code point and the value is the number of packets sent for that dcsp. note: not all operating systems make data available on a per-dscp basis, so this property shouldn't be relied upon on those systems. syntax var perdscppacketssent = rtcoutboundrtpstreamstats.perdscppacketssent; value a record comprised of string/value pairs. each key is the string representation of a single differentiated services code point (dscp)'s id number. note: due to network bleaching and remapping, the numbers seen on this record are not necessarily going to match the values as they were when the data was sent. specif...
RTCOutboundRtpStreamStats.qualityLimitationReason - Web APIs
the qualitylimitationreason property of the rtcoutboundrtpstreamstats dictionary is a string indicating the reason why the media quality in the stream is currently being reduced by the codec during encoding, or none if no quality reduction is being performed. this quality reduction may include changes such as reduced frame rate or resolution, or an increase in compression factor. the amount of time the encoded media has had its quality reduced in each of the potential ways that can be done can be found in qualitylimitationdurations. syntax var qualitylimitationreason = rtcoutboundrtpstreamstats.qualitylimitationreason; value a map whose keys are domstrings whose values come from the rtcqualitylimitationreason enumerated type, and whose values are the duration of the media, in seconds, wh...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
ndidates and false if it cannot. if no remote peer has been established, this value is null. note: this property's value is determined once the local peer has called rtcpeerconnection.setremotedescription(); the provided description is used by the ice agent to determine whether or not the remote peer supports trickled ice candidates. example var pc = new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice. pc.setremotedescription(remoteoffer) .then(_ => pc.createanswer()) .then(answer => pc.setlocaldescription(answer)) .then(_ => if (pc.cantrickleicecandidates) { return pc.localdescription; } return new promise(r => { pc.addeventlistener('icegatheringstatechange', e => ...
RTCPeerConnection: datachannel event - Web APIs
entlistener("datachannel", ev => { receivechannel = ev.channel; receivechannel.onmessage = myhandlemessage; receivechannel.onopen = myhandleopen; receivechannel.onclose = myhandleclose; }, false); receivechannel is set to the value of the event's channel property, which specifies the rtcdatachannel object representing the data channel linking the remote peer to the local one. ...
RTCPeerConnection.getStats() - Web APIs
() used success and failure callbacks to report the results to you, instead of using a promise. this version of getstats() is obsolete; in addition, the data it returns is entirely different from the current specification, and the form of that data was never documented. this form of getstats() has been or will soon be removed from most browsers; you should not use it, and should update existing code to use the new promise-based version. check the browser compatibility table to verify the state of this method. promise = rtcpeerconnection.getstats(selector, successcallback, failurecallback) parameters selector optional a mediastreamtrack for which to gather statistics. if this is null (the default value), statistics will be gathered for the entire rtcpeerconnection. successcallback a...
RTCPeerConnection.getTransceivers() - Web APIs
ed to send and receive data on the connection. syntax transceiverlist = rtcpeerconnection.gettransceivers(); parameters none. return value an array of the rtcrtptransceiver objects representing the transceivers handling sending and receiving all media on the rtcpeerconnection. the list is in the order in which the transceivers were added to the connection. example the following snippet of code stops all transceivers associated with an rtcpeerconnection. pc.gettransceivers().foreach(transceiver => { transceiver.stop(); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.gettransceivers()' in that specification. candidate recommendation ...
RTCPeerConnection: negotiationneeded event - Web APIs
unication environment requires reconfiguring the connection. bubbles no cancelable no interface event event handler property rtcpeerconnection.onnegotiationneeded the negotiationneeded event is first dispatched to the rtcpeerconnection when media is first added to the connection. this starts the process of ice negotiation by instructing your code to begin exchanging ice candidates through the signaling server. see signaling transaction flow in signaling and video calling for a description of the signaling process that begins with a negotiationneeded event. examples in this example, we use addeventlistener() to create an event handler for negotiationneeded. its role is to create an sdp offer and send it through the signaling channel to t...
RTCPeerConnection.onicecandidate - Web APIs
should not be sent to the remote peer. when this happens, the connection's icegatheringstate has also changed to complete. you don't need to watch for this explicitly; instead, if you need to sense the end of signaling, you should watch for a icegatheringstatechange event indicating that the ice negotiation has transitioned to the complete state. example the example below, which is based on the code from the article signaling and video calling, sets up a handler for icecandidate events to send the candidates to the remote peer. pc.onicecandidate = function(event) { if (event.candidate) { // send the candidate to the remote peer } else { // all ice candidates have been sent } } notice that the end of negotiation is detected here when the event's candidate property is null. sp...
RTCPeerConnection.onicecandidateerror - Web APIs
process. syntax rtcpeerconnection.onicecandidateerror = eventhandler; value this should be set to a function you provide which is passed a single parameter: an rtcpeerconnectioniceerrorevent object describing the icecandidateerror event. the event offers properties describing the error to help you handle it appropriately. example pc.onicecandidateerror = function(event) { if (event.errorcode >= 300 && event.errorcode <= 699) { // stun errors are in the range 300-699. see rfc 5389, section 15.6 // for a list of codes. turn adds a few more error codes; see // rfc 5766, section 15 for details. } else if (event.errorcode >= 700 && event.errorcode <= 799) { // server could not be reached; a specific error number is // provided but these are not yet specified. } } ...
RTCPeerConnection.oniceconnectionstatechange - Web APIs
on an rtcpeerconnection instance. this happens when the state of the connection's ice agent, as represented by the iceconnectionstate property, changes. syntax rtcpeerconnection.oniceconnectionstatechange = eventhandler; value this event handler can be set to function which is passed a single input parameter: an event object describing the iceconnectionstatechange event which occurred. your code can look at the value of rtcpeerconnection.iceconnectionstate to determine what the new state is. example the example below watches the state of the ice agent for a failure or unexpected closure and takes appropriate action, such as presenting an error message or attempting to restart the ice agent. pc.oniceconnectionstatechange = function(event) { if (pc.iceconnectionstate === "failed" || ...
RTCPeerConnection.onidentityresult - Web APIs
such an event is sent when an identity assertion is generated, via getidentityassertion() or during the creation of an offer or an answer. syntax peerconnection.onidentityresult = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. an event handler always has one single parameter, containing the event, here of type rtcidentityevent. ...
RTCPeerConnection.onidpassertionerror - Web APIs
such an event is sent when the associated identity provider (idp) encounters an error while generating an identity assertion. this event handler is deprecated. you should instead detect idp assertion errors by handling rejection of the promise returned by rtcpeerconnection.peeridentity. ...
RTCPeerConnection.onidpvalidationerror - Web APIs
such an event is sent when the associated identity provider (idp) encounters an error while validating an identity assertion. this event handler is obsolete. you should instead detect idp validation errors by watching for the promise returned by rtcpeerconnection.peeridentity to be rejected. ...
RTCPeerConnection.onpeeridentity - Web APIs
such an event is sent when an identity assertion, received from a peer, has been successfully validated. this event handler is obsolete. to detect successful validation of the identity, wait for the promise returned by peeridentity to resolve successfully with the peer's identity. syntax peerconnection.onpeeridentity = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}. ...
RTCPeerConnection.onremovestream - Web APIs
sting removetrack event on the remote mediastream and the corresponding mediastream.onremovetrack event handler property of the remote mediastream. the rtcpeerconnection api is now track-based, so having zero tracks in the remote stream is equivalent to the remote stream being removed and the old removestream event. the rtcpeerconnection.onremovestream event handler is a property containing the code to execute when the removestream event, of type mediastreamevent, is received by this rtcpeerconnection. such an event is sent when a mediastream is removed from this connection. syntax peerconnection.onremovestream = function; values function is the name of a user-defined function, without the () suffix or any parameters, or an anonymous function declaration, such as function(event) {...}...
RTCPeerConnection.remoteDescription - Web APIs
cpeerconnection.remotedescription returns a rtcsessiondescription describing the session (which includes configuration and media information) for the remote end of the connection. if this hasn't been set yet, this is null. the returned value typically reflects a remote description which has been received over the signaling server (as either an offer or an answer) and then put into effect by your code calling rtcpeerconnection.setremotedescription() in response. syntax var sessiondescription = peerconnection.remotedescription; on a more fundamental level, the returned value is the value of rtcpeerconnection.pendingremotedescription if that property isn't null; otherwise, the value of rtcpeerconnection.currentremotedescription is returned. see pending and current descriptions in webrtc conn...
RTCPeerConnection.restartIce() - Web APIs
this example creates a handler for the iceconnectionstatechange event that handles a transition to the failed state by restarting ice in order to try again. pc.addeventlistener("iceconnectionstatechange", event => { if (pc.iceconnectionstate === "failed") { /* possibly reconfigure the connection in some way here */ /* then request ice restart */ pc.restartice(); } }); with this code in place, a transition to the failed state during ice negotiation will cause a negotiationneeded event to be fired, in response to which your code should renegotiate as usual. however, because you have called restartice(), your call to createoffer() which occurs in the handler for negotiationneeded will trigger an ice restart rather than just a regular renegotiation. specifications spe...
RTCPeerConnection.setConfiguration() - Web APIs
d. syntaxerror one or more of the urls provided in the configuration.iceservers list is invalid. example in this example, it has already been determined that ice restart is needed, and that negotiation needs to be done using a different ice server. ...
RTCPeerConnection: signalingstatechange event - Web APIs
rtcpeerconnection to notify it that its signaling state, as indicated by the signalingstate property, has changed. bubbles no cancelable no interface event event handler property rtcpeerconnection.onsignalingstatechange examples given an rtcpeerconnection, pc, and an updatestatus() function that presents status information to the user, this code sets up an event handler to let the user know when the ice negotiation process finishes up. pc.addeventlistener("signalingstatechange", ev => { switch(pc.signalingstate) { case "stable": updatestatus("ice negotiation complete"); break; } }, false); using onsignalingstatechange, it looks like this: pc.onsignalingstatechange = ev => { switch(pc.signalingstate) { case "...
RTCPeerConnection: track event - Web APIs
ter a new track has been added to an rtcrtpreceiver which is part of the connection. bubbles yes cancelable no interface rtctrackevent event handler property ontrack by the time this event is delivered, the new track has been fully added to the peer connection. see track event types in rtctrackevent for details. examples this example shows code that creates a new rtcpeerconnection, then adds a new track event handler. pc = new rtcpeerconnection({ iceservers: [ { urls: "turn:fake.turnserver.url", username: "someusername", credential: "somepassword" } ] }); pc.addeventlistener("track", e => { videoelement.srcobject = e.streams[0]; hangupbutton.disabled = false; }, false); the event handler assigns the ...
RTCPeerConnectionIceErrorEvent - Web APIs
properties the rtcpeerconnectioniceerrorevent interface includes the properties found on the event interface, as well as the following properties: address read only a domstring providing the local ip address used to communicate with the stun or turn server being used to negotiate the connection, or null if the local ip address has not yet been exposed as part of a local ice candidate. errorcode read only an unsigned integer value stating the numeric stun error code returned by the stun or turn server. if no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid stun error codes. the 701 error is fired only once per server url, and only while the is icegatheringstate is gathering. errortext read only a domstring containing th...
RTCRtpEncodingParameters.scaleResolutionDownBy - Web APIs
g encoding. this property is only available for tracks whose kind is video. syntax rtpencodingparameters.scaleresolutiondownby = scalingfactor; rtpencodingparameters = { scaleresolutiondownby: scalingfactor }; value a double-precison floating-point number specifying the amount by which to reduce the size of the video during encoding. the default value, 1.0, means that the video will be encoded at its original size. a value of 2.0 would reduce the size of the video by a factor of 2 both horizontally and vertically, resulting in a video 25% the original size. a value less than 1.0 would cause the video to get larger rather than smaller, which is not the intent of this property. therefore, specifying a value less than 1.0 is not permitted and will cause a rangeerror exception to be thro...
RTCRtpParameters - Web APIs
the rtcrtpparameters dictionary is the basic object describing the parameters of an rtp transport. it is extended separately for senders and receivers in the form of the rtcrtpsendparameters and rtcrtpreceiveparameters dictionaries. to obtain the parameters of a sender or receiver, call its getparameters() method: getparameters() getparameters() properties codecs an array of rtcrtpcodecparameters objects describing the set of codecs from which the sender or receiver will choose. this parameter cannot be changed once initially set. headerextensions an array of zero or more rtp header extensions, each identifying an extension supported by the sender or receiver. header extensions are described in rfc 3550: 5.3.1. this parameter cannot be changed once initially set. rtcp an rtcrtc...
RTCRtpReceiver - Web APIs
sport. use the transport property instead. methods rtcrtpreceiver.getcontributingsources() returns an array of rtcrtpcontributingsource instances for each unique csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds. rtcrtpreceiver.getparameters() returns an rtcrtpparameters object which contains information about how the rtc data is to be decoded. rtcrtpreceiver.getstats() returns a promise whose fulfillment handler receives a rtcstatsreport which contains statistics about the incoming streams and their dependencies. rtcrtpreceiver.getsynchronizationsources() returns an array including one rtcrtpsynchronizationsource instance for each unique ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ...
RTCRtpSendParameters - Web APIs
om the rtcrtpparameters interface. degradationpreference specifies the preferred way the webrtc layer should handle optimizing bandwidth against quality in constrained-bandwidth situations; the value comes from the rtcdegradationpreference enumerated string type, and the default is balanced. encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media. priority a string from the rtcprioritytype enumerated type which indicates the encoding's priority. the default value is low. transactionid a string containing a unique id for the last set of parameters applied; this value is used to ensure that setparameters() can only be called to alter changes made by a specific previous call to getparameter...
RTCRtpStreamStats.firCount - Web APIs
stream falls behind and has to skip frames in order to catch up. syntax var fircount = rtcrtpstreamstats.fircount; value an integer value indicating how many fir packets have been received by the sender during the current connection. this value is available only on receivers for video tracks. the receiver sends a fir packet to the sender any time it falls bahind or loses packets and cannot decode the incoming stream any longer because of the lost data. this tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up. the higher fircount is, the more often frames were dropped, which may be an indication that the media's bit rate is too high for the available bandwidth, or that the receiving device is overburdened and is therefore unable to process the...
RTCRtpStreamStats.kind - Web APIs
u're targeting. syntax mediakind = rtcrtpstreamstats.kind; value a domstring whose value is "audio" if the track whose statistics are given by the rtcrtpstreamstats object contains audio, or "video" if the track contains video media. this string will always be the same as the one provided by the associated mediastreamtrack object's kind property. it will also match the statistics object's rtccodecstats.codec property's media type. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcrtpstreamstats.kind' in that specification. candidate recommendation initial definition. ...
RTCRtpStreamStats.pliCount - Web APIs
the plicount property of the rtcrtpstreamstats dictionary states the number of times the stream's receiving end sent a picture loss indication (pli) packet to the sender. a pli packet indicates that some amount of encoded video data has been lost for one or more frames. syntax var plicount = rtcrtpstreamstats.plicount; value an integer value indicating the number of times a pli packet was sent by the stream's receiver to the sender. a pli message is used by video decoders (running on the receiving end of the stream) to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. this may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situati...
RTCRtpStreamStats.sliCount - Web APIs
syntax var slicount = rtcrtpstreamstats.slicount; value an unsigned long integer indicating the number of sli packets the sender received from the receiver due to lost runs of macroblocks. a high value of slicount may be an indication of an unreliable network. for technical details, see rfc 4585: 6.3.2. ...
RTCRtpTransceiver.sender - Web APIs
the read-only sender property of webrtc's rtcrtptransceiver interface indicates the rtcrtpsender responsible for encoding and sending outgoing media data for the transceiver's stream. syntax var rtpsender = rtcrtptransceiver.sender; value an rtcrtpsender object used to encode and send media whose media id matches the current value of mid. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtptransceiver.sender' in that specification. candidate recommendation ...
RTCRtpTransceiver - Web APIs
the rtcrtpreceiver object that handles receiving and decoding incoming media. sender read only the rtcrtpsender object responsible for encoding and sending data to the remote peer. stopped indicates whether or not sending and receiving using the paired rtcrtpsender and rtcrtpreceiver has been permanently disabled, either due to sdp offer/answer, or due to a call to stop(). methods setcodecpreferences() a list of rtcrtpcodecparameters objects which override the default preferences used by the user agent for the transceiver's codecs. stop() permanently stops the rtcrtptransceiver. the associated sender stops sending data, and the associated receiver likewise stops receiving and decoding incoming data. specifications specification status comment webrtc 1...
RTCStatsReport - Web APIs
pair for the transport are deleted when the rtcpeerconnection changes its rtcpeerconnection.icegatheringstate to new during an ice restart. the active candidate pair is deleted after the transport switches to another candidate pair; this change cannot be detected otherwise. certificate an rtccertificatestats object providing statistics related to a certificate being used by an rtcicetransport. codec an rtccodecstats object containing statistics about a codec currently being used by rtp streams to send or receive data for the rtcpeerconnection. csrc an rtccontributingsourcestats object which contains statistics related to a contributing source (csrc) that contributed to an inbound rtp stream. data-channel an rtcdatachannelstats object which contains statistics about each rtcdatachannel ...
RTCStatsType - Web APIs
pair for the transport are deleted when the rtcpeerconnection changes its rtcpeerconnection.icegatheringstate to new during an ice restart. the active candidate pair is deleted after the transport switches to another candidate pair; this change cannot be detected otherwise. certificate an rtccertificatestats object providing statistics related to a certificate being used by an rtcicetransport. codec an rtccodecstats object containing statistics about a codec currently being used by rtp streams to send or receive data for the rtcpeerconnection. csrc an rtccontributingsourcestats object which contains statistics related to a contributing source (csrc) that contributed to an inbound rtp stream. data-channel an rtcdatachannelstats object which contains statistics about each rtcdatachannel ...
Range.compareBoundaryPoints() - Web APIs
end_to_start compares the end boundary-point of sourcerange to the start boundary-point of range. range.start_to_end compares the start boundary-point of sourcerange to the end boundary-point of range. range.start_to_start compares the start boundary-point of sourcerange to the start boundary-point of range. if the value of the parameter is invalid, a domexception with a notsupportederror code is thrown. sourcerange a range to compare boundary points with the range. example var range, sourcerange, compare; range = document.createrange(); range.selectnode(document.getelementsbytagname("div")[0]); sourcerange = document.createrange(); sourcerange.selectnode(document.getelementsbytagname("div")[1]); compare = range.compareboundarypoints(range.start_to_end, sourcerange); specific...
Range - Web APIs
Web › API › Range
performance. range.tostring() returns the text of the range. range.comparenode() returns a constant representing whether the node is before, after, inside, or surrounding the range. range.comparepoint() returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the range. range.createcontextualfragment() returns a documentfragment created from a given string of code. range.getboundingclientrect() returns a domrect object which bounds the entire contents of the range; this would be the union of all the rectangles returned by range.getclientrects(). range.getclientrects() returns a list of domrect objects that aggregates the results of element.getclientrects() for all the elements in the range. range.intersectsnode() returns a boolean indicating wh...
ReadableStream.ReadableStream() - Web APIs
tegy is supplied, the default used is the same as a countqueuingstrategy with a high water mark of 1. return value an instance of the readablestream object. exceptions rangeerror the supplied type value is neither "bytes" nor undefined. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() fuction is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of ...
ReadableStream.getReader() - Web APIs
nding on the mode value. exceptions rangeerror the provided mode value is not "byob" or undefined. typeerror the stream you are trying to create a reader for is not a readablestream. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(f...
ReadableStream.tee() - Web APIs
ions typeerror the source stream is not a readablestream. examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui. see simple tee example for the full code. function teestream() { const teedoff = stream.tee(); fetchstream(teedoff[0], list2); fetchstream(teedoff[1], list3); } function fetchstream(stream, list) { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain ...
ReadableStreamBYOBReader - Web APIs
adablestreambyobreader interface of the streams api represents a byob ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom readablestream() constructor). constructor readablestreambyobreader() creates and returns a readablestreambyobreader object instance. properties readablestreambyobreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreambyobreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use i...
ReadableStreamDefaultController.close() - Web APIs
e readablestream.cancel() or readablestreamdefaultreader.cancel(). syntax readablestreamdefaultcontroller.close(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of...
ReadableStreamDefaultController.enqueue() - Web APIs
en chunk in the associated stream. syntax readablestreamdefaultcontroller.enqueue(chunk); parameters chunk the chunk to enqueue. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream — see controller.enqueue(string). a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is ru...
ReadableStreamDefaultController - Web APIs
roller.close() closes the associated stream. readablestreamdefaultcontroller.enqueue() enqueues a given chunk in the associated stream. readablestreamdefaultcontroller.error() causes any future interactions with the associated stream to error. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. note that a readablestreamdefaultcontroller object is provided as the parameter of the start() and pull() functions. when a button is pressed, the generation is stopped, the stream ...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
n instance of the readablestreamdefaultreader object. exceptions typeerror the supplied stream parameter is not a readablestream, or it is already locked for reading by another reader. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(f...
ReadableStreamDefaultReader.cancel() - Web APIs
eadable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the source object is not a readablestreamdefaultreader, or the stream has no owner. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (this code is based on our simple random stream example). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. when the stream is done (if (done)), we run reader.cancel() to cancel the stream, signalling that we don't need to use it any more. function fet...
ReadableStreamDefaultReader - Web APIs
the readablestreamdefaultreader interface of the streams api represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request). constructor readablestreamdefaultreader() creates and returns a readablestreamdefaultreader object instance. properties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreamdefaultreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreamdefaul...
RelativeOrientationSensor.RelativeOrientationSensor() - Web APIs
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
RelativeOrientationSensor - Web APIs
the relativeorientationsensor interface of the the sensor apis describes the device's physical orientation without regard to the earth's reference coordinate system. to use this sensor, the user must grant permission to the 'accelerometer', and 'gyroscope' device sensors through the permissions api. if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. this is not something that would ever be shown to a user. see feature-policy for implementation instructions. constructor relativeorientationsensor.relativeorientationsensor() creates a new relativeorientationsensor object. properties no specific properties; inherits methods from its ancestors orientationsensor and sensor. event handlers no specific event handlers;...
ReportingObserver - Web APIs
edia) { navigator.mozgetusermedia( constraints, success, failure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details. note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia() method twice. after the first time we call reportingobserver.takerecords(), which returns the first generated report and empties the queue. because of this, when the button is pressed only the second report is listed. specifications specification status comment reporting apithe definition of 'reportingob...
Request.destination - Web APIs
ion read-only property of the request interface returns a string describing the type of content being requested. the string must be one of those found in the requestdestination enumerated type or the empty string, which is the default value. the destination is used by the user agent to, for example, help determine which set of rules to follow for cors purposes, or how to navigate any complicated code paths that affect how specific types of request get handled. these destinations vary substantially in how they operate. some are simply data receptacles, where the received data is stored for processing later. others are script-based, in which case the received data is delivered to a script by calling it and passing the data along. script-based destinations include <script> elements, as well as ...
Resource Timing API - Web APIs
be a nice place to have a diagram showing the relationships between these segments of the resource loading time. resource size the performanceresourcetiming interface has three properties that can be used to obtain size data about a resource. the transfersize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. the encodedbodysize property returns the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. decodedbodysize returns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. other properties the nexthopprotocol property returns the network protocol used to fetch the ...
Response() - Web APIs
Web › API › Response › Response
ptional an object defining a body for the response. this can be null (which is the default value), or one of: blob buffersource formdata readablestream urlsearchparams usvstring init optional an options object containing any custom settings that you want to apply to the response, or an empty object (which is the default value). the possible options are: status: the status code for the reponse, e.g., 200. statustext: the status message associated with the status code, e.g., ok. headers: any headers you want to add to your response, contained within a headers object or object literal of bytestring key/value pairs (see http headers for a reference). examples in our fetch response example (see fetch response live) we create a new response object using the constr...
Response.redirect() - Web APIs
Web › API › Response › redirect
rl. note: this is mainly relevant to the serviceworker api. a controlling service worker could intercept a page's request and redirect it as desired. this will actually lead to a real redirect if a service worker sends it upstream. syntax var response = response.redirect(url, status); parameters url the url that the new response is to originate from. status optional an optional status code for the response (e.g., 302.) return value a response object. exceptions exception explanation rangeerror the specified status is not a redirect status. typeerror the specified url is invalid. example responseobj.redirect('https://www.example.com', 302); specifications specification status comment fetchthe definition o...
Response.redirected - Web APIs
ring when you call fetch(). see the example disallowing redirects, which shows this being done. syntax var isredirected = response.redirected; value a boolean which is true if the response indicates that your request was redirected. examples detecting redirects checking to see if the response comes from a redirected request is as simple as checking this flag on the response object. in the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under disallowing redirects below. fetch("awesome-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { e...
Response.status - Web APIs
Web › API › Response › status
syntax var mystatus = response.status; value a number (to be precise, an unsigned short). example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response status value to the console. ...
Response.statusText - Web APIs
syntax var mystatustext = response.statustext; value a bytestring. the default value is "". example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response statustext value to the console. ...
Response - Web APIs
Web › API › Response
operties response.headers read only the headers object associated with the response. response.ok read only a boolean indicating whether the response was successful (status in the range 200–299) or not. response.redirected read only indicates whether or not the response is the result of a redirect (that is, its url list has more than one entry). response.status read only the status code of the response. (this will be 200 for a success). response.statustext read only the status message corresponding to the status code. (e.g., ok for 200). response.trailers a promise resolving to a headers object, associated with the response with response.headers for values of the http trailer header. response.type read only the type of the response (e.g., basic, cors). response.url read...
SVGAElement.target - Web APIs
s to be opened when a link is activated. this property is used when there are multiple possible targets for the ending resource, like when the parent document is a mlti-frame html or xhtml document. syntax mylink.target = 'value'; value an svganimatedstring indicating the ending resource target that opens the document when the link is activated. sample values can be found here example the code is taken from the "svgaelement example code" ... var linkref = document.queryselector('a'); linkref.target ='_blank'; ... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'target' in that specification. recommendation browser compatibility the compatibility table on this page is generated fro...
SVGMarkerElement - Web APIs
methods this also inherits methods from its parent, svgelement, and implements properties from svgstylable. setorienttoangle(in svgangle angle) void sets the value of attribute orient to the given angle. exceptions: a domexception with code no_modification_allowed_err is raised when the object itself is read only. setorienttoauto() void sets the value of attribute orient to 'auto'. exceptions: a domexception with code no_modification_allowed_err is raised when the object itself is read only. ...
SVGMatrix - Web APIs
Web › API › SVGMatrix
flipy() post-multiplies the transformation [1 0 0 -1 0 0] and returns the resulting matrix as svgmatrix. svgmatrix.skewx() post-multiplies a skewx transformation on the current matrix and returns the resulting matrix as svgmatrix. svgmatrix.skewy() post-multiplies a skewy transformation on the current matrix and returns the resulting matrix as svgmatrix. exceptions a domexception with the code no_modification_allowed_err is raised when attempting updating a read-only attribute or when the object itself is read-only. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgmatrix' in that specification. recommendation initial definition ...
SVGNumber - Web APIs
Web › API › SVGNumber
the svgnumber interface corresponds to the <number> basic data type. an svgnumber object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. properties svgnumber.value a float representing the number. note: if the svgnumber is read-only, a domexception with the code no_modification_allowed_err is raised on an attempt to change the value. methods this interface doesn't provide any specific methods. specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgnumber' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgnumber' in that specification. recommend...
SVGPreserveAspectRatio - Web APIs
name type description align unsigned short the type of the alignment value as specified by one of the svg_preserveaspectratio_* constants defined on this interface. meetorslice unsigned short the type of the meet-or-slice value as specified by one of the svg_meetorslice_* constants defined on this interface. exceptions on setting: a domexception with code no_modification_allowed_err is raised on an attempt to change the value of an attribute on a read only object. methods the svgpreserveaspectratio interface do not provide any specific methods. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and sen...
SVGScriptElement - Web APIs
94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgscriptelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties svgscriptelement.type read only a domstring corresponding to the type attribute of the given <script> element. a domexception is raised with the code no_modification_allowed_err on an attempt to change the value of a read only attribut. svgscriptelement.crossorigin read only a domstring corresponding to the crossorigin attribute of the given <script> element. methods this interface doesn't implement any specific methods, but inherits methods from its parent interface, svgelement. specifications specification status comme...
Screen - Web APIs
Web › API › Screen
orientation (only works in fullscreen or for installed apps) methods inherited from eventtarget: eventtarget.addeventlistener() registers an event handler of a specific event type on the eventtarget. eventtarget.removeeventlistener() removes an event listener from the eventtarget. eventtarget.dispatchevent() dispatches an event to this eventtarget. additional methods in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties. see also webidl bindings. void seteventhandler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) example if (screen.pixeldepth < 8) { // use low-color version of page } else { // use regular, colorful page } specification ...
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
ginalpolicy: the originalpolicy of the securitypolicyviolationevent (required). referrer: the referrer of the securitypolicyviolationevent. if not included, the default value is "". sample: the sample of the securitypolicyviolationevent. if not included, the default value is "". sourcefile: the sourcefile of the securitypolicyviolationevent. if not included, the default value is "". statuscode: the statuscode of the securitypolicyviolationevent (required). violateddirective: the violateddirective of the securitypolicyviolationevent (required). return value a securitypolicyviolationevent object instance. example let spvevt = new securitypolicyviolationevent('foo', { ... }); specifications specification status comment content security policy level 3...
SecurityPolicyViolationEvent - Web APIs
hat caused the violation, usually the first 40 characters. this will only be populated if the resource is an inline script, event handler, or style — external resources causing a violation will not generate a sample. securitypolicyviolationevent.sourcefileread only a usvstring representing the uri of the document or worker in which the violation was found. securitypolicyviolationevent.statuscoderead only a number representing the http status code of the document or worker in which the violation occurred. securitypolicyviolationevent.violateddirectiveread only a domstring representing the directive whose enforcement uncovered the violation. examples document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.blockeduri); console.log(e.violateddirective); cons...
Selection - Web APIs
Web › API › Selection
ranges (for instance, to allow the user to select a column from a <table>). however, browsers other than gecko did not implement multiple ranges, and the specification also requires the selection to always have a single range. selection and input focus selection and input focus (indicated by document.activeelement) have a complex relationship that varies by browser. in cross-browser compatible code, it's better to handle them separately. safari and chrome (unlike firefox) currently focus the element containing selection when modifying the selection programmatically; it's possible that this may change in the future (see w3c bug 14383 and webkit bug 38696). behavior of selection api in terms of editing host focus changes the selection api has a common behavior (i.e., shared between browser...
Selection API - Web APIs
s in a variable, you perform a variety of operations on it, for example copying the selection to a text string using selection.tostring(), adding a range (as represented by a standard range object) to the selection (or removing one) with selection.addrange()/selection.removerange(), or changing the selection to be the entire contents of a dom node using selection.selectallchildren(). you can run code in response to the selection being changed, or a new selection being started, using the globaleventhandlers.onselectionchange and globaleventhandlers.onselectstart event handlers. selection api interfaces selection represents the range of text selected by the user or the current position of the caret. extensions to other interfaces window.getselection(), document.getselection() retu...
Sensor - Web APIs
Web › API › Sensor
this is not something that would ever be shown to a user. see feature-policy for implementation instructions. ...
Server-sent events - Web APIs
ver-sent events' in that specification. living standard see also tools eventsource polyfill for node.js remy sharp’s eventsource polyfill yaffle’s eventsource polyfill rick waldron’s jquery plugin intercooler.js declarative sse support related topics ajax javascript websockets other resources a twitter like application powered by server-sent events and its code on github. html5 and server-sent events server-sent events using asp.net ...
ServiceWorker.onstatechange - Web APIs
an eventlistener property called whenever an event of type statechange is fired; it is basically fired anytime the serviceworker.state changes. syntax serviceworker.onstatechange = function(statechangeevent) { ... } serviceworker.addeventlistener('statechange', function(statechangeevent) { ... } ) examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. var serviceworker; if (registration.installing) { serviceworker = registration.installing; document.queryselector('#kind').textcontent = 'installing'; } else if (registration.waiting) { serviceworker = registration.waiting; document.queryselector('#kind').textcontent = 'waiting'; } else if (registration.active) { ...
ServiceWorker.state - Web APIs
the state read-only property of the serviceworker interface returns a string representing the current state of the service worker. it can be one of the following values: installing, installed, activating, activated, or redundant. syntax someurl = serviceworker.state value a serviceworkerstate definition (see the spec.) examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. var serviceworker; if (registration.installing) { serviceworker = registration.installing; document.queryselector('#kind').textcontent = 'installing'; } else if (registration.waiting) { serviceworker = registration.waiting; document.queryselector('#kind').textcontent = 'waiting'; } else if...
ServiceWorker - Web APIs
nt. event handlers serviceworker.onstatechange read only an eventlistener property called whenever an event of type statechange is fired; it is basically fired anytime the serviceworker.state changes. methods the serviceworker interface inherits methods from its parent, worker, with the exception of worker.terminate — this should not be accessible from service workers. examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. if ('serviceworker' in navigator) { navigator.serviceworker.register('service-worker.js', { scope: './' }).then(function (registration) { var serviceworker; if (registration.installing) { servicewo...
ServiceWorkerContainer.ready - Web APIs
it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an active worker. once that condition is met, it resolves with the serviceworkerregistration. syntax navigator.serviceworker.ready.then(function(serviceworkerregistration) { ... }); value a promise that will never reject, and which may eventually resolve with a serviceworkerregistration. ...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
usage notes although examples demonstrating how to share subscription related information with the application server tend to use fetch(), this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example. consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using fetch() is robust enough to handle cases where attempts to exchange data fail. note: in earlier drafts of the specification, this event was defined to be sent when a pushsubscription has expired. examples this example, run in the context of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription. self.addeventlistener("pushsubscription...
ServiceWorkerMessageEvent.data - Web APIs
browsers, this property has been deprecated. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the data read-only property of the serviceworkermessageevent interface returns the event's data. it can be any data type. syntax var mydata = serviceworkermessageeventinstance.data; value any data type. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function...
ServiceWorkerMessageEvent.lastEventId - Web APIs
d. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the lasteventid read-only property of the serviceworkermessageevent interface represents, in server-sent events, the last event id of the event source. syntax var mylasteventid = serviceworkermessageeventinstance.lasteventid; value a domstring. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function...
ServiceWorkerMessageEvent.origin - Web APIs
as been deprecated. service worker messages will now use the messageevent interface, for consistency with other web messaging features. the origin read-only property of the serviceworkermessageevent interface returns the origin of the service worker's environment settings object. syntax var myorigin = serviceworkermessageeventinstance.origin; value a domstring. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function...
ServiceWorkerMessageEvent.ports - Web APIs
e the messageevent interface, for consistency with other web messaging features. the ports read-only property of the serviceworkermessageevent interface returns an array of messageport objects connected with the message channel the message is being sent through. syntax var myports = serviceworkermessageeventinstance.ports; value an array of messageport objects. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function...
ServiceWorkerMessageEvent.source - Web APIs
now use the messageevent interface, for consistency with other web messaging features. the source read-only property of the serviceworkermessageevent returns a reference to the serviceworker object of the associated service worker that sent the message. syntax var mysource = serviceworkermessageeventinstance.source; value a serviceworker or messageport object. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function...
ServiceWorkerMessageEvent - Web APIs
rkermessageevent.lasteventid read only represents, in server-sent events, the last event id of the event source. serviceworkermessageevent.source read only returns a reference to the service worker that sent the message. serviceworkermessageevent.ports read only returns an array of messageport objects. methods inherits methods from its parent, event. examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent. navigator.serviceworker.ready.then(function(reg) { ... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function...
ServiceWorkerRegistration - Web APIs
isplays the notification with the requested title. serviceworkerregistration.update() checks the server for an updated version of the service worker without consulting caches. serviceworkerregistration.unregister() unregisters the service worker registration and returns a promise. the service worker will finish any ongoing operations before it is unregistered. examples in this example, the code first checks whether the browser supports service workers and if so registers one. next, it adds an updatefound listener in which it uses the service worker registration to listen for further changes to the service worker's state. if the service worker hasn't changed since the last time it was registered, then the updatefound event will not be fired. if ('serviceworker' in navigator) { navigat...
SharedWorker() - Web APIs
urn value the created worker. exceptions a securityerror is raised if the document is not allowed to start workers, for example if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. ...
SharedWorker.port - Web APIs
Web › API › SharedWorker › port
the port property of the sharedworker interface returns a messageport object used to communicate and control the shared worker. syntax myworker.port; value a messageport object. example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. multiple scripts can then access the worker through a messageport object accessed using the sharedworker.port property — the port is started using its start() method: var myworker = new sharedworker('worker.js'); myworker.port.start(); for a full example, see our basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification. living standard ...
SharedWorker - Web APIs
t, eventtarget, and implements methods from abstractworker. example in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation. the different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows. the following code snippet shows creation of a sharedworker object using the sharedworker() constructor. both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property. if the onmessage event is attached using addeventlistener, the port is manually started using its start() method: myworker.po...
SharedWorkerGlobalScope.onconnect - Web APIs
syntax onconnect = function() { ... }; examples this example shows a shared worker file — when a connection to the worker occurs from a main thread via a messageport, the onconnect event handler fires. the event object is a messageevent. ...
SourceBuffer.abort() - Web APIs
parser state. the mse api is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. saying that, current implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again. for example, consider this code: sourcebuffer.addeventlistener('updateend', function (_) { ... }); sourcebuffer.appendbuffer(buf); let's say that after the call to appendbuffer but before the updateend event fires (i.e. a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a new point in time. in this case you would want to manually call abort() on the source buffer to st...
SourceBuffer.appendWindowEnd - Web APIs
the default value of appendwindowend is positive infinity. ...
SourceBuffer.appendWindowStart - Web APIs
the default value of appendwindowstart is the presentation start time, which is the beginning time of the playable media. ...
SpeechGrammarList.addFromString() - Web APIs
stored in a variable) and adds it to the speechgrammarlist as a new speechgrammar object. syntax speechgrammarlistinstance.addfromstring(string,weight); returns void. parameters string a domstring representing the grammar to be added. weight optional a float representing the weight of the grammar relative to other grammars present in the speechgrammarlist. the weight means the importance of this grammar, or the likelihood that it will be recognised by the speech recognition service. ...
SpeechGrammarList - Web APIs
methods speechgrammarlist.item() standard getter — allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax. speechgrammarlist.addfromuri() takes a grammar present at a specific uri and adds it to the speechgrammarlist as a new speechgrammar object. speechgrammarlist.addfromstring() takes a grammar present in a specific domstring within the code base (e.g. stored in a variable) and adds it to the speechgrammarlist as a new speechgrammar object. examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will...
SpeechRecognition() - Web APIs
the speechrecognition() constructor creates a new speechrecognition object instance. syntax var myrecognition = new speechrecognition(); parameters none. examples this code is excerpted from our speech color changer example. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrec...
SpeechRecognition.continuous - Web APIs
r continuous results are returned for each recognition, or only a single result. it defaults to single results (false.) syntax var mycontinuous = myspeechrecognition.continuous; myspeechrecognition.continuous = true; value a boolean representing the current speechrecognition's continuous status. true means continuous, and false means not continuous (single result each time.) examples this code is excerpted from our speech color changer example. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | pu...
SpeechRecognition.grammars - Web APIs
peechrecognition interface returns and sets a collection of speechgrammar objects that represent the grammars that will be understood by the current speechrecognition. syntax var mygrammars = myspeechrecognition.grammars; myspeechrecognition.grammars = myspeechgrammarlist; value a speechgrammarlist containing the speechgrammar objects that represent your grammar for your app. examples this code is excerpted from our speech color changer example. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | pu...
SpeechRecognition.interimResults - Web APIs
e.g. the speechrecognitionresult.isfinal property is false.) the default value for interimresults is false. syntax var myinterimresult = myspeechrecognition.interimresults; myspeechrecognition.interimresults = false; value a boolean representing the state of the current speechrecognition's interim results. true means interim results are returned, and false means they aren't. examples this code is excerpted from our speech color changer example. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | pu...
SpeechRecognition.lang - Web APIs
ion interface returns and sets the language of the current speechrecognition. if not specified, this defaults to the html lang attribute value, or the user agent's language setting if that isn't set either. syntax var mylang = myspeechrecognition.lang; myspeechrecognition.lang = 'en-us'; value a domstring representing the bcp 47 language tag for the current speechrecognition. examples this code is excerpted from our speech color changer example. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | pu...
SpeechRecognition.maxAlternatives - Web APIs
the maxalternatives property of the speechrecognition interface sets the maximum number of speechrecognitionalternatives provided per speechrecognitionresult. the default value is 1. syntax var mymaxalternativenumber = myspeechrecognition.maxalternatives; myspeechrecognition.maxalternatives = 2; value a number representing the maximum returned alternatives for each result. examples this code is excerpted from our speech color changer example. var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | pu...
SpeechRecognition.onresult - Web APIs
the onresult property of the speechrecognition interface represents an event handler that will run when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app (when the result event fires.) syntax myspeechrecognition.onresult = function() { ... }; examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0. // each speechrecognitionr...
SpeechRecognition: result event - Web APIs
the result event of the web speech api is fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app bubbles no cancelable no interface speechrecognitionevent event handler property onresult examples this code is excerpted from our speech color changer example. you can use the result event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('result', function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; }); or use the onresult event han...
SpeechRecognitionAlternative.confidence - Web APIs
of the speechrecognitionresult interface returns a numeric estimate of how confident the speech recognition system is that the recognition is correct. note: mozilla's implementation of confidence is still being worked on — at the moment, it always seems to return 1. syntax var myconfidence = speechrecognitionalternativeinstance.confidence; returns a number betwen 0 and 1. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechRecognitionAlternative.transcript - Web APIs
ult interface returns a string containing the transcript of the recognised word(s). for continuous recognition, leading or trailing whitespace will be included where necessary so that concatenation of consecutive speechrecognitionresults produces a proper transcript of the session. syntax var mytranscript = speechrecognitionalternativeinstance.transcript; returns a domstring. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechRecognitionAlternative - Web APIs
represents a single word that has been recognised by the speech recognition service. properties speechrecognitionalternative.transcript read only returns a string containing the transcript of the recognised word. speechrecognitionalternative.confidence read only returns a numeric estimate of how confident the speech recognition system is that the recognition is correct. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechRecognitionEvent.results - Web APIs
n subsequent result events are fired, interim results may be overwritten by a newer interim result or by a final result — they may even be removed, if they are at the end of the "results" array and the array length decreases. final results on the other hand will not be overwritten or removed. syntax var myresults = event.results; value a speechrecognitionresultlist object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechRecognitionEvent - Web APIs
read only returns the semantic meaning of what the user said. speechrecognitionevent.resultindex read only returns the lowest index value result in the speechrecognitionresultlist "array" that has actually changed. speechrecognitionevent.results read only returns a speechrecognitionresultlist object representing all the speech recognition results for the current session. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechRecognitionResult.item() - Web APIs
the item getter of the speechrecognitionresult interface is a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax. syntax var myalternative = speechrecognitionresultinstance[0]; returns a speechrecognitionalternative object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects ...
SpeechRecognitionResult.length - Web APIs
— the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) the number of alternatives contained in the result depends on what the speechrecognition.maxalternatives property was set to when the speech recognition was first initiated. syntax var mylength = speechrecognitionresultinstance.length; returns a number. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechRecognitionResult - Web APIs
e updated later on. speechrecognitionresult.length read only returns the length of the "array" — the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) methods speechrecognitionresult.item a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechRecognitionResultList.item() - Web APIs
the item getter of the speechrecognitionresultlist interface is a standard getter — it allows speechrecognitionresult objects in the list to be accessed via array syntax. syntax var myresult = speechrecognitionresultlistinstance[0]; returns a speechrecognitionresult object. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contai...
SpeechRecognitionResultList.length - Web APIs
the length read-only property of the speechrecognitionresultlist interface returns the length of the "array" — the number of speechrecognitionresult objects in the list. syntax var mylength = speechrecognitionresultlistinstance.length; returns a number. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0. // each speechrecognitionresult object contains speechrecognitionalternative objects that contain individual results.
SpeechRecognitionResultList - Web APIs
ts, or a single one if results are being captured in continuous mode. properties speechrecognitionresultlist.length read only returns the length of the "array" — the number of speechrecognitionresult objects in the list. methods speechrecognitionresultlist.item a standard getter that allows speechrecognitionresult objects in the list to be accessed via array syntax. examples this code is excerpted from our speech color changer example. recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects. // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0...
SpeechSynthesisErrorEvent - Web APIs
the speechsynthesiserrorevent interface of the web speech api contains information about any errors that occur while processing speechsynthesisutterance objects in the speech service. properties speechsynthesiserrorevent extends the speechsynthesisevent interface, which inherits properties from its parent interface, event. speechsynthesiserrorevent.error read only returns an error code indicating what has gone wrong with a speech synthesis attempt. methods speechsynthesiserrorevent extends the speechsynthesisevent interface, which inherits methods from its parent interface, event. examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var vo...
StereoPannerNode.pan - Web APIs
the value can range between -1 (full left pan) and 1 (full right pan). syntax var audioctx = new audiocontext(); var pannode = audioctx.createstereopanner(); pannode.pan.value = -0.5; returned value an a-rate audioparam containing the panning to apply. note: though the audioparam returned is read-only, the value it represents is not. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value. in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. mo...
StereoPannerNode - Web APIs
eakers" constructor stereopannernode() creates a new instance of a stereopannernode object. properties inherits properties from its parent, audionode. stereopannernode.pan read only is an a-rate audioparam representing the amount of panning to apply. methods no specific method; inherits methods from its parent, audionode. example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value. in the javascript we create a mediaelementaudiosourcenode and a stereopannernode, and connect the two together using the connect() method. we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. mo...
Storage API - Web APIs
note: this feature is available in web workers. ...
Streams API - Web APIs
simple random stream: this example shows how to use a custom stream to generate random strings, enqueue them as chunks, and then read them back out again. simple tee example: this example extends the simple random stream example, showing how a stream can be teed and both resulting streams can be read independently. simple writer: this example shows how to to write to a writable stream, then decode the stream and write the contents to the ui. unpack chunks of a png: this example shows how pipethrough() can be used to transform a readablestream into a stream of other data types by transforming a data of a png file into a stream of png chunks. examples from other developers: progress indicators with streams, service workers, & fetch. specifications specification status ...
StylePropertyMapReadOnly.forEach() - Web APIs
indexoptional the index of the current element being processed. arrayoptional the stylepropertymapreadonly thatforeach() is being called on. ...
SubmitEvent() - Web APIs
esent a submit event fired at an html form. syntax let submitevent = new submitevent(type,eventinitdict); parameters type a domstring indicating the event which occurred. for submitevent, this is always submit. eventinitdict optional an optional dictionary of initial values for the event's properties. return value a submitevent object configured using the given inputs. examples this code snippet locates a form in the current document, and then an html <button> within the form with the class submit on it. next, a new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found). then the event is sent to the form, telling the form that it's been submitted by the button. const form = document.queryselector("form"); const fo...
Text.wholeText - Web APIs
Web › API › Text › wholeText
nly property returns the full text of all text nodes logically adjacent to the node. the text is concatenated in document order. this allows to specify any text node and obtain all adjacent text as a single string. ...
TextMetrics.width - Web APIs
Web › API › TextMetrics › width
the read-only width property of the textmetrics interface contains the text's advance width (the width of that inline box) in css pixels. examples given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('foo'); // textmetrics object text.width; // 16; specifications specification html living standardthe definition of 'textmetrics.width' in that specification. ...
TextTrack - Web APIs
Web › API › TextTrack
e. needs details texttrack.kind read only returns a domstring indicating what kind of text track the texttrack describes. the value must be one of those in the texttrackkind enum. texttrack.label read only a human-readable domstring which contains the text track's label, if one is present; otherwise, this is an empty string (""), in which case a custom label may need to be generated by your code using other attributes of the track, if the track's label needs to be exposed to the user. texttrack.language read only a domstring which specifies the text language in which the text track's contents is written. the value must adhere to the format specified in the tags for identifying languages (bcp 47) document from the ietf, just like the html lang attribute. for example, this can be "en-us...
Touch.pageX - Web APIs
Web › API › Touch › pageX
his example illustrates how to access the touch object's touch.pagex and touch.pagey properties. the touch.pagex property is the horizontal coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. the touch.pagey property is the vertical coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. when the touchmove event handler is invoked, each touch point's touch.pagex and touch.pagey coordinates are accessed via the event's touchevent.changedtouches list. // register a touchmove listeners for the 'source' element var src = docu...
Touch.pageY - Web APIs
Web › API › Touch › pageY
his example illustrates how to access the touch object's touch.pagex and touch.pagey properties. the touch.pagex property is the horizontal coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. the touch.pagey property is the vertical coordinate of a touch point relative to the viewport (in css pixels), including any scroll offset. in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface. when the touchmove event handler is invoked, each touch point's touch.pagex and touch.pagey coordinates are accessed via the event's touchevent.changedtouches list. // register a touchmove listeners for the 'source' element var src = docu...
Touch.radiusX - Web APIs
Web › API › Touch › radiusX
point's touch.rotationangle. likewise, the touch.radiusy property is the radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the axis perpendicular to that indicated by touch.rotationangle. the touch.rotationangle is the angle (in degrees) that the ellipse described by radiusx and radiusy is rotated clockwise about its center. the following simple code snippet, registers a single handler for the touchstart, touchmove and touchend events. when the src element is touched, the element's width and height will be calculate based on the touch point's radiusx and radiusy values and the element will then be rotated using the touch point's rotationangle. <div id="src"> ... </div> var src = document.getelementbyid("src"); src.addeventlistener('touchs...
Touch.screenX - Web APIs
Web › API › Touch › screenX
screen, not including any scroll offset. example this example illustrates how to access the touch object's touch.screenx and touch.screeny properties. the touch.screenx property is the horizontal (x) coordinate of a touch point relative to the screen in css pixels. the touch.screeny property is the vertical coordinate of a touch point relative to the screen in css pixels. in following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of source and then releases contacts with the surface. when the touchstart event handler is invoked, each touch point's touch.screenx and touch.screeny coordinates are accessed. // register a touchstart listeners for the 'source' element var src = document.getelementbyid("source"); src.addeventlistener('touch...
Touch.target - Web APIs
Web › API › Touch › target
to attach the touch listeners directly to the target. syntax var el = touchpoint.target; return value el the target element of the touch object. example this example illustrates how to access the touch object's touch.target property. the touch.target property is an element (eventtarget) on which a touch point is started when contact is first placed on the surface. in following simple code snippet, we assume the user initiates one or more touch contacts on the source element. when the touchstart event handler for this element is invoked, each touch point's touch.target property is accessed via the event's touchevent.targettouches list. // register a touchmove listener for the 'source' element var src = document.getelementbyid("source"); src.addeventlistener('touchstart', function...
TouchEvent.altKey - Web APIs
Web › API › TouchEvent › altKey
otherwise, it is false. this property is read only . syntax var altenabled = touchevent.altkey; return value altenabled true if the alt key is enabled for this event; and false if the alt is not enabled. example this example illustrates how to access the touchevent key modifier properties: touchevent.altkey, touchevent.ctrlkey, touchevent.metakey and touchevent.shiftkey. in following code snippet, the touchstart event handler logs the state of the event's modifier keys. someelement.addeventlistener('touchstart', function(e) { // log the state of this event's modifier keys console.log("altkey = " + e.altkey); console.log("ctrlkey = " + e.ctrlkey); console.log("metakey = " + e.metakey); console.log("shiftkey = " + e.shiftkey); }, false); specifications s...
TouchEvent.changedTouches - Web APIs
nt.changedtouches; return value changes a touchlist whose touch objects include all the touch points that contributed to this touch event. example this example illustrates the touchevent object's touchevent.changedtouches property. the touchevent.changedtouches property is a touchlist object that contains one touch object for each touch point which contributed to the event. in following code snippet, the touchmove event handler iterates through the changedtouches list and prints the identifier of each touch point that changed since the last event. someelement.addeventlistener('touchmove', function(e) { // iterate through the list of touch points that changed // since the last event and print each touch point's identifier. for (var i=0; i < e.changedtouches.length; i++) { ...
TouchEvent.targetTouches - Web APIs
he current target element. example this example illustrates the touchevent object's touchevent.targettouches property. the touchevent.targettouches property is a touchlist object that includes those tps that are currently touching the surface and started on the element that is the target of the current event. as such, the targettouches list is a strict subset of the touches list. in following code snippet, the function compares the length of the touches list to the the length of the targettouches list and returns true if the lengths are the same and returns false otherwise. function touches_in_target(ev) { // return true if all of the touches are within the target element; // otherwise return false. return (ev.touches.length == ev.targettouches.length ? true : false); } specificat...
TouchEvent.touches - Web APIs
t are still in contact with the touch surface, regardless of whether or not they've changed or what their target element was at touchstart time. example this example illustrates the touchevent object's touchevent.touches property. the touchevent.touches property is a touchlist object and containing a list of touch objects for every point of contact currently touching the surface. in following code snippet, the touchstart event handler checks the length of the touchevent.touches list to determine the number of touch points that were activated and then invokes different handlers depending on the number of touch points. someelement.addeventlistener('touchstart', function(e) { // invoke the appropriate handler depending on the // number of touch points. switch (e.touches.length) { ...
TouchEvent - Web APIs
ument window and moved into the browser's ui area, a plug-in, or other external content. the user has placed more touch points on the screen than can be supported, in which case the earliest touch in the touchlist gets canceled. using with addeventlistener() and preventdefault() it's important to note that in many cases, both touch and mouse events get sent (in order to let non-touch-specific code still interact with the user). if you use touch events, you should call preventdefault() to keep the mouse event from being sent as well. the exception to this is chrome, starting with version 56 (desktop, chrome for android, and android webview), where the default value for the passive option for touchstart and touchmove is true and calls to preventdefault() will have no effect. to override thi...
TouchList.item() - Web APIs
Web › API › TouchList › item
the specified index in the touchlist. syntax var touchpoint = touchlist.item(index); parameters index the index of the touch object to retrieve. the index is a number in the range of 0 to one less than the length of the touchlist. return value touchpoint the requested touch object from the touchlist. returns null if the index is not less than the length of the list. example this code example illustrates the use of the touchlist interface's item method and the length property. target = document.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item in the touches list var touch; if (ev.ta...
TouchList.length - Web APIs
Web › API › TouchList › length
the length read-only property indicates the number of items (touch points) in a given touchlist. syntax var numtouches = touchlist.length; return value numtouches the number of touch points in touchlist. example this code example illustrates the use of the touchlist interface's item method and the length property. target = document.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item in the touches list var touch; if (ev.targettouches.length >= 1) touch = ev.targettouches.item(0); else touch = ev.touches.item(0); }, false); specifications specification status co...
Supporting both TouchEvent and MouseEvent - Web APIs
at may affect an application. if the browser fires both touch and mouse events because of a single user input, the browser must fire a touchstart before any mouse events. consequently, if an application does not want mouse events fired on a specific touch target element, the element's touch event handlers should call preventdefault() and no additional mouse events will be dispatched. here is a code snippet of the touchmove event handler calling preventdefault(). // touchmove handler function process_touchmove(ev) { // call preventdefault() to prevent any further handling ev.preventdefault(); } event order although the specific ordering of touch and mouse events is implementation-defined, the standard indicates the following order is typical: for single input: touchstart zero or ...
Touch events - Web APIs
+) { var 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.ident...
TrackDefault.TrackDefault() - Web APIs
a domstring specifying the id of the specific track that the sourcebuffer should apply to. if not specified, this value will be an empty string and the sourcebuffer can contain any tracks of the specified type. errors when this constructor is invoked, the following errors can occur: error explanation invalidaccesserror the supplied language is not a valid language code, e.g. en-us. typeerror there are values specified in the kinds array that do not apply to the specified type. example tbd ...
TrackDefault.language - Web APIs
en-us. syntax var mylanguage = trackdefault.language; value a domstring. example tbd ...
UIEvent.pageX - Web APIs
Web › API › UIEvent › pageX
event relative to the whole document. this property was never part of any standard, and was only implemented across a subset of browsers, and only for a limited number of versions. a standardized version of pagex was added to the mouseevent interface, however, and is well-supported. you should not expect to find pagex on any non-mouse events. do not look for pagex on any non-mouse events in new code and update existing code as soon as possible. syntax var pos = event.pagex value an integer value, in pixels, indicating the x coordinate at which the mouse pointer was located when the event occurred. this value is relative to the left edge of the entire document, regardless of the current horizontal scrolling offset of the document. examples for an example, see the documentation for the ...
UIEvent - Web APIs
Web › API › UIEvent
rdinate of the event relative to the whole document. uievent.sourcecapabilities read only returns an instance of the inputdevicecapabilities interface, which provides information about the physical device responsible for generating a touch event. uievent.viewread only returns a windowproxy that contains the view that generated the event. uievent.which read only returns the numeric keycode of the key pressed, or the character code (charcode) for an alphanumeric key pressed. methods this interface also inherits methods of its parent, event. uievent.inituievent() initializes a uievent object. if the event has already being dispatched, this method does nothing. specifications specification status comment inputdevicecapabilities draft added sou...
URL.createObjectURL() - Web APIs
formance and memory usage, if there are safe times when you can explicitly unload them, you should do so. using object urls for media streams in older versions of the media source specification, attaching a stream to a <video> element required creating an object url for the mediastream. this is no longer necessary, and browsers are removing support for doing this. important: if you still have code that relies on createobjecturl() to attach streams to media elements, you need to update your code to simply set srcobject to the mediastream directly. specifications specification status comment file apithe definition of 'createobjecturl()' in that specification. working draft initial definition. media source extensionsthe definition of 'url' in that spe...
URL.hash - Web APIs
Web › API › URL › hash
if the url does not have a fragment identifier, this property contains an empty string — "". note: this feature is available in web workers. syntax const string = url.hash url.hash = newhash value a usvstring. ...
URL.origin - Web APIs
Web › API › URL › origin
the exact structure varies depending on the type of url: for http or https urls, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified). for file: urls, the value is browser dependant. for blob: urls, the origin of the url following blob: will be used, e.g "blob:https://mozilla.org" will be returned as "https://mozilla.org". note: this feature is available in web workers. syntax const originstring = url.origin value a usvstring. ...
URL.searchParams - Web APIs
Web › API › URL › searchParams
note: this feature is available in web workers. syntax const urlsearchparams = url.searchparams value a urlsearchparams object. examples if the url of your page is https://example.com/?name=jonathan%20smith&age=18 you could parse out the name and age parameters using: let params = (new url(document.location)).searchparams; let name = params.get('name'); // is the string "jonathan smith". ...
URLSearchParams() - Web APIs
a leading '?' character is ignored. a sequence of usvstring pairs, representing names/values. a record of usvstring keys and usvstring values. return value a urlsearchparams object instance. ...
URLSearchParams.set() - Web APIs
value void. examples let's start with a simple example: let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a third parameter. params.set('baz', 3); params.tostring(); // "foo=1&bar=2&baz=3" below is a real-life example demonstrating how to create a url and set some search parameters. you can copy and paste the example in a code environment like codepen, jsfiddle, or the multi-line javascript interpreter in firefox. line #41: comment out this line to stop dumping the search parameters to the console (debug). line #43: dumps the generated object and it's string representation to the console (info). line #44: tries to automatically open a new window/tab with the generated url (when uncommented). 'use strict' functi...
URLSearchParams.sort() - Web APIs
this method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). note: this feature is available in web workers. syntax searchparams.sort(); parameters none. return value undefined. ...
URLSearchParams - Web APIs
ver, it will strip an initial leading ? off of a string, if present. ...
URLUtilsReadOnly.origin - Web APIs
for url using file: scheme, the value is browser dependant. this version of origin is implemented by workerlocation for use on workers. ...
USB.requestDevice() - Web APIs
Web › API › USB › requestDevice
of the usb interface returns a promise that resolves with an instance of usbdevice if the specified device is found. calling this function triggers the user agent's pairing flow. syntax usb.requestdevice([filters]) parameters filters an array of filter objects for possible devices you would like to pair. each filter object can have the following properties: vendorid productid classcode subclasscode protocolcode serialnumber return value a promise that resolves with an instance of usbdevice. example the following example looks for one of two usb devices. notice that two product ids are specified. both are passed to requestdevice(). this triggers a user-agent flow that prompts the user to select a device for pairing. only the selected device is passed to then(). t...
USBDevice.productID - Web APIs
the productid read only property of the usbdevice interface the manufacturer-defined code that identifies a usb device. syntax var serialnumber = usbdevice.productid value the manufacturer-defined code that identifies a usb device. specifications specification status comment webusbthe definition of 'productid' in that specification. draft initial definition. ...
USBDevice - Web APIs
Web › API › USBDevice
mantic versioning scheme. usbdevice.deviceversionsubminor read only the patch version number of the device in a semantic versioning scheme. usbdevice.manufacturername read only the of the organization that manufactured the usb device. usbdevice.opened read only indicates whether a session has been started with a paired usb device. usbdevice.productid read only the manufacturer-defined code that identifies a usb device. usbdevice.productname read only the manufacturer-defined name that identifies a usb device. usbdevice.serialnumber read only the manufacturer-defined serial number for the specific usb device. usbdevice.usbversionmajor read only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbve...
USBEndpoint - Web APIs
he packets that data sent through this endpoint will be divided into. examples while sometimes the developer knows ahead of time the exact layout of a device's endpoints there are cases where this must be discovered at runtime. for example, a usb serial device must provide bulk input and output endpoints but their endpoint numbers will depend on what other interfaces the device provides. this code identifies the correct endpoints by searching for the interface implementing the usb cdc interface class and then identifying the candidate endpoints based on their type and direction. let inendpoint = undefined; let outendpoint = undefined; for (const interface of device.configuration.interfaces) { // only support devices with out multiple alternate interfaces. const alternate = interface.
USVString - Web APIs
Web › API › USVString
usvstring corresponds to the set of all possible sequences of unicode scalar values. usvstring maps to a string when returned in javascript; it's generally only used for apis that perform text processing and need a string of unicode scalar values to operate on. usvstring is equivalent to domstring except for not allowing unpaired surrogate codepoints. unpaired surrogate codepoints present in usvstring are converted by the browser to unicode 'replacement character' u+fffd, (�). specifications specification status comment web idlthe definition of 'usvstring' in that specification. candidate recommendation initial definition. ...
Using the User Timing API - Web APIs
t they are placed between two marks thus they are effectively a midpoint between two marks. this document shows how to create mark and measure performance entry types and how to use user timing methods (which are extensions of the performance interface) to retrieve and remove entries from the browser's performance timeline. a live version of the examples is available on github, as is the source code. pull requests, enhancement requests and bug reports are welcome. performance marks a performance mark is a named performance entry that is created by the application at some location in an application. the mark is a timestamp in the browser's performance timeline. creating a performance mark the performance.mark() method is used to create a performance mark. the method takes one argument, th...
User Timing API - Web APIs
the application and can be set at any location in an application. measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. this document provides an overview of the mark and measure performance event types including the four user timing methods that extend the performance interface. for more details and example code regarding these two performance event types and the methods, see using the user timing api. performance marks a performance mark is a named performance entry that is created by the application. the mark is a timestamp in the browser's performance timeline. creating a performance mark the performance.mark() method is used to create a performance mark. the method takes one argument, the name of...
ValidityState.patternMismatch - Web APIs
password, or search -- and the pattern value is set to a valid regular expression, if the value don't doesn't conform to the constraints set by the pattern value, the patternmismatch property will be true. ...
validityState.tooLong - Web APIs
specifications specification status comment html living standardthe definition of 'validitystate.toolong' in that specification. ...
validityState.tooShort - Web APIs
specifications specification status comment html living standardthe definition of 'validitystate.tooshort' in that specification. ...
Vibration API - Web APIs
the vibration api offers web apps the ability to access this hardware, if it exists, and does nothing if the device doesn't support it. describing vibrations vibration is described as a pattern of on-off pulses, which may be of varying lengths. the pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses. vibration is controlled with a single method: navigator.vibrate(). ...
VideoTrack - Web APIs
main". label read only a domstring providing a human-readable label for the track. for example, a track whose kind is "sign" might have a label of "a sign-language interpretation". this string is empty if no label is provided. language read only a domstring specifying the video track's primary language, or an empty string if unknown. the language is specified as a bcp 47 (rfc 5646) language code, such as "en-us" or "pt-br". sourcebuffer read only the sourcebuffer that created the track. returns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source. usage notes to get a videotrack for a given media element, use the element's videotracks property, which returns a videotracklist ...
VisualViewport - Web APIs
vant oneventname property of this interface. resize fired when the visual viewport is resized. also available via the visualviewport.onresize property. scroll fired when the visual viewport is scrolled. also available via the visualviewport.onscroll property. examples hiding an overlaid box on zoom this example, taken from the visual viewport readme, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in. this is a nice way to improve the user experience when zooming in on pages. a live sample is also available. var bottombar = document.getelementbyid('bottombar'); var viewport = window.visualviewport; function resizehandler() { if (viewport.scale > 1.3) bottombar.style.display = "none"; else ...
Visual Viewport API - Web APIs
sualviewport object. if this property doesn't exist, the api is unsupported. interfaces visualviewport represents the visual viewport for a given window. a window's visualviewport object provides information about the viewport's position and size, and receives the resize and event:visualviewport:scroll events you can onitor to know when chances occur to the window's viewport. example the code below is based on the sample the specification, though it adds a few things that make it function better. it shows a function called viewporthandler(). when called it queries the offsetleft and height properties for values it uses in a css translate() method. you invoke this function by passing it to both event calls. one thing that may not be clear in this example is the use of the pendingupdat...
WEBGL_compressed_texture_etc - Web APIs
ession. ext.compressed_signed_r11_eac one-channel (red) signed format compression. ext.compressed_rg11_eac two-channel (red and green) unsigned format compression. ext.compressed_signed_rg11_eac two-channel (red and green) signed format compression. ext.compressed_rgb8_etc2 compresses rgb8 data with no alpha channel. ext.compressed_rgba8_etc2_eac compresses rgba8 data. the rgb part is encoded the same as rgb_etc2, but the alpha part is encoded separately. ext.compressed_srgb8_etc2 compresses srgb8 data with no alpha channel. ext.compressed_srgb8_alpha8_etc2_eac compresses srgba8 data. the srgb part is encoded the same as srgb_etc2, but the alpha part is encoded separately. ext.compressed_rgb8_punchthrough_alpha1_etc2 similar to rgb8_etc, but with ability to punch through the al...
WEBGL_draw_buffers.drawBuffersWEBGL() - Web APIs
ext.color_attachment6_webgl ext.color_attachment7_webgl ext.color_attachment8_webgl ext.color_attachment9_webgl ext.color_attachment10_webgl ext.color_attachment11_webgl ext.color_attachment12_webgl ext.color_attachment13_webgl ext.color_attachment14_webgl ext.color_attachment15_webgl return value none. examples see webgl_draw_buffers for more context with this example code. ext.drawbufferswebgl([ ext.color_attachment0_webgl, // gl_fragdata[0] ext.color_attachment1_webgl, // gl_fragdata[1] ext.color_attachment2_webgl, // gl_fragdata[2] ext.color_attachment3_webgl // gl_fragdata[3] ]); specifications specification status comment webgl_draw_buffersthe definition of 'webgl_draw_buffers' in that specification. recommendation ini...
WEBGL_draw_buffers - Web APIs
r, ext.color_attachment3_webgl, gl.texture_2d, tx[3], 0); mapping the color attachments to draw buffer slots that the fragment shader will write to using gl_fragdata: ext.drawbufferswebgl([ ext.color_attachment0_webgl, // gl_fragdata[0] ext.color_attachment1_webgl, // gl_fragdata[1] ext.color_attachment2_webgl, // gl_fragdata[2] ext.color_attachment3_webgl // gl_fragdata[3] ]); shader code that writes to multiple textures: <script type="x-shader/x-fragment"> #extension gl_ext_draw_buffers : require precision highp float; void main(void) { gl_fragdata[0] = vec4(0.25); gl_fragdata[1] = vec4(0.5); gl_fragdata[2] = vec4(0.75); gl_fragdata[3] = vec4(1.0); } </script> specifications specification status comment webgl_draw_buffersthe definition of 'web...
WaveShaperNode.curve - Web APIs
ut signal. syntax var audioctx = new audiocontext(); var distortion = audioctx.createwaveshaper(); distortion.curve = mycurvedataarray; // mycurvedataarray is a float32array value a float32array. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount...
WaveShaperNode.oversample - Web APIs
ount of samples before applying the shaping curve. syntax distortion.oversample = enumeratedvalue; values distortion is a waveshapernode. enumeratedvalue is one of 'none', '2x', or '4x'. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount...
WaveShaperNode - Web APIs
versampling is a technique for creating more samples (up-sampling) before applying the distortion effect to the audio signal. methods no specific method; inherits methods from its parent, audionode. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves because of their natural properties. their s-shape, for instance, helps create a smoother sounding result. we found the below distortion curve code on stack overflow. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ... function makedistortioncurve(amount...
WebGLProgram - Web APIs
the webglprogram is part of the webgl api and is a combination of two compiled webglshaders consisting of a vertex shader and a fragment shader (both written in glsl). to create a webglprogram, call the gl context's createprogram() function. after attaching the shader programs using attachshader(), you link them into a usable program. this is shown in the code below. var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. \n\n' + info; } see webglshader for information on creating the vertexshader and fragmentshader in the above e...
WebGLRenderingContext.attachShader() - Web APIs
the webglrenderingcontext.attachshader() method of the webgl api attaches either a fragment or vertex webglshader to a webglprogram. syntax void gl.attachshader(program, shader); parameters program a webglprogram. shader a fragment or vertex webglshader. examples the following code attaches pre-existing shaders to a webglprogram. var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program. \n\n' + info; } specifications specification status comment webgl 1.0the definition of 'attachshader' in that ...
WebGLRenderingContext.getShaderInfoLog() - Web APIs
le information. syntax gl.getshaderinfolog(shader); parameters shader a webglshader to query. return value a domstring that contains diagnostic messages, warning messages, and other information about the last compile operation. when a webglshader object is initially created, its information log will be a string of length 0. examples checking compilation messages /* load shader source code. */ gl.shadersource(shader, shadercode); /* compile shader source code. */ gl.compileshader(shader); var message = gl.getshaderinfolog(shader); if (message.length > 0) { /* message may be an error or a warning */ throw message; } specifications specification status comment webgl 1.0the definition of 'getshaderinfolog' in that specification. recommendation i...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
tex_shader. precisiontype a precision type value. either gl.low_float, gl.medium_float, gl.high_float, gl.low_int, gl.medium_int, or gl.high_int. return value a webglshaderprecisionformat object or null, if an error occurs. exceptions gl.invalid_enum if the shader or precision types aren't recognized. gl.invalid_operation if the shader compiler isn't supported. examples the following code gets the precision format of a gl.vertex_shader with a gl.medium_float precision type. var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float); // webglshaderprecisionformat { rangemin: 127, rangemax: 127, precision: 23 } specifications specification status comment webgl 1.0the...
WebGLRenderingContext.getShaderSource() - Web APIs
examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'getshadersource' in that specification. recommendation initial definition. ...
WebGLRenderingContext.linkProgram() - Web APIs
syntax void gl.linkprogram(program); parameters program the webglprogram to link. return value none. examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw new error('could not compile webgl program. ...
WebGLRenderingContext.shaderSource() - Web APIs
return value none. examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'shadersource' in that specification. recommendation initial definition. ...
Basic scissoring - Web APIs
« previousnext » ...
Canvas size and WebGL - Web APIs
ument.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 » ...
Clearing by clicking - Web APIs
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 this example is also available on github. « previousnext » ...
Clearing with colors - Web APIs
paragraph.innerhtml = "congratulations! your browser supports webgl. "; gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); // set the clear color to darkish green. gl.clearcolor(0.0, 0.5, 0.0, 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); }, false); the source code of this example is also available on github. « previousnext » ...
Color masking - Web APIs
« previousnext » ...
Detect WebGL - Web APIs
getcontext("webgl") || canvas.getcontext("experimental-webgl"); // report the result. if (gl && gl instanceof webglrenderingcontext) { paragraph.innerhtml = "congratulations! your browser supports webgl."; } else { paragraph.innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; } } }, false); the source code of this example is also available on github. « previousnext » ...
Hello vertex attributes - Web APIs
« previousnext » ...
Scissor animation - Web APIs
« previousnext » ...
Simple color animation - Web APIs
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. « previousnext » ...
WebGL constants - Web APIs
format compression. compressed_rg11_eac 0x9272 two-channel (red and green) unsigned format compression. compressed_signed_rg11_eac 0x9273 two-channel (red and green) signed format compression. compressed_rgb8_etc2 0x9274 compresses rbg8 data with no alpha channel. compressed_rgba8_etc2_eac 0x9275 compresses rgba8 data. the rgb part is encoded the same as rgb_etc2, but the alpha part is encoded separately. compressed_srgb8_etc2 0x9276 compresses srbg8 data with no alpha channel. compressed_srgb8_alpha8_etc2_eac 0x9277 compresses srgba8 data. the srgb part is encoded the same as srgb_etc2, but the alpha part is encoded separately. compressed_rgb8_punchthrough_alpha1_etc2 0x9278 similar to rg...
WebGL tutorial - Web APIs
webgl enables web content to use an api based on opengl es 2.0 to perform 3d rendering in an html <canvas> in browsers that support it without the use of plug-ins. webgl programs consist of control 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 ...
WebGL: 2D and 3D graphics for the web - Web APIs
Web › API › WebGL API
render targets, fragment depth. see also the blog post "webgl 2 lands in firefox" and webglsamples.org/webgl2samples for a few demos. guides and tutorials below, you'll find an assortment of guides to help you learn webgl concepts and tutorials that offer step-by-step lessons and examples. guides data in webgl a guide to variables, buffers, and other types of data used when writing webgl code. webgl best practices tips and suggestions to help you improve the quality, performance, and reliability of your webgl content. using extensions a guide to using webgl extensions. tutorials webgl tutorial a beginner's guide to webgl core concepts. a good place to start if you don't have previous webgl experience. examples a basic 2d webgl animation example this example demonstrate...
WebRTC coding guide - Web APIs
once you have an overall understanding of what webrtc does and how it works, your mind likely turns to implementation. how do you create a web application that uses two-way video or data streams without having to do all the hard work of compressing frames, building streams, and so forth by yourself? this coding guide will explain in depth how webrtc works, and will dive into actual code that uses webrtc to do useful things. there are no subpages at this time. if you need to learn more about the fundamentals of how webrtc and its protocols work, check out our high-level guides for webrtc. ...
WebRTC connectivity - Web APIs
cription contains not just the offer or answer under consideration, but any local ice candidates which have already been gathered since the offer or answer was created. similarly, pendingremotedescription includes any remote ice candidates which have been provided by calls to rtcpeerconnection.addicecandidate(). see the individual articles on these properties and methods for more specifics, and codecs used by webrtc for information about codecs supported by webrtc and which are compatible with which browsers. the codecs guide also offers guidance to help you choose the best codecs for your needs. ice candidates as well as exchanging information about the media (discussed above in offer/answer and sdp), peers must exchange information about the network connection. this is known as an ice ca...
Introduction to WebRTC protocols - Web APIs
mation through that server. you would create a connection with a turn server and tell all peers to send packets to the server which will then be forwarded to you. this obviously comes with some overhead so it is only used if there are no other alternatives. sdp session description protocol (sdp) is a standard for describing the multimedia content of the connection such as resolution, formats, codecs, encryption, etc. so that both peers can understand each other once the data is transferring. this is, in essence, the metadata describing the content and not the media content itself. technically, then, sdp is not truly a protocol, but a data format used to describe connection that shares media between devices. documenting sdp is well outside the scope of this documentation; however, there a...
WebRTC Statistics API - Web APIs
nted candidate-pair statistics describing the change from one rtcicetransport to another, such as during an ice restart. rtcicecandidatepairstats rtcstats certificate statistics about a certificate being used by an rtcicetransport. rtccertificatestats rtcstats codec statistics about a specific codec being used by streams being sent or received by this connection. rtccodecstats rtcstats csrc statistics for a single contributing source (csrc) that contributed to one of the connection's inbound rtp streams. rtcrtpcontributingsourcestats rtcstats data-channel statistics related...
WebSocket.close() - Web APIs
Web › API › WebSocket › close
the websocket.close() method closes the websocket connection or connection attempt, if any. if the connection is already closed, this method does nothing. syntax websocket.close(); parameters code optional a numeric value indicating the status code explaining why the connection is being closed. if this parameter is not specified, a default value of 1005 is assumed. see the list of status codes of closeevent for permitted values. reason optional a human-readable string explaining why the connection is closing. this string must be no longer than 123 bytes of utf-8 text (not characters). exceptions thrown invalid_access_err an invalid code was specified. syntax_err the reason string is too long or contains unpaired surrogates. note: in gecko, this method didn't support any pa...
WebSocket - Web APIs
Web › API › WebSocket
essage an event listener to be called when a message is received from the server. websocket.onopen an event listener to be called when the connection is opened. websocket.protocol read only the sub-protocol selected by the server. websocket.readystate read only the current state of the connection. websocket.url read only the absolute url of the websocket. methods websocket.close([code[, reason]]) closes the connection. websocket.send(data) enqueues data to be transmitted. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. close fired when a connection with a websocket is closed. also available via the onclose property error fired when a connection with a websocket has been closed ...
The WebSocket API (WebSockets) - Web APIs
server api implementation for node.js. total.js: web application framework for node.js (example: websocket chat) faye: a websocket (two-ways connections) and eventsource (one-way connections) for node.js server and client. signalr: signalr will use websockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same. caddy: a web server capable of proxying arbitrary commands (stdin/stdout) as a websocket. ws: a popular websocket client & server library for node.js. jsonrpc-bidirectional: asynchronous rpc which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client). cowboy: cowboy is a sm...
Tools for analyzing Web Audio usage - Web APIs
this article discusses tools available to help you do that. chrome a handy web audio inspector can be found in the chrome web store. edge add information for developers using microsoft edge. firefox firefox offers a native web audio editor. ...
Window: animationcancel event - Web APIs
cancelable no interface animationevent event handler property onanimationcancel the original target for this event is the element that had the animation applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: animationcancel. examples this code adds a listener to the animationcancel event. window.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); the same, but using the onanimationcancel property instead of addeventlistener(): window.onanimationcancel = () => { console.log('animation canceled'); }; see a live example of this event. specifications specification status comment ...
Window: animationiteration event - Web APIs
elable no interface animationevent event handler property onanimationiteration the original target for this event is the element that had the animation applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: animationiteration. ...
Window.clearImmediate() - Web APIs
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. ...
Window.controllers - Web APIs
the controllers property of the window interface returns the xul controllers of the chrome window. syntax controllers = window.controllers controllers is an object of type xulcontrollers (nsicontrollers). specification xul-specific. not part of specification. by default, a window's controller contains the code that supports the global window commands. chrome code can add controllers (to be used in conjunction with the godocommand and goupdatecommand functions in globaloverlay.js). however, the added controllers must be explicitly removed when the window is unloaded, as this is not done automatically. each missing removal can cause bug 415775: assertion: xpconnect is being called on a scope without a 'components' property! ...
window.dump() - Web APIs
Web › API › Window › dump
log. notes a common use of dump() is to debug javascript. the message passed to dump() is sent to the system console (native console) if the firefox process was started with the -console option. if the -console option was not specified then the output goes to stderr. output from dump() is not sent to the browser console. output can be sent to the browser console using console.log(). privileged code can also use components.utils.reporterror and nsiconsoleservice to log messages to the error console/browser console. dump() is also available to xpcom components implemented in javascript, even though window is not the global object in components. it is also explicitly made available in sandboxes. however, this use of dump is not affected by the preference mentioned below -- it will always be s...
Window: error event - Web APIs
t: 2rem; margin: .5rem; } img { width: 0; height: 0; } js const log = document.queryselector('.event-log-contents'); window.addeventlistener('error', (event) => { log.textcontent = log.textcontent + `${event.type}: ${event.message}\n`; console.log(event) }); const scripterror = document.queryselector('#script-error'); scripterror.addeventlistener('click', () => { const badcode = 'const s;'; eval(badcode); }); result specifications specification status ui events working draft ...
Window.getComputedStyle() - Web APIs
d be used to inspect the element's style — including those set by a <style> element or an external stylesheet. the element.style object should be used to set styles on that element, or inspect styles directly added to it from javascript manipulation or the global style attribute. the first argument must be an element. non-elements, like a text node, will throw an error. defaultview in many code samples, getcomputedstyle is used from the document.defaultview object. in nearly all cases, this is needless, as getcomputedstyle exists on the window object as well. it's likely the defaultview pattern was a combination of folks not wanting to write a testing spec for window and making an api that was also usable in java. use with pseudo-elements getcomputedstyle can pull style info from pseu...
Window.history - Web APIs
Web › API › Window › history
of before using them. example history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons. for security reasons the history object doesn't allow the non-privileged code to access the urls of other pages in the session history, but it does allow it to navigate the session history. there is no way to clear the session history or to disable the back/forward navigation from unprivileged code. the closest available solution is the location.replace() method, which replaces the current item of the session history with the provided url. specifications specif...
Window.onmozbeforepaint - Web APIs
ecko 11 (firefox 11 / thunderbird 11 / seamonkey 2.8)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. summary an event handler for the mozbeforepaint event. this is used in concert with the window.mozrequestanimationframe() method to perform smooth, synchronized animations from javascript code. syntax window.onmozbeforepaint = funcref; funcref is the handler function. example see window.mozrequestanimationframe() for an example. notes this event fires immediately before the browser window is repainted, if the event has been requested by one or more scripts calling window.mozrequestanimationframe(). the event handler receives as an input parameter an event whose timestamp pro...
Window.pageYOffset - Web APIs
it then gets a reference to the element we want to scroll into view calling getelementbyid() on the frame's htmliframeelement.contentdocument. with the target element in hand, we set the scrolltop of the frame's scrolli...
Window: popstate event - Web APIs
persisted user state is restored, if the browser chooses to do so. if the original and new entry's shared the same document, but had different fragments in their urls, send the hashchange event to the window. as you can see, the popstate event is nearly the last thing done in the process of navigating pages in this way. ...
Window.screenLeft - Web APIs
Web › API › Window › screenLeft
if(!window.screenleft) { window.screenleft = window.screenx; window.screentop = window.screeny; } specifications specification status comment css object model (cssom) view modulethe definition of 'window.screenleft...
Window.screenTop - Web APIs
Web › API › Window › screenTop
if(!window.screenleft) { window.screenleft = window.screenx; window.screentop = window.screeny; } specifications specification status comment css object model (cssom) view modulethe definition of 'window.screentop'...
Window.screenY - Web APIs
Web › API › Window › screenY
inpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degtorad(360), false); ctx.fill(); pelem.textcontent = 'window.screenleft: ' + window.screenleft + ', window.screentop: ' + window.screentop; window.requestanimationframe(positionelem); } window.requestanimationframe(positionelem); these work in exactly the same way as screenx/screeny. also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using screenx/screeny. if(!window.screenleft) { window.screenleft = window.screenx; window.screentop = window.screeny; } specifications specification status comment css object model (cssom) view modulethe definition of 'window.screeny' in that specifi...
Window: transitioncancel event - Web APIs
interface transitionevent event handler property globaleventhandlers.ontransitioncancel the original target for this event is the element that had the transition applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitioncancel. examples this code adds a listener to the transitioncancel event: window.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): window.ontransitioncancel = () => { console.log('transition canceled'); }; see a live example of this event. specifications specification status comment...
Window: transitionend event - Web APIs
of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. the original target for this event is the element that had the transition applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionend. examples this code adds a listener to the transitionend event: window.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend property instead of addeventlistener(): window.ontransitionend = () => { console.log('transition ended'); }; see a live example of this event. specifications specification status comment css ...
Window: transitionrun event - Web APIs
cancelable no interface transitionevent event handler property ontransitionrun the original target for this event is the element that had the transition applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionrun. examples this code adds a listener to the transitionrun event: window.addeventlistener('transitionrun', () => { console.log('transition is running but hasn't necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): window.ontransitionrun = () => { console.log('transition started running'); }; see a live example of this event. specification...
Window: transitionstart event - Web APIs
interface transitionevent event handler property globaleventhandlers.ontransitionstart the original target for this event is the element that had the transition applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionstart. examples this code adds a listener to the transitionstart event: window.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): window.ontransitionrun = () => { console.log('started transitioning'); }; see a live example of this event. specifications specification status comment ...
Window: unhandledrejection event - Web APIs
on}`); }; preventing default handling many environments (such as node.js) report unhandled promise rejections to the console by default. you can prevent that from happening by adding a handler for unhandledrejection events that—in addition to any other tasks you wish to perform—calls preventdefault() to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. this works because unhandledrejection is cancelable. window.addeventlistener('unhandledrejection', function (event) { // ...your code here to handle the unhandled rejection... // prevent the default handling (such as outputting the // error to the console) event.preventdefault(); }); specifications specification status comment html living standardthe def...
Window.window - Web APIs
Web › API › Window › window
inside of its functions would refer to that window object. in the non-namespaced version, "this.window" would refer back to "window", and also be able to readily get the document location. another advantage, is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, they would not be able to do this if they had hard-coded a reference to "window". the default in the class could still be set as the current window object. specifications specification status comment html living standardthe definition of 'window.window' in that specification. living standard no difference from the latest snapshot html 5.1 html 5.1the definition of 'window.window' in that specification. recom...
WindowEventHandlers.onhashchange - Web APIs
the hashchange event the dispatched hashchange event has the following properties: field type description newurl domstring the new url to which the window is navigating. oldurl domstring the previous url from which the window was navigated. ...
WindowEventHandlers.onpopstate - Web APIs
ger a popstate event. the popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in javascript), when navigating between two history entries for the same document. syntax window.onpopstate = funcref; funcref is a handler function. ...
self.createImageBitmap() - Web APIs
age's extraction. the available options are: imageorientation: specifies whether the image should be presented as is or flipped vertically. either none (default) or flipy. premultiplyalpha: specifies whether the bitmap's color channels should be premultiplied by the alpha channel. one of none, premultiply, or default (default). colorspaceconversion: specifies whether the image should be decoded using color space conversion. either none or default (default). the value default indicates that implementation-specific behavior is used. resizewidth: a long integer that indicates the output width. resizeheight: a long integer that indicates the output height. resizequality: specifies the algorithm to be used for resizing the input to match the output dimensions. one of pixelated, low (d...
WindowOrWorkerGlobalScope.indexedDB - Web APIs
the indexeddb read-only property of the windoworworkerglobalscope mixin provides a mechanism for applications to asynchronously access the capabilities of indexed databases. syntax var idbfactory = self.indexeddb; value an idbfactory object. example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open('todolist'); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; } } specifications specification status comment indexed database api draftthe definition of 'indexeddb' in that specification. recommendation defined in a windoworworkerglobalscope partial in the ...
Worker() - Web APIs
Web › API › Worker › Worker
y useful for debugging purposes. exceptions a securityerror is raised if the document is not allowed to start workers, e.g. if the url has an invalid syntax or if the same-origin policy is violated. a networkerror is raised if the mime type of the worker script is incorrect. it should always be text/javascript. a syntaxerror is raised if aurl cannot be parsed. examples the following code snippet shows creation of a worker object using the worker() constructor and subsequent usage of the object: var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see our basic dedicated worker example (run dedicated worker). specifications specificati...
Worker: message event - Web APIs
the message event is fired on a worker object when the worker's parent receives a message from its worker (i.e. when the worker sends a message using dedicatedworkerglobalscope.postmessage()). ...
Worker.onmessage - Web APIs
Web › API › Worker › onmessage
s an eventhandler, that is a function to be called when the message event occurs. these events are of type messageevent and will be called when the worker's parent receives a message (i.e. from the dedicatedworkerglobalscope.postmessage method). note: the message payload is available in the message event's data property. syntax myworker.onmessage = function(e) { ... } example the following code snippet shows creation of a worker object using the worker() constructor. messages are passed to the worker when the value inside the form input first changes. an onmessage handler is also present, to deal with messages that are passed back from the worker. var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('me...
Worker.terminate() - Web APIs
Web › API › Worker › terminate
the terminate() method of the worker interface immediately terminates the worker. this does not offer the worker an opportunity to finish its operations; it is simply stopped at once. syntax myworker.terminate(); parameters none. returns void. example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated. var myworker = new worker('worker.js'); myworker.terminate(); specifications specification status comment html living standardthe definition of 'worker.terminate()' in that specification. living standard ...
WorkerGlobalScope.navigator - Web APIs
will get a workernavigator object written to the console — something like the following: object {online: true, useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) ap…ml, like gecko) chrome/40.0.2214.93 safari/537.36", product: "gecko", platform: "macintel", appversion: "5.0 (macintosh; intel mac os x 10_10_1) applewebki…ml, like gecko) chrome/40.0.2214.93 safari/537.36"…} appcodename: "mozilla" appname: "netscape" appversion: "5.0 (macintosh; intel mac os x 10_10_1) applewebkit/537.36 (khtml, like gecko) chrome/40.0.2214.93 safari/537.36" hardwareconcurrency: 4 online: true platform: "macintel" product: "gecko" useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) applewebkit/537.36 (khtml, like gecko) chrome/40.0.2214.93 safari/537.36" ...
WorkerGlobalScope.onclose - Web APIs
summary the onclose property of the workerglobalscope interface represents an eventhandler to be called when the close event occurs and bubbles through the worker. this non-standard event handler was only implemented by a few browsers and has been removed from all or nearly all of them. syntax self.onclose = function() { ... }; example the following code snippet shows an onclose handler set inside a worker: self.onclose = function() { console.log('your worker instance has been closed'); } specifications this feature is no longer defined in any specifications. ...
WorkerGlobalScope.onerror - Web APIs
the onerror property of the workerglobalscope interface represents an eventhandler to be called when the error event occurs and bubbles through the worker. syntax self.onerror = function() { ... }; example the following code snippet shows an onerror handler set inside a worker: self.onerror = function() { console.log('there is an error inside your worker!'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onerror' in that specification. living standard ...
WorkerGlobalScope.onlanguagechange - Web APIs
the onlanguagechange property of the workerglobalscope interface represents an eventhandler to be called when the languagechange event occurs and bubbles through the worker. syntax self.onlanguagechange = function() { ... }; example the following code snippet shows an onlanguagechange handler set inside a worker: self.onlanguagechange = function() { console.log('your preferred language settings have been changed'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onlanguagechange' in that specification. living standard ...
WorkerGlobalScope.onoffline - Web APIs
the onoffline property of the workerglobalscope interface represents an eventhandler to be called when the offline event occurs and bubbles through the worker. syntax self.onoffline = function() { ... }; example the following code snippet shows an onoffline handler set inside a worker: self.onoffline = function() { console.log('your worker is now offline'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onoffline' in that specification. living standard ...
WorkerGlobalScope.ononline - Web APIs
the ononline property of the workerglobalscope interface represents an eventhandler to be called when the online event occurs and bubbles through the worker. syntax self.ononline = function() { ... }; example the following code snippet shows an ononline handler set inside a worker: self.ononline = function() { console.log('your worker is now online'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.ononline' in that specification. living standard ...
WorkerNavigator - Web APIs
lock object and querying for an existing lock object. workernavigator.permissions read only returns a permissions object that can be used to query and update permission status of apis covered by the permissions api. navigator.storageread only returns a storagemanager interface for managing persistance permissions and estimating available storage. inherited properties navigatorid.appcodename read only always returns 'mozilla', in any browser. this property is kept only for compatibility purposes. navigatorid.appname read only returns the official name of the browser. do not rely on this property to return the correct value. navigatorid.appversion read only returns the version of the browser as a string. do not rely on this property to return the correct value. navigat...
WritableStreamDefaultWriter.ready - Web APIs
am is done writing and thus able to receive data before sending a binary chunk. the second also checks whether the the writablestream is done writing, but this time because the writing must be finished before the writer can be closed. function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter var defaultwriter = writablestream.getwriter(); var encoder = new textencoder(); var encoded = encoder.encode(message, {stream: true}); encoded.foreach(function(chunk) { // make sure the stream and its writer are able to // receive data. defaultwriter.ready .then(function() { defaultwriter.write(chunk) .then(function() { console.log("chunk written to sink.); }) .catch(function(err) { console.l...
XDomainRequest.onprogress - Web APIs
note: while handling this event, you can look at xdomainrequest.responsetext to get the response so far. once loading is complete, the xdomainrequest.onload event handler gets called. syntax xdr.onprogress = funcref; parameters funcref a function to call when progress events occur. ...
init() - Web APIs
warning: this method must not be called from javascript. [noscript] void init( in nsiprincipal principal, in nsiscriptcontext scriptcontext, in nsiglobalobject globalobject, in nsiuri baseuri, [optional] in nsiloadgroup loadgroup ); parameters principal the principal to use for the request; this must not be null. scriptcontext the script context to use for the request; this must not be null. globalobject the object to use as the global for our request. often, this is the outer window, but it may also be a sandbox or backstage pass. this may be null, but if it is, the request cannot create a document. prior to firefox 23, this was always a window. ...
XMLHttpRequest.abort() - Web APIs
syntax xmlhttprequest.abort() parameters none. return value undefined example this example begins loading content from the mdn home page, then due to some condition, aborts the transfer by calling abort(). ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
1; mode=block\r\n each line is terminated by both carriage return and line feed characters (\r\n). these are essentially delimiters separating each of the headers. note: in modern browsers, the header names are returned in all lower case, as per the latest spec. example this example examines the headers in the request's readystatechange event handler, xmlhttprequest.onreadystatechange. the code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values. var request = new xmlhttprequest(); request.open("get", "foo.txt", true); request.send(); request.onreadystatechange = function() { if(this.readystate == this.headers_received) { // get the raw he...
XMLHttpRequest.onreadystatechange - Web APIs
lled whenever the readystate attribute changes. the callback is called from the user interface thread. the xmlhttprequest.onreadystatechange property contains the event handler to be called when the readystatechange event is fired, that is every time the readystate property of the xmlhttprequest changes. warning: this should not be used with synchronous requests and must not be used from native code. syntax xmlhttprequest.onreadystatechange = callback; values callback is the function to be executed when the readystate changes. examples const xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.onreadystatechange = function () { // in local files, status is 0 upon success in mozilla firefox if(xhr.readystat...
XMLHttpRequest.openRequest() - 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. this mozilla-specific method is available only from within privileged code, and is only called from a c++ context in order to initialize an xmlhttprequest. to initialize a request from javascript code, use the standard open() method instead. ...
XMLHttpRequest.send() - Web APIs
r.onload = function () { // request finished. do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes. if (this.readystate === xmlhttprequest.done && this.status === 200) { // request finished. do processing here. } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new int8array()); // xhr.send(document); specifications specification status comment xmlhttprequestthe def...
XMLHttpRequest.status - Web APIs
before the request completes, the value of status is 0. browsers also report a status of 0 in case of xmlhttprequest errors. ...
XMLHttpRequest.statusText - Web APIs
if the request's readystate is in unsent or opened state, the value of statustext will be an empty string. if the server response doesn't explicitly specify a status text, statustext will assume the default value "ok". ...
XMLHttpRequest - Web APIs
ed by the server. xmlhttprequest.send() sends the request. if the request is asynchronous (which is the default), this method returns as soon as the request is sent. xmlhttprequest.setrequestheader() sets the value of an http request header. you must call setrequestheader()after open(), but before send(). non-standard methods xmlhttprequest.init() initializes the object for use from c++ code. warning: this method must not be called from javascript. xmlhttprequest.openrequest() initializes a request. this method is to be used from native code; to initialize a request from javascript code, use open() instead. see the documentation for open(). xmlhttprequest.sendasbinary() a variant of the send() method that sends binary data. events abort fired when a request has been abo...
XMLSerializer - Web APIs
cepts a string and not a node as its second parameter, xmlserializer is used to first convert the node into a string. var inp = document.createelement('input'); var xmls = new xmlserializer(); var inp_xmls = xmls.serializetostring(inp); // first convert dom node into a string // insert the newly created node into the document's body document.body.insertadjacenthtml('afterbegin', inp_xmls); the code creates a new <input> element by calling document.createelement(), then serializes it into xml using serializetostring(). once that's done, insertadjacenthtml() is used to insert the <input> element into the dom. specifications specification status comment dom parsing and serializationthe definition of 'xmlserializer' in that specification. working draft ...
XPathException - Web APIs
constants constant value description invalid_expression_err 51 if the expression has a syntax error or otherwise is not a legal expression according to the rules of the specific xpathevaluator or contains specialized extension functions or variables not supported by this implementation. ...
XPathResult - Web APIs
athresult.invaliditeratorstateread only signifies that the iterator has become invalid. it is true if resulttype is unordered_node_iterator_type or ordered_node_iterator_type and the document has been modified since this result was returned. xpathresult.numbervalueread only a number representing the value of the result if resulttype is number_type. xpathresult.resulttyperead only a number code representing the type of the result, as defined by the type constants. xpathresult.singlenodevalueread only a node representing the value of the single node result, which may be null. xpathresult.snapshotlengthread only the number of nodes in the result snapshot. xpathresult.stringvalueread only a string representing the value of the result if resulttype is string_type. methods xpat...
XRInputSourceArray - Web APIs
erates over each item in the list, in order from first to last. keys() a list of the keys corresponding to the entries in the input source list. values() returns an iterator you can use to go through all the values in the list. each item is a single xrinputsource object. in addition to these methods, you may use array notation to access items in the list by index for example, the snippet of code below calls a function handleinput(), passing into it the first item in the input source list, if the list isn't empty. let sources = xrsession.inputsources; if (sources.length > 0) { handleinput(sources[0]); } examples specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification. working draft in...
XRInputSourceEvent() - Web APIs
put source has fully completed a primary squeeze action. squeezeend sent to an xrsession when an ongoing primary squeeze action ends or when an input source with an ongoing primary squeeze action is disconnected. squeezestart sent to an xrsession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. examples the code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene. xrsession.addeventlistener("select", event => { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (targetraypose) { let hit = myhittest(targetraypose.transform); if (hit) { /* handle the hit *...
XRInputSourceEvent.frame - Web APIs
d to provide access to the getpose() method, which you can use to get the relative positions of the objects in the scene at the time the event occurred. however, since the event frame isn't an animation frame, there is no viewer pose available to represent the viewer's current point of view; the results of calling getviewerpose() will be an xrviewerpose with an empty views list. examples this code shows a handler for the selectstart event which gets the target ray's pose from the frame, mapping the pose representing the ray (event.inputsource.targetrayspace) to the overall reference space myrefspace. then, if the result isn't null, the target ray pose's transform is passed into a function called mycheckandhandlehit() to see if the ray was pointing at anything when the select was triggered...
XRInputSourceEvent - Web APIs
put source has fully completed a primary squeeze action. squeezeend sent to an xrsession when an ongoing primary squeeze action ends or when an input source with an ongoing primary squeeze action is disconnected. squeezestart sent to an xrsession when an input source begins its primary squeeze action, indicating that the user has begun to grab, squeeze, or grip the controller. examples the code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene. xrsession.addeventlistener("select", event => { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (targetraypose) { let hit = myhittest(targetraypose.transform); if (hit) { /* handle the hit *...
XRInputSourcesChangeEvent() - Web APIs
ntinitdict an object conforming to the xrinputsourceschangeeventinit dictionary, prodividing the initial values for the event. return value a newly-created xrinputsourceschangeevent object configured based upon the input parameters provided. event types inputsourceschange delivered to the xrsession when the set of input devices available to it changes. example the following snippet of code creates a new xrinputsourceschangeevent object indicating that a single new input source, described by an xrinputsource object named newinputsource, has been added to the system. let iscevent = new xrinputsourceschangeevent("inputsourceschange", { session: xrsession, added: [newinputsource], removed: [] }); specifications specification status comment ...
XRRigidTransform.inverse - Web APIs
let view of pose.view) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); /* ... */ mat4.multiply(modelviewmatrix, view.transform.inverse.matrix, objectmatrix); gl.uniformmatrix4fv(programinfo.uniformlocations.modelviewmatrix, false, modelviewmatrix); /* ... */ } this outline of a renderer's core code shows how the pose's view gets represented by taking its transform's inverse's matrix as the model view matrix used to transform objects based on the viewer's position and orientation. the inverse's matrix is multiplied by the object's matrix to get the model view matrix, which is then passed into the shader program by setting a uniform to contain that information. specifications speci...
XRRigidTransform - Web APIs
se read only returns a xrrigidtransform which is the inverse of this transform. that is, if applied to an object that had been previously transformed by the original transform, it will undo the transform and return the original object. usage notes when an xrrigidtransform is interpreted, the orientation is always applied to the affected object before the position is applied. example this code snippet creates an xrrigidtransform to specify the offset and orientation in relation to the current reference space to use when creating a new reference space. it then requests the first animation frame callback by calling the session's requestanimationframe() method. xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrrefere...
XRSession.cancelAnimationFrame() - Web APIs
ame which was previously requested by calling requestanimationframe. syntax xrsession.cancelanimationframe(handle); parameters handle the unique value returned by the call to requestanimationframe() that previously scheduled the animation callback. return value none. usage notes this function has no effect if the specified handle cannot be found. example in the example below we see code which starts up a webxr session if immersive vr mode is supported. once started, the session schedules its first frame to be rendered by calling requestanimationframe(). the pausexr() function shown at the bottom can be called to suspend the webvr session, in essence, by canceling any pending animation frame callback. since each frame callback schedules the next one, removing the callback termin...
XRSession.onsqueezestart - Web APIs
ze action on a webxr input device. these actions represent the user squeezing or tightly gripping an object or controller. to learn more about how to use and handle webxr controller inputs, see inputs and input sources. syntax xrsession.onsqueezestart = squeezestarthandlerfunction; value a function to be invoked whenever the xrsession receives a squeezestart event. examples this snippet of code adds a simple handler for the squeezestart event, which responds only to events on the user's dominant hand by getting the target ray, then calling a function findobjectusingray() to identify the object that the user is pointing at. this object is then stored in a heldobject variable in the user object we're using to represent user information. xrsession.onsqueezestart = event => { if (event.i...
XRSession.requestAnimationFrame() - Web APIs
} } // the window animation loop can be started immediately upon the page loading. window.requestanimationframe(onwindowanimationframe) function onxranimationframe(time, xrframe) { xrsession.requestanimationframe(onxranimationframe) renderframe(time, xrframe) } function renderframe(time, xrframe) { // shared rendering logic. } // assumed to be called by a user gesture event elsewhere in code. function startxrsession() { navigator.xr.requestsession('immersive-vr').then((session) => { xrsession = session xrsession.addeventlistener('end', onxrsessionended) // do necessary session setup here. // begin the session’s animation loop. xrsession.requestanimationframe(onxranimationframe) }) } function onxrsessionended() { xrsession = null } specifications ...
XRSession: squeeze event - Web APIs
rt, squeeze, and squeezeend events work, and how you should react to them, see primary squeeze actions in inputs and input sources. examples the following example uses addeventlistener() to set up a handler for the squeeze event. the handler fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function called myhandlesqueezewithray(). this code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity. if you need to track a squeeze action that isn't instantaneous, listen for the squeezestart and squeezeend events to sense when the squeeze action begins and ends. xrsession.addeventlistener("squeeze", event => { if (event.inputsource.targetraymode == "tracked-pointer") { let targetraypose = ev...
XRSystem: devicechange event - Web APIs
devices are currently available. if (navigator.xr) { navigator.xr.addeventlistener("devicechange", event => { navigator.xr.issessionsupported("immersive-vr") .then(immersiveok) => { if (immersiveok) { enablexrbutton.disabled = false; } else { enablexrbutton.disabled = true; } }); }); } when devicechange is received, the handler set up in this code calls the xr method issessionsupported() to find out if there's a device available that can handle immersive vr presentations. if there is, the button to enter xr mode is enabled; otherwise it's disabled. you can also use the ondevicechange event handler property to set a single handler for devicechange events: if (navigator.xr) { navigator.xr.ondevicechange = event => { /* ... etc ... */...
XRView.eye - Web APIs
Web › API › XRView › eye
escribes a monoscopic view, or the view otherwise doesn't represent a particular eye's point-of-view. usage notes the primary purpose of this property is to allow the correct area of any pre-rendered stereo content to be presented to the correct eye. for dynamically-rendered 3d content, you can usually ignore this and simply render each of the viewer's views, one after another. examples this code, from the viewer pose's renderer, iterates over the pose's views and renders them. however, we have flags which, if true, indicate that a particular eye has been injured during gameplay. when rendering that eye, if the flag is true, that view is skipped instead of being rendered. gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); gl.clearcolor(0,0...
XRView.transform - Web APIs
Web › API › XRView › transform
. examples for each view making up the presented scene, the view's transform represents the position and orientation of the viewer or camera relative to the reference space's origin. you can then use the inverse of this matrix to transform the objects in your scene to adjust their placement and orientation to simulate the viewer's movement through space. in this example, we see an outline of a code fragment used while rendering an xrframe, which makes use of the view transform to place objects in the world during rendering. const modelviewmatrix = mat4.create(); const normalmatrix = mat4.create(); for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); for (let obj of world.objects) { mat4.mu...
XRView - Web APIs
Web › API › XRView
{x: inverseorientation[0], y: inverseorientation[1], z: inverseorientation[2], w: inverseorientation[3]}); mat4.copy(mousematrix, newtransform.matrix); // create a new reference space that transforms the object to the new // position and orientation, returning the new reference space. return refspace.getoffsetreferencespace(newtransform); } this code is broken into four sections. in the first, the quaternion inverseorientation is computed. this represents the rotation of the object given the values of mousepitch (rotation around the object's reference's space's x axis) and mouseyaw (rotation around the object's y axis). the second section computes the "up" vector for the object. this vector indicates the direction which is "up" in the scene ...
XRWebGLLayer.ignoreDepthValues - Web APIs
t possible to more accurately represent the scene in the 3d space. examples if the web application which is using wexr is rendering its content without using a depth buffer—or if the depth buffer's contents are invalid—you should disable the use of the depth buffer for webxr rendering by setting ignoredepthvalues to true when creating the xrwebgllayer. this is demonstrated in the snippet of code below: const gllayeroptions = { ignoredepthvalues: true }; let gllayer = new xrwebgllayer(xrsession, gl, gllayeroptions); specifications specification status comment webxr device apithe definition of 'xrwebgllayer.ignoredepthvalues' in that specification. working draft initial definition. ...
XSL Transformations in Mozilla FAQ - Web APIs
ing parsing with xslt is brittle and we rather not support d-o-e than either crash or be even slower. what about document.write? just like for xhtml, document.write is not supported during xslt transformations. sadly, current builds don't error, but just give unexpected results, like crashes (bug 202765). in most cases, there is no need to actually use it, though. if you need platform dependent code or stylesheets, just do <xsl:if test="system-property('xsl:vendor')='transformiix'"> <!-- mozilla specific markup --> </xsl:if> <xsl:if test="system-property('xsl:vendor')='microsoft'"> <!-- ie specific markup --> </xsl:if> check system-properties.xml for the properties of your favorite system. msxml has an additional property. <xsl:if xmlns:msxsl...
msGetRegionContent - Web APIs
ary method is specific to internet explorer browser. syntax var retval = element.msgetregioncontent(); parameters retval [out, reval] type: msrangecollection the name of the property to enable. return value type: boolean returned ranges are sorted by document position and do not overlap. if an element is not a region, this method throws a domexception with the invalidaccesserror error code. this is only available to regions that are document elements and not to regions that are pseudo-elements. see also microsoft api extensions ...
msPutPropertyEnabled - Web APIs
or disabled. this proprietary method is specific to internet explorer and microsoft edge. syntax var retval = style.msputpropertyenabled(propertyname, true); parameters name[in]: name of the property. (string) boolean[in]: true = enable the property. false = disable the property. return value type = hresult: if this method succeeds, it returns s_ok. otherwise, it returns an hresult error code. see also css style declaration microsoft api extensions ...
msWriteProfilerMark - Web APIs
he mswriteprofilermark method writes a profiling event. this proprietary method is specific to internet explorer and microsoft edge. syntax window.mswriteprofilermark("start-render"); parameters bstrprofilermarkname[in] an event name. type = string. this parameter may be null. return value type: hresult. if this method succeeds, it returns s_ok. otherwise, it returns an hresult error code. notes mswriteprofilermark enables you to inject dom based performance markers in addition to existing javascript api to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for more accurately debugging real users perf issues. internet explorer 10. this method is also available in th...
ARIA Technique Template - Accessibility
description possible effects on user agents and assistive technology note: opinions may differ on how assistive technology should handle this technique. ...
Using the alertdialog role - Accessibility
d focus is moved to a control inside the dialog, screen readers should announce the dialog's accessible role, name and optionally description before announcing the focused element. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: a basic alert dialog the code snippet below shows how to mark up an alert dialog that only provides a message and an ok button. <div role="alertdialog" aria-labelledby="dialog1title" aria-describedby="dialog1desc"> <div role="document" tabindex="0"> <h2 id="dialog1title">your login session is about to expire</h2> <p id="dialog1desc">to extend your session, click the ok button</p> <button>ok</button> </div> </...
Using the aria-activedescendant attribute - Accessibility
about the active child which has focus. this active child using the aria-activedescendant property must always be visible on screen and must be a descendant of the container in the document object model. ...
Using the log role - Accessibility
user is idle, unless aria-live=”assertive” has been set and in which case the user may be interrupted. screen magnifiers may visually indicate that a log update has occurred. note: opinons may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: adding the role in the html code the snippet below shows how the log role is added directly into the html source code. <div id="liveregion" class="region" role="log"></div> example 2: snippet from an example application this snippet creates the chat log in an ajax chat application. <div id="chatarea" role="log"> <ul id="chatregion" aria-live="polite" aria-atomic="false"> <li>please choose a user name to begin using a...
Using the status role - Accessibility
t and in which case the user may be interrupted. screen magnifiers may enlarge the status. note: opinons may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: adding the status role in html the snippet below shows how the status role is added directly into the html source code. <p role="status">your changes were automatically saved.</p> working examples: notes aria attributes used status related aria techniques alert role live region roles live region attributes compatibility the paciello group published some data on compatibility via their 2014 blog post: screen reader support for aria live regions tbd: add updated support informatio...
Using the toolbar role - Accessibility
description this technique demonstrates how to use the toolbar role and describes the effect it has on browsers and assistive technology. ...
ARIA Test Cases - Accessibility
table legend - no info/test yet n/a not applicable (not supported technically) pass expected behaviour met fail expected behaviour notmet 1. 2. reference to link example note regarding dojo/dijit test files the main purpose of dojo's dijit test files are for dojo developers to exercise and debug the code. as such, they are used to test a variety of features, such as styling, behavior, mouse, and keyboard interactions, to name few. these test files are not specifically for testing aria. still, dojo's widgets implement aria, and the noted test files could be used as an "aria test file". new tests for internet explorer 8 rc1 on this msdn page the aria state/role mapping in ie8 to msaa roles can be...
ARIA annotations - Accessibility
ollectively known as aria annotations, which allow the creation of accessible annotations inside web documents. typical use cases include edit suggestions (i.e. an addition and/or deletion in an editable document), and comments (e.g. an editorial comment related to a part of a document under review). below we'll introduce the new features associated with aria annotations, and have a look at some code examples that show them in action. note: you can find all the examples discussed in this article in a demo file at aria-annotations. aria annotations features the aria attributes providing these new abilities are as follows: aria-description="" — provides a detailed description of an html element, as opposed to the brief label provided by aria-label. role="insertion" and role="deletion...
ARIA: feed role - Accessibility
primary content, assistive technologies can provide functions that enable users to jump from article to article and efficiently discern which articles they want to read. the feed pattern enables reliable assistive technology reading mode interaction by establishing the following interoperability agreement between the web page and assistive technologies: in the context of a feed, the web page code is responsible for: appropriate visual scrolling of the content based on which article contains dom focus. loading or removing feed articles based on which article contains dom focus. in the context of a feed, assistive technologies with a reading mode are responsible for: indicating which article contains the reading cursor by ensuring the article element or one of its desce...
ARIA: gridcell role - Accessibility
e table, grid, or treegrid has the ability to have rows and/or columns dynamically added, hidden, or removed. use aria-colindex to describe a gridcell's order in the list of columns, and aria-rowindex to describe a gridcell's order in the list of rows. use aria-colcount and aria-rowcount on the parent element with role="grid" applied to it to set the total number of columns or rows. this sample code demonstrates a table-style grouping of information where the third and fourth columns have been removed. aria-colindex is being used to describe the rows' position and allows a person using assistive technology to infer that certain rows have been removed: <div role="grid" aria-colcount="6"> <div role="rowgroup"> <div role="row"> <div role="columnheader" aria-colindex="1">first name<...
ARIA: Main role - Accessibility
r and footer --> </body> accessibility concerns use only one main role per document the main landmark role should only be used once per document. if a document contains two main roles, say updating page content when triggered by javascript, the inactive main role's presence should be removed from assistive technology via techniques such as toggling the hidden attribute. <main> <h1>active <code>main</code> element</h1> <!-- content --> </main <main hidden> <h1>hidden <code>main</code> element</h1> <!-- content --> </main> best practices prefer html using the <main> element will automatically communicate a section has a role of main. if at all possible, prefer using it instead. skip navigation skip navigation, also known as "skipnav", is a technique that allows an assistive ...
ARIA: switch role - Accessibility
y of its aria-checked attribute being set to "true". the switch has two child elements containing the "off" and "on" labels and is followed by a <label> identifying the switch. <button role="switch" aria-checked="true" id="speakerpower" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerpower" class="switch">speaker power</label> javascript this javascript code defines and applies a function to handle click events on switch widgets. the function changes the aria-checked attribute from true to false, or vice versa. document.queryselectorall(".switch").foreach(function(theswitch) { theswitch.addeventlistener("click", handleclickevent, false); }); function handleclickevent(evt) { let el = evt.target; if (el.getattribute("aria-checked") == "true") ...
ARIA: dialog role - Accessibility
ready has a visible title bar, the text inside that bar can be used to label the dialog itself. the best way to achieve this is by using the aria-labelledby attribute to the role="dialog" element. additionally, if the dialog contains additional descriptive text besides the dialog title, this text can be associated with the dialog using the aria-describedby attribute. ...
ARIA: heading role - Accessibility
y you can go higher, and some screen readers may support it, the results can be unpredictable with other browser/screen reader combinations. best practices the best way to use this role is to not use it at all, and instead use the native heading tags <h1> through <h6> as shown in the example above. the heading role and aria-level attribute should only be used to retrofit accessibility on legacy code that you cannot make major changes to. added benefits none. specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'heading' in that specification. recommendation precedence order the heading role overrides the native semantic meaning of the element it is being used for. the aria-level attribute, in addition, d...
ARIA: listbox role - Accessibility
ire already built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so. the <select> element with descendant <option> elements handles all the needed interactions natively. examples example 1: a single select listbox that uses aria-activedescendant the snippet below shows how the listbox role is added directly into the html source code. <p id="listbox1label" role="label">select a color:</p> <div role="listbox" tabindex="0" id="listbox1" aria-labelledby="listbox1label" onclick="return listitemclick(event);" onkeydown="return listitemkeyevent(event);" onkeypress="return listitemkeyevent(event);" aria-activedescendant="listbox1-1"> <div role="option" id="listbox1-1" class="selected" aria-selected="true">green</div> ...
Alerts - Accessibility
. if the criteria was not met, the user will be notified via an alert. instead of using the javascript ‘alert’ function, we’ll use a simple wai-aria widget for notification. this notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the “onblur” handler in javascript's default ‘alert’ function). ...
overview - Accessibility
using wai-aria roles and states with the yui menu control slider from the paciello group blog: aria slider, part one, part two, part threet (example) creating an accessible, internationalized dojo rating widget tabs enhancing tabview accessibility with wai-aria roles and states, from the yui blog enhancing the jquery ui tabs accordingly to wcag 2.0 and aria tab panel example here on codetalks lightbox wcag 2.0 and aria-conformant lightbox application http://majx-js.digissime.net/js/popin/ form validation wcag 2.0 and aria-conformant live form validation tables german tutorial on creating an accessible form simple grid example at codetalks date picker grid at codetalks wcag 2.0 and aria-conformant sortable tables ...
ARIA - Accessibility
ctually a javascript-powered progress bar widget. the aria-valuemin and aria-valuemax attributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it and therefore must be kept updated with javascript. along with placing them directly in the markup, aria attributes can be added to the element and updated dynamically using javascript code like this: // find the progress bar <div> in the dom. var progressbar = document.getelementbyid("percent-loaded"); // set its aria roles and states, // so that assistive technologies know what kind of widget it is. progressbar.setattribute("role", "progressbar"); progressbar.setattribute("aria-valuemin", 0); progressbar.setattribute("aria-valuemax", 100); // create a function that can be calle...
Accessibility Information for Web Authors - Accessibility
extension add-on to firefox 2.x and firefox 3.x. it not only checks and reports possible markup errors and warnings (based on w3c tidy and/or based on true sgml validation) but it can also report accessibility errors and warnings according to selectable accessibility guidelines (section 508, wcag priorities 1, 2 or 3). its accessibility report is viewable in the view source window (view > source code ctrl+u or right-click on the status bar). two panes are added at the bottom of the view source code window: the left pane contains the errors and warnings (with their correspondent line number) and the right pane identifies the checkpoint along with an example and a clickable link to the reference/guideline. just wonderful! the html advanced validator may also be downloaded from firefox add-on...
Web accessibility for seizures and physical reactions - Accessibility
n the browser or in the os. see the mdn document, "accessibility: what users can to to browse more safely" to see more details of how a user accesses the controls. prefers-reduced-motion support for prefers-reduced-motion in modern browsers is growing. @media screen and (prefers-reduced-motion: reduce) { } @media screen and (prefers-reduced-motion) { } to see a great example of how to use the code prefers-reduced-motion, visit the mdn document, prefers-reduced-motion, or see the example below from the section on new in chrome 74. button { animation: vibrate 0.3s linear infinite both; } @media (prefers-reduced-motion: reduce) { button { animation: none; } } prefers-color-scheme this can be useful if the ambient light api is not available. support is emerging. @media (prefers...
Color contrast - Accessibility
and have trouble differentiating between similar colors. this is because they don't see bright and dark areas as readily as those without such conditions, and therefore have trouble seeing edges, borders, and other details. it is good to have a cool design on your website, but the design is worthless if your users can't read your content. examples let's have a look at some simple html and css code: <div class="good">good contrast</div> <div class="bad">bad contrast</div> div { /* general div styles here */ } .good { background-color: #fae6fa; } .bad { background-color: #400064; } both pieces of text have their default black color. the "good" <div> has a light purple background, which makes the text easy to read: example1 <div class="good"> good contrast </div> ...
Understandable - Accessibility
peration of user interface must be understandable. guideline 3.1 — readable: make text content readable and understandable this guideline focuses on making text content as understandable as possible. success criteria how to conform to the criteria practical resource 3.1.1 language of page (a) the default human language of each web page should be detectable via code. this is essential for purposes like making sure the reader has arrived at a page written in a language suitable for them. the simplest way to achieve this is to set the lang attribute on the page's <html> element, giving it a value equal to the language code that best represents the language the page is written in. see setting the primary language of the document. 3.1.2 language of p...
-moz-image-rect - CSS: Cascading Style Sheets
yle="left:133px;top:0px;">top right</div> <div id="box3" style="left:0px;top:136px;">bottom left</div> <div id="box4" style="left:133px;top:136px;">bottom right</div> </div> this places the four segments of our image in a two-by-two box grid. these four segments are all contained within a larger <div> block whose primary purpose is to receive click events and dispatch them to our javascript code. the javascript code this code handles the click event when the container receives a mouse click. function rotate() { var prevstyle = window.getcomputedstyle(document.getelementbyid("box4"), null).getpropertyvalue("background-image"); // now that we've saved the last one, start rotating for (var i=1; i<=4; i++) { var curid = "box" + i; // shift the background images var c...
-webkit-line-clamp - CSS: Cascading Style Sheets
ecifies that the content wonʼt be clamped. <integer> this value specifies the number of lines after which the content will be clamped. it must be greater than 0. formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax none | <integer> examples truncating a paragraph html <p> in this example the <code>-webkit-line-clamp</code> property is set to <code>3</code>, which means the text is clamped after three lines. an ellipsis will be shown at the point where the text is clamped. </p> css p { width: 300px; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; } result specifications specification status comment c...
:-moz-window-inactive - CSS: Cascading Style Sheets
er used. syntax :-moz-window-inactive examples this example alters the appearance of a box's background depending on whether its window is active or not. html <div id="mybox"> <p>this is a box!</p> </div> css #mybox { background: linear-gradient(to bottom, yellow, cyan); width: 200px; height: 200px; } #mybox:-moz-window-inactive { background: cyan; } result the result of this code is shown below. you can view this as a separate page as well. specifications not part of any standard. ...
::-webkit-progress-bar - CSS: Cascading Style Sheets
. note: for ::-webkit-progress-value to take effect, appearance needs to be set to none on the <progress> element. syntax ::-webkit-progress-bar examples css content progress { -webkit-appearance: none; } ::-webkit-progress-bar { background-color: orange; } html content <progress value="10" max="50"> result result screenshot if you're not using a webkit or blink browser, the code above results in a progress bar that looks like this: specifications not part of any standard. ...
::-webkit-progress-inner-element - CSS: Cascading Style Sheets
e examples work only on blink and webkit. adding a black border around the progress bar in this example, a 2px black border is added around the progress bar. html <progress value="10" max="50"> css progress { -webkit-appearance: none; } ::-webkit-progress-inner-element { border: 2px solid black; } result result screenshot if you're not using a blink or webkit browsear, the above code resuls in a progress bar looking like this: specifications not part of any standard. ...
::backdrop - CSS: Cascading Style Sheets
ed to be a grey-blue color rather than the black it defaults to in most browsers. video::backdrop { background-color: #448; } the resulting screen looks like this: note the dark grey-blue letterbox effect above and below where the backdrop is visible. normally that area is black, but its appearance has been altered by the css above. you can see this example in action or view or remix the code on glitch. specifications specification status comment fullscreen apithe definition of '::backdrop' in that specification. living standard initial definition. ...
::first-letter (:first-letter) - CSS: Cascading Style Sheets
letter of the first line of a block-level element, but only when not preceded by other content (such as images or inline tables). /* selects the first letter of a <p> */ p::first-letter { font-size: 130%; } the first letter of an element is not always trivial to identify: punctuation that precedes or immediately follows the first letter is included in the match. punctuation includes any unicode character defined in the open (ps), close (pe), initial quote (pi), final quote (pf), and other punctuation (po) classes. some languages have digraphs that are always capitalized together, like the ij in dutch. in these cases, both letters of the digraph should be matched by the ::first-letter pseudo-element. (this is poorly supported by browsers; see the browser compatibility table below.) a c...
::marker - CSS: Cascading Style Sheets
Web › CSS › ::marker
list item, which typically contains a bullet or number. it works on any element or pseudo-element set to display: list-item, such as the <li> and <summary> elements. ::marker { color: blue; font-size: 1.2em; } allowable properties only certain css properties can be used in a rule with ::marker as a selector: all font properties the white-space property color text-combine-upright, unicode-bidi and direction properties the content property all animation and transition properties the specification states that additional css properties may be supported in future. syntax ::marker examples html <ul> <li>peaches</li> <li>apples</li> <li>plums</li> </ul> css ul li::marker { color: red; font-size: 1.5em; } result specifications specification status ...
:fullscreen - CSS: Cascading Style Sheets
switch back and forth between full-screen and traditional presentations. examples in this example, the color of a button is changed depending on whether or not the document is in full-screen mode. this is done without needing to specifically apply style changes using javascript. html the page's html looks like this: <h1>mdn web docs demo: :fullscreen pseudo-class</h1> <p>this demo uses the <code>:fullscreen</code> pseudo-class to automatically change the style of a button used to toggle full-screen mode on and off, entirely using css.</p> <button id="fs-toggle">toggle fullscreen</button> the <button> with the id "fs-toggle" will change between pale red and pale green depending on whether or not the document is in full-screen mode. css the magic happens in the css. there are two r...
:placeholder-shown - CSS: Cascading Style Sheets
an undesirable way. you can use the text-overflow property to alter the way overflowing text is displayed. html <input id="input1" placeholder="name, rank, and serial number"> <br><br> <input id="input2" placeholder="name, rank, and serial number"> css #input2:placeholder-shown { text-overflow: ellipsis; } result customized input field the following example highlights the branch and id code fields with a custom style. html <form id="test"> <p> <label for="name">enter student name:</label> <input id="name" placeholder="student name"/> </p> <p> <label for="branch">enter student branch:</label> <input id="branch" placeholder="student branch"/> </p> <p> <label for="sid">enter student id:</label> <input type="number" pattern="[0-9]{8}" title="8 digit i...
:read-only - CSS: Cascading Style Sheets
e :read-write pseudo-class on the other hand is used to provide some nicer styling to the editable <textarea>. input:-moz-read-only, textarea:-moz-read-only, input:read-only, textarea:read-only { border: 0; box-shadow: none; background-color: white; } textarea:-moz-read-write, textarea:read-write { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } you can find the full source code at readonly-confirmation.html; this renders like so: styling read-only non-form controls this selector doesn't just select <input>/<textarea> elements — it will select any element that cannot be edited by the user. <p contenteditable>this paragraph is editable; it is read-write.</p> <p>this paragraph is not editable; it is read-only.</p> p { font-size: 150%; padding: 5px; border-ra...
:read-write - CSS: Cascading Style Sheets
e :read-write pseudo-class on the other hand is used to provide some nicer styling to the editable <textarea>. input:-moz-read-only, textarea:-moz-read-only, input:read-only, textarea:read-only { border: 0; box-shadow: none; background-color: white; } textarea:-moz-read-write, textarea:read-write { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } you can find the full source code at readonly-confirmation.html; this renders like so: styling read-write non-form controls this selector doesn't just select <input>/<textarea> elements — it will select any element that can be edited by the user, such as a <p> element with contenteditable set on it. <p contenteditable>this paragraph is editable; it is read-write.</p> <p>this paragraph is not editable; it is read-only.</p>...
:state() - CSS: Cascading Style Sheets
Web › CSS › :state
the :state css pseudo-class represents any custom element with the specified custom state in elementinternals.states. custom-element:state(foo) { /* styles to apply when `custom-element` is in the `foo` state */ } syntax syntax not found in db! examples fill in a simple example that nicely shows a typical usage of the selector, then perhaps some more complex examples. my code block and/or include a list of links to useful code samples that live elsewhere: x y z specifications specification status comment unknownthe definition of 'the :state() selector' in that specification. unknown initial definition. ...
font-variation-settings - CSS: Cascading Style Sheets
ues normal text is laid out using default settings. <string> <number> when rendering text, the list of opentype axis names is passed to the text layout engine to enable or disable font features. each setting is always a <string> of 4 ascii characters, followed by a <number> indicating the axis value. if the <string> has more or fewer characters or contains characters outside the u+20 - u+7e codepoint range, the whole property is invalid. the <number> can be fractional or negative. formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax normal | [ <string> <number> ]# examples setting font weight and stretch in a @font-face rule @font-face { font-family: 'opentypefont'; src: url('open_type_font.woff2') format('woff2'); font-weig...
light-level - CSS: Cascading Style Sheets
for example: night time, or a dimly illuminated indoor environment. normal the device is used in a environment with a light level in the ideal range for the screen, and which does not necessitate any particular adjustment. washed the device is used in an exceptionally bright environment, causing the screen to be washed out and difficult to read. for example: bright daylight. examples this code will likely not work on any devices (device compatibility is low). @media (light-level: normal) { p { background: url("texture.jpg"); color: #333; } } @media (light-level: dim) { p { background: #222; color: #ccc; } } @media (light-level: washed) { p { background: white; color: black; font-size: 2em; } } specifications specification status...
prefers-reduced-data - CSS: Cascading Style Sheets
igin> <link rel="stylesheet" href="style.css"> </head> css @media (prefers-reduced-data: no-preference) { @font-face { font-family: montserrat; font-style: normal; font-weight: 400; font-display: swap; /* latin */ src: local('montserrat regular'), local('montserrat-regular'), url('fonts/montserrat-regular.woff2') format('woff2'); unicode-range: u+0000-00ff, u+0131, u+0152-0153, u+02bb-02bc, u+02c6, u+02da, u+02dc, u+2000-206f, u+2074, u+20ac, u+2122, u+2191, u+2193, u+2212, u+2215, u+feff, u+fffd; } } body { font-family: montserrat, -apple-system, blinkmacsystemfont, "segoe ui", roboto, helvetica, arial, "microsoft yahei", sans-serif, "apple color emoji", "segoe ui emoji", "segoe ui symbol"; } result specifications ...
@supports - CSS: Cascading Style Sheets
Web › CSS › @supports
@supports (display: grid) { div { display: grid; } } @supports not (display: grid) { div { float: right; } } in javascript, @supports can be accessed via the css object model interface csssupportsrule. syntax the @supports at-rule associates a block of statements with a supports condition. ...
Attribute selectors - CSS: Cascading Style Sheets
te name of attr whose value is exactly value. [attr~=value] represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value. [attr|=value] represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, - (u+002d). it is often used for language subcode matches. [attr^=value] represents elements with an attribute name of attr whose value is prefixed (preceded) by value. [attr$=value] represents elements with an attribute name of attr whose value is suffixed (followed) by value. [attr*=value] represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string. [attr operator value i] ...
Using multiple backgrounds - CSS: Cascading Style Sheets
each subsequent sub-property (background-repeat and background-position) applies to the corresponding backgrounds. so the first listed value fo...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
this guide, we will take a thorough look at how the alignment and justification properties work in flexbox. to center our box we use the align-items property to align our item on the cross axis, which in this case is the block axis running vertically. we use justify-content to align the item on the main axis, which in this case the inline axis running horizontally. you can take a look at the code of this example below. change the size of the container or nested element and the nested element always remains centered. properties that control alignment the properties we will look at in this guide are as follows. justify-content — controls alignment of all items on the main axis. align-items — controls alignment of all items on the cross axis. align-self — controls alignment of...
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
rst look our three properties control the following aspects of a flex item's flexibility: flex-grow: how much of the positive free space does this item get? flex-shrink: how much negative free space can be removed from this item? flex-basis: what is the size of the item before growing and shrinking happens? the properties are usually expressed as the shorthand flex property. the following code would set the flex-grow property to 2, flex-shrink to 1 and flex-basis to auto. .item { flex: 2 1 auto; } if you have read the article basic concepts of flexbox, then you will have already had an introduction to the properties. here we will explore them in depth in order that you can fully understand what the browser is doing when you use them. important concepts when working on the main axi...
Ordering Flex Items - CSS: Cascading Style Sheets
an integer value greater than 0 will be displayed after any items that have not been given an explicit order value. you can also use negative values with order, which can be quite useful. if you want to make one item display first, and leave the order of all other items unchanged, you can give that item an order of -1. as this is lower than 0 the item will always be displayed first. in the live code example below i have items laid out using flexbox. by changing which item has the class active assigned to it in the html, you can change which item displays first and therefore becomes full width at the top of the layout, with the other items displaying below it. the items are displayed in what is described in the specification as order-modified document order. the value of the order property...
Introduction to formatting contexts - CSS: Cascading Style Sheets
g the browser how you wish to deal with overflowing content. there are some occasions in which you will find you get unwanted scrollbars or clipped shadows when you use this property purely to create a bfc. in addition, it is potentially not very readable for a future developer, as it may not be obvious why you used overflow for this purpose. if you do this, it would be a good idea to comment the code to explain. explicitly creating a bfc using display: flow-root using display: flow-root (or display: flow-root list-item) on the containing block will create a new bfc without any other potentially problematic side-effects. with display: flow-root on the <div>, everything inside that container participates in the block formatting context of that container, and floats will not poke out of the...
CSS Fonts - CSS: Cascading Style Sheets
Web › CSS › CSS Fonts
opentype font features guide font features or variants refer to different glyph...
Basic Concepts of grid layout - CSS: Cascading Style Sheets
...
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
e other demos try changing the direction property to rtl to cause the boxes to display in a right-to-left direction, or changing the writing-mode from horizontal-tb to vertical-rl. new border shorthands there are two-value shorthands to set the width, style and, color of the block or inline dimension, and two-value shorthands to set all three values in the block or inline dimension. the below code, in a horizontal writing mode, would give you a 2px green solid border on the top and bottom of the box, and a 4px dotted purple border on the left and right. .box { border-block: 2px solid green; border-inline-width: 4px; border-inline-style: dotted; border-inline-color: rebeccapurple; } note: these two value shorthands shipped in firefox 66, check browser support before using as othe...
Using z-index - CSS: Cascading Style Sheets
endered on the default rendering layer 0 (zero). if several elements share the same z-index value (i.e., they are placed on the same layer), stacking rules explained in the section stacking without the z-index property apply. in the following example, the layers' stacking order is rearranged using z-index. the z-index of element #5 has no effect since it is not a positioned element. ...
Stacking with floated blocks - CSS: Cascading Style Sheets
of appearance in the html note: if an opacity value is applied to the non-positioned block (div #4), then something strange happens: the background and border of that block pops up above the floating blocks and the positioned blocks. this is due to a peculiar part of the specification: applying a opacity value creates a new stacking context (see what no one told you about z-index). ...
Stacking context example 2 - CSS: Cascading Style Sheets
is is the stacking context hierarchy: root stacking context div #2 (z-index 2) div #3 (z-index 1) div #4 (z-index 10) note: it is worth remembering that in general the html hierarchy is different from the stacking context hierarchy. in the stacking context hierarchy, elements that do not create a stacking context are collapsed on their parent. ...
Stacking without the z-index property - CSS: Cascading Style Sheets
of appearance in the html keep in mind, when the order property alters rendering from the "order of appearance in the html" within flex containers, it similarly affects the order for stacking context. in the example below, elements #1 through #4 are positioned elements. element #5 is static, and so is drawn below the other four elements, even though it comes later in the html markup. ...
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
this article, we consider questions that might arise related to compatibility across browsers and versions of browsers when adding support for scroll-snap to your web site or app. what should i do if i used the old firefox implementation? if you have only used the old firefox implementation of the specification, with the properties that are detailed in scroll snap points, you should update your code to use the new specification. this will ensure your scroll snapping works in all browsers which implement the specification, including firefox. if you do not do this your scroll snapping will no longer work in firefox 68 and up. the main things to note are as follows: the scroll-snap-type-x and scroll-snap-type-y properties have been dropped the scroll-snap-type property has become a longhan...
Using CSS transitions - CSS: Cascading Style Sheets
perty: opacity, left; transition-duration: 3s, 5s, 2s, 1s; } this gets interpreted as: div { transition-property: opacity, left; transition-duration: 3s, 5s; } using transitions when highlighting menus a common use of css is to highlight items in a menu as the user hovers the mouse cursor over them. it's easy to use transitions to make the effect even more attractive. before we look at code snippets, you might want to take a look at the live demo (assuming your browser supports transitions). first, we set up the menu using html: <nav> <a href="#">home</a> <a href="#">about</a> <a href="#">contact us</a> <a href="#">links</a> </nav> then we build the css to implement the look and feel of our menu. the relevant portions are shown here: a { color: #fff; background-color...
CSS Writing Modes - CSS: Cascading Style Sheets
that defines various international writing modes, such as left-to-right (e.g. used by latin and indic scripts), right-to-left (e.g. used by hebrew or arabic scripts), bidirectional (used when mixing left-to-right and right-to-left scripts) and vertical (e.g. used by some asian scripts). ...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
esheets. though style sheets come from these different origins, they overlap in scope; to make this work, the cascade algorithm defines how they interact. user-agent stylesheets the browser has a basic style sheet that gives a default style to any document. these style sheets are named user-agent stylesheets. some browsers use actual style sheets for this purpose, while others simulate them in code, but the end result is the same. some browsers let users modify the user-agent stylesheet. although some constraints on user-agent stylesheets are set by the html specification, browsers still have a lot of latitude: that means that significant differences exist from one browser to another. to simplify the development process, web developers often use a css reset style sheet, forcing common prop...
Comments - CSS: Cascading Style Sheets
Web › CSS › Comments
by design, comments have no effect on the layout of a document. syntax comments can be placed wherever white space is allowed within a style sheet. they can be used on a single line, or traverse multiple lines. /* comment */ examples /* a one-line comment */ /* a comment which stretches over several lines */ /* the comment below is used to disable specific styling */ /* span { color: blue; font-size: 1.5em; } */ notes the /* */ comment syntax is used for both single and multiline comments. there is no other way to specify comments in external style sheets. ...
Layout and the containing block - CSS: Cascading Style Sheets
he computed value depends on the element's containing block. the properties that work this way are box model properties and offset properties: the height, top, and bottom properties compute percentage values from the height of the containing block. the width, left, right, padding, and margin properties compute percentage values from the width of the containing block. some examples the html code for all our examples is: <body> <section> <p>this is a paragraph!</p> </section> </body> only the css is altered in each instance below. example 1 in this example, the paragraph is statically positioned, so its containing block is <section> because it's the nearest ancestor that is a block container. <body> <section> <p>this is a paragraph!</p> </section> </body> body { ...
General sibling combinator - CSS: Cascading Style Sheets
lement only if it follows the first element (though not necessarily immediately), and both are children of the same parent element. /* paragraphs that are siblings of and subsequent to any image */ img ~ p { color: red; } syntax former_element ~ target_element { style properties } examples css p ~ span { color: red; } html <span>this is not red.</span> <p>here is a paragraph.</p> <code>here is some code.</code> <span>and here is a red span!</span> <code>more code...</code> <span>and this is a red span!</span> result specifications specification status comment selectors level 4the definition of 'subsequent-sibling combinator' in that specification. working draft renames it the "subsequent-sibling" combinator. selectors level 3the ...
Grid wrapper - CSS: Cascading Style Sheets
accessibil...
CSS Layout cookbook - CSS: Cascading Style Sheets
note: if you are new to css layout then you might first like to take a look at our css layout learning module, as this will give you the basic grounding you need to make use of the recipes here. ...
Testing media queries programmatically - CSS: Cascading Style Sheets
the query list. const mediaquerylist = window.matchmedia("(orientation: portrait)"); // define a callback function for the event listener. function handleorientationchange(mql) { // ... } // run the orientation change handler once. handleorientationchange(mediaquerylist); // add the callback function as a listener to the query list. mediaquerylist.addlistener(handleorientationchange); this code creates the orientation-testing media query list, then adds an event listener to it. after adding the listener, we also call the listener directly. this makes our listener perform adjustments based on the current device orientation; otherwise, our code might assume the device is in portrait mode at startup, even if it's actually in landscape mode. the handleorientationchange() function would loo...
Media queries - CSS: Cascading Style Sheets
or state. you can learn more about programmatically using media queries in testing media queries. reference at-rules @import @media guides using media queries introduces media queries, their syntax, and the operators and media features which are used to construct media query expressions. testing media queries programmatically describes how to use media queries in your javascript code to determine the state of a device, and to set up listeners that notify your code when the results of media queries change (such as when the user rotates the screen or resizes the browser). using media queries for accessibility learn how media queries can help users understand your website better. specifications specification status comment media queries level 5 ...
CSS reference - CSS: Cascading Style Sheets
Web › CSS › Reference
xt-overflowtext-renderingtext-shadowtext-transformtext-underline-offsettext-underline-position<time><time-percentage><timing-function>top@top-centertouch-actiontransformtransform-box<transform-function>transform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functiontranslatetranslate()translate3d()translatex()translatey()translatez()turnuunicode-bidiunicode-range (@font-face)unset<url>url()user-zoom (@viewport)v:validvar()vertical-alignvh@viewportviewport-fit (@viewport)visibility:visitedvmaxvminvwwwhite-spacewidowswidthwidth (@viewport)will-changeword-breakword-spacingword-wrapwriting-modexxzz-indexzoom (@viewport)others--* selectors the following are the various selectors, which allow styles to be conditional based on various featur...
Shorthand properties - CSS: Cascading Style Sheets
l. note: there is also a newer value, revert, which has limited browser support. note: see origin of css declarations in introducing the css cascade for more information on each of these and how they work. we can look at a list of links and explore how the universal values work. the live example below allows you to play with the css and see what happens when you make changes. playing with code really is the best way to get to grips with html and css. for example: the second list item has the class my-class-1 applied. this sets the color of the <a> element nested inside to inherit. if you remove the rule how does it change the color of the link? do you understand why the third and fourth links are the color that they are? check the description of the values above if not. which of ...
Specificity - CSS: Cascading Style Sheets
s :where() always has its specificity replaced with zero. this chunk of css ... div:where(.outer) p { color: orange; } div p { color: blueviolet; } #no-where-support { margin: 0.5em; border: 1px solid red; } #no-where-support:where(*) { display: none !important; } ... when used with the following html ... <div id="no-where-support"> ⚠️ your browser doesn't support the <code><a href="/docs/web/css/:where" target="_top">:where()</a></code> pseudo-class. </div> <div class="outer"> <p>this is in the outer div.</p> <div class="inner"> <p>this text is in the inner div.</p> </div> </div> ... appears on the screen like this: form-based specificity specificity is based on the form of a selector. in the following case, the selector *[id="foo"] counts as an ...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
se valid values can be used, via the var() functional notation, in a context where they might not make sense. properties and custom variables can lead to invalid css statements, leading to the new concept of valid at computed time. what happens with invalid variables? when the browser encounters an invalid var() substitution, the initial or inherited value of the property is used. consider the code snippet below. html <p>this paragraph is initial black.</p> css :root { --text-color: 16px; } p { color: blue; } p { color: var(--text-color); } as expected, the browser substitutes the value of --text-color in place of var(--text-color), but 16px is not a valid property value for color. after substitution, the property doesn’t make any sense. the browser handles this situation in two st...
WebKit CSS extensions - CSS: Cascading Style Sheets
the standards track. -webkit-mask-position-x* -webkit-mask-position-y* * supported unprefixed in firefox, with prefix in safari. supported in firefox with -webkit- prefix the following properties are supported with the -webkit- prefix in firefox. many of these are supported with no prefix as well: see formerly proprietary properties that are now standard above. note: due to the legacy code in a multitude of web sites that used -webkit- prefixed properties, edge and firefox redirect many -webkit- prefixed properties to -moz-, -ms-, and unprefixed equivalents. a -webkit-align-content -webkit-align-items -webkit-align-self -webkit-animation -webkit-animation-delay -webkit-animation-direction -webkit-animation-duration -webkit-animation-fill-mode -webkit-animation-iterati...
border-bottom-left-radius - CSS: Cascading Style Sheets
avior on internal table elements is undefined for the moment.. it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> examples live example code . an arc of circle is used as the border div { border-bottom-left-radius: 40px 40px; } . an arc of ellipse is used as the border div { border-bottom-left-radius: 40px 20px; } . the box is a square: an arc of circle is used as the border div { border-bottom-left-radius: 4...
border-bottom-right-radius - CSS: Cascading Style Sheets
avior on internal table elements is undefined for the moment.. it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> examples live example code . an arc of circle is used as the border div { border-bottom-right-radius: 40px 40px; } . an arc of ellipse is used as the border div { border-bottom-right-radius: 40px 20px; } . the box is a square: an arc of circle is used as the border div { border-bottom-right-radius...
border-top-left-radius - CSS: Cascading Style Sheets
avior on internal table elements is undefined for the moment.. ...
border-top-right-radius - CSS: Cascading Style Sheets
avior on internal table elements is undefined for the moment.. it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage> examples live example code an arc of circle is used as the border div { border-top-right-radius: 40px 40px; } an arc of ellipse is used as the border div { border-top-right-radius: 40px 20px; } the box is a square: an arc of circle is used as the border div { border-top-right-radius: 40%; } . ...
calc() - CSS: Cascading Style Sheets
Web › CSS › calc
ensure that input fields retain an appropriate size, we use calc() again to establish that they should be the width of their container minus 1em. then, the following html makes use of this css: <form> <div id="formbox"> <label>type something:</label> <input type="text"> </div> </form> nested calc() with css variables you can also use calc() with css variables. ...
clamp() - CSS: Cascading Style Sheets
Web › CSS › clamp
b repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. note that using clamp() for font sizes, as in these examples, allows you to set a font-size that grows with the size of the viewport, but doesn't go below a minimum font-size or above a maximum font-size. it has the same effect as the code in fluid typography but in one line, and without the use of media queries. syntax the clamp() function takes three comma separated expressions as its parameter, in the order of minimum value, preferred value, maximum value. the minimum value is the smallest (most negative) value. this is the lower bound in the range of allowed values. if the preferred value is less than this value, the minimum...
content - CSS: Cascading Style Sheets
Web › CSS › content
sed simultaneously */ content: open-quote chapter_counter; /* global values */ content: inherit; content: initial; content: unset; syntax values none the pseudo-element is not generated. normal computes to none for the ::before and ::after pseudo-elements. <string> specifies the "alt text" for the element. this value can be any number of text characters. non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol. <image> an <image>, denoted by the <url> or <gradient> data type, or part of the webpage, defined by the element() function, denoting the content to display. <counter>() the value of a css counter, generally a number. it can be displayed using either the counter() or counters() function. the counter...
counters() - CSS: Cascading Style Sheets
Web › CSS › counters
, or inherit. <counter-style> a counter style name or symbols() function, where a counter style name is a numeric, alphabetic, or symbolic simple predefined counter style, a complex longhand east asian or ethiopic predefined counter style, or other predefined counter style. if omitted, the counter-style defaults to decimal <string> any number of text characters. non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol. formal syntax counters( <custom-ident>, <string>, <counter-style>? )where <counter-style> = <counter-style-name> | symbols()where <counter-style-name> = <custom-ident> examples default value compared to upper roman html <ol> <li> <ol> <li></li> <li></li> <li></li> ...
cross-fade() - CSS: Cascading Style Sheets
ombining an image with a radial gradient. syntax important: the specification and current implementations have different syntaxes. the specification syntax is explained first. specification syntax the cross-fade() function takes a list of images with a percentage defining how much of each image is retained in terms of opacity when it is blended with the other images. the percent value must be coded without quotes, must contain the “%” symbol, and its value must be between 0% and 100%. the function can be used in css anywhere an ordinary image reference can be used. cross-fade percentages think of the percentage as an opacity value for each image. this means a value of 0% means the image is fully transparent while a value of 100% makes the image fully opaque. cross-fade( url(white.p...
env() - CSS: Cascading Style Sheets
Web › CSS › env
such that all content inside the rectangle is visible. note: unlike other css properties, user agent-defined property names are case-sensitive. formal syntax env( <custom-ident> , <declaration-value>? ) examples the below example makes use of the optional second parameter of env(), which allows you to provide a fallback value in case the environment variable is not available. <p> if the <code>env()</code> function is supported in your browser, this paragraph’s text will have 50px of padding between it and the left border — but not the top, right and bottom. this is because the accompanying css is the equivalent of <code>padding: 0 0 0 50px</code>, because, unlike other css properties, user agent property names are case-sensitive. </p> p { width: 300px; border: 2px s...
font-family - CSS: Cascading Style Sheets
ast item in the list of font family names. the following keywords are defined: serif glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings. e.g. lucida bright, lucida fax, palatino, "palatino linotype", palladio, "urw palladio", serif. sans-serif glyphs have stroke endings that are plain. e.g. "open sans", "fira sans", "lucida sans", "lucida sans unicode", "trebuchet ms", "liberation sans", "nimbus sans l", sans-serif. monospace all glyphs have the same fixed width. e.g. "fira mono", "dejavu sans mono", menlo, consolas, "liberation mono", monaco, "lucida console", monospace. cursive glyphs in cursive fonts generally have either joining strokes or other cursive characteristics beyond those of italic typefaces. the glyphs are partially or...
font-feature-settings - CSS: Cascading Style Sheets
ngs shouldn't be used to enable small caps. values normal text is laid out using default settings. <feature-tag-value> when rendering text, the list of opentype feature tag value is passed to the text layout engine to enable or disable font features. the tag is always a <string> of 4 ascii characters. if it has more or less characters, or if it contains characters outside the u+20 – u+7e codepoint range, the whole property is invalid. the value is a positive integer. the two keywords on and off are synonyms for 1 and 0 respectively. if no value is set, the default is 1. for non-boolean opentype features (e.g. stylistic alternates), the value implies a particular glyph to be selected; for boolean values, it is a switch. formal definition initial valuenormalapplies toall elements. i...
font-language-override - CSS: Cascading Style Sheets
system. for example, "eng" is english, and "kor" is korean. formal definition initial valuenormalapplies toall elements. it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | <string> examples using danish glyphs html <p class="para1">default language setting.</p> <p class="para2">this is a string with the <code>font-language-override</code> set to danish.</p> css p.para1 { font-language-override: normal; } p.para2 { font-language-override: "dan"; } result specifications specification status comment css fonts module level 4the definition of 'font-language-override' in that specification. working draft initial definition. ...
font-variant-alternates - CSS: Cascading Style Sheets
pped to a number. it corresponds to the opentype values swsh and cswh, like swsh 2 and cswh 2. ornaments() this function enables ornaments, like fleurons and other dingbat glyphs. the parameter is a font-specific name mapped to a number. it corresponds to the opentype value ornm, like ornm 2. note: in order to preserve text semantics, font designers should include ornaments that don't match unicode dingbat characters as ornamental variants of the bullet character (u+2022). be aware that some existing fonts don't follow this advice. annotation() this function enables annotations, like circled digits or inverted characters. the parameter is a font-specific name mapped to a number. it corresponds to the opentype value nalt, like nalt 2. formal definition initial valuenormalapplies toall...
font-variation-settings - CSS: Cascading Style Sheets
lt settings. <string> <number> when rendering text, the list of variable font axis names is passed to the text layout engine to enable or disable font features. each setting is always one or more pairs consisting of a <string> of 4 ascii characters followed by a <number> indicating the axis value to set. if the <string> has more or fewer characters or contains characters outside the u+20 - u+7e codepoint range, the whole property is invalid. the <number> can be fractional or negative, depending on the value range available in your font, as defined by the font designer. description this property is a low-level mechanism designed to set variable font features where no other way to enable or access those features exist. you should only use it when no basic properties exist to set those featu...
image-orientation - CSS: Cascading Style Sheets
nitial; image-orientation: unset; /* obsolete values. obsolete since gecko 63 */ image-orientation: 90deg; /* rotate 90deg */ image-orientation: 90deg flip; /* rotate 90deg, and flip it horizontally */ image-orientation: flip; /* no rotation, only applies a horizontal flip */ syntax values none default initial value. will not apply any additional image rotation; the image is oriented as encoded or as other css property values dictate. from-image the exif information contained in the image will be used to rotate the image appropriately. <angle> obsolete since gecko 63 the <angle> of rotation to apply to the image. it is rounded to the nearest 90deg (0.25turn). flip obsolete since gecko 63 the image is flipped horizontally (i.e., reflected) after the rotation given by the <angle>...
ime-mode - CSS: Cascading Style Sheets
Web › CSS › ime-mode
y is only partially and inconsistently implemented in browsers. it was introduced by microsoft with internet explorer 5 as a proprietary extension: -ms-ime-mode attribute | imemode property. note: in general, it's not appropriate for a public web site to change the ime mode. this property should only be used for private web applications or to undo the property if it was previously set by legacy code. syntax the ime-mode property is specified using one of the keyword values listed below. values auto no change is made to the current input method editor state. this is the default. normal the ime state should be normal; this value can be used in a user style sheet to override the page's setting. this value is not supported by internet explorer. active the input method editor is initi...
<integer> - CSS: Cascading Style Sheets
Web › CSS › integer
tive integer 0 zero +0 zero, with a leading + -0 zero, with a leading - invalid integers 12.0 this is a <number>, not an <integer>, though it represents an integer. 12. decimal points are not allowed. +---12 only one leading +/- is allowed. ten letters are not allowed. _5 special characters are not allowed. \35 escaped unicode characters are not allowed, even if they are an integer (here: 5). \4e94 non-arabic numerals are not allowed, even when escaped (here: the japanese 5, 五). 3e4 scientific notation is not allowed. specifications specification status comment css values and units module level 4the definition of '<integer>' in that specification. editor's draft no s...
margin-bottom - CSS: Cascading Style Sheets
tive value places it farther from its neighbors, while a negative value places it closer. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this property has no effect on non-replaced inline elements, such as <span> or <code>. syntax /* <length> values */ margin-bottom: 10px; /* an absolute length */ margin-bottom: 1em; /* relative to the text size */ margin-bottom: 5%; /* relative to the nearest block container's width */ /* keyword values */ margin-bottom: auto; /* global values */ margin-bottom: inherit; margin-bottom: initial; margin-bottom: unset; the margin-bottom property is specified as the keywor...
margin-top - CSS: Cascading Style Sheets
sitive value places it farther from its neighbors, while a negative value places it closer. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this property has no effect on non-replaced inline elements, such as <span> or <code>. syntax /* <length> values */ margin-top: 10px; /* an absolute length */ margin-top: 1em; /* relative to the text size */ margin-top: 5%; /* relative to the nearest block container's width */ /* keyword values */ margin-top: auto; /* global values */ margin-top: inherit; margin-top: initial; margin-top: unset; the margin-top property is specified as the keyword auto, or a <length>, o...
margin - CSS: Cascading Style Sheets
Web › CSS › margin
is a shorthand for margin-top, margin-right, margin-bottom, and margin-left. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the top and bottom margins have no effect on non-replaced inline elements, such as <span> or <code>. note: margins create extra space around an element. in contrast, padding creates extra space within an element. syntax /* apply to all four sides */ margin: 1em; margin: -3px; /* vertical | horizontal */ margin: 5% auto; /* top | horizontal | bottom */ margin: 1em auto 2em; /* top | right | bottom | left */ margin: 2px 1em 0 auto; /* global values */ margin: inherit; margin: initial; m...
order - CSS: Cascading Style Sheets
Web › CSS › order
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax /* <integer> values */ order: 5; order: -5; /* global values */ order: inherit; order: initial; order: unset; since order is only meant to affect the visual order of elements and not their logical or tab order. ...
overscroll-behavior-x - CSS: Cascading Style Sheets
, and default scroll overflow behavior is prevented. formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto examples preventing an underlying element from scrolling horizontally in our simple overscroll-behavior-x example (see source code also), we have two block-level boxes, one inside the other. the outer box has a large width set on it so the page will scroll horizontally. the inner box has a small width (and height) set on it so it sits comforably inside the viewport, but its content is given a large width so it will scroll horizontally. by default, when the inner box is scrolled and a scroll boundary is reached, the whole pa...
overscroll-behavior - CSS: Cascading Style Sheets
ling areas, and default scroll overflow behavior is prevented. formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ contain | none | auto ]{1,2} examples preventing an underlying element from scrolling in our overscroll-behavior example (see the source code also), we present a full-page list of fake contacts, and a dialog box containing a chat window. both of these areas scroll; normally if you scrolled the chat window until you hit a scroll boundary, the underlying contacts window would start to scroll too, which is not desirable. this can be stopped using overscroll-behavior-y (overscroll-behavior would also work) on the chat window, like this...
<ratio> - CSS: Cascading Style Sheets
Web › CSS › ratio
the <ratio> css data type, used for describing aspect ratios in media queries, denotes the proportion between two unitless values. syntax in media queries level 3, the <ratio> data type consisted of a strictly positive <integer> followed by a forward slash ('/', unicode u+002f solidus) and a second strictly positive <integer>. spaces before and after the slash are optional. the first number represents the width, while the second represents the height. in media queries level 4, the <ratio> date type is updated to consist of a strictly positive <number> followed by a forward slash ('/', unicode u+002f solidus) and a second strictly positive <number>. in addition a single <number> as a value is allowable. examples use in a media query @media screen and (min-aspect-ratio: 16/9) { ... } com...
text-decoration-skip - CSS: Cascading Style Sheets
obal values */ text-decoration-skip: inherit; text-decoration-skip: initial; text-decoration-skip: unset; syntax values none nothing is skipped. thus, text decoration is drawn for all text content and across atomic inline-level boxes. objects the entire margin box of the element is skipped if it is an atomic inline such as an image or inline-block. spaces all spacing is skipped: all unicode white space characters and all word separators, plus any adjacent letter-spacing or word-spacing. leading-spaces the same as spaces, except that only leading spaces are skipped. trailing-spaces the same as spaces, except that only trailing spaces are skipped. edges the start and end of the text decoration is inset slightly (e.g., by half of the line thickness) from the content edge of the d...
transform-box - CSS: Cascading Style Sheets
specifications specification status comment css transforms level 1the definition of 'transform-box' in that specification. working draft initial definition ...
transform-origin - CSS: Cascading Style Sheets
nding boxcomputed valuefor <length> the absolute value, otherwise a percentageanimation typesimple list of length, percentage, or calc formal syntax [ <length-percentage> | left | center | right | top | bottom ] | [ [ <length-percentage> | left | center | right ] && [ <length-percentage> | top | center | bottom ] ] <length>?where <length-percentage> = <length> | <percentage> examples code sample transform: none; <div class="box1">&nbsp;</div> .box1 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: none; -webkit-transform: none; } transform: rotate(30deg); <div class="box2">&nbsp;</div> .box2 { margin: 0.5em; width: 3em; height: 3em; bo...
will-change - CSS: Cascading Style Sheets
izations that the browser make is to remove the optimizations as soon as it can and revert back to normal. but adding will-change directly in a stylesheet implies that the targeted elements are always a few moments away from changing and the browser will keep the optimizations for much longer time than it would have otherwise. so it is a good practice to switch will-change on and off using script code before and after the change occurs. don't apply will-change to elements to perform premature optimization. if your page is performing well, don't add the will-change property to elements just to wring out a little more speed. will-change is intended to be used as something of a last resort, in order to try to deal with existing performance problems. it should not be used to anticipate perfo...
CSS: Cascading Style Sheets
Web › CSS
collapse the containing block stacking and block-formatting contexts initial, computed, used, and actual values css shorthand properties css flexible box layout css grid layout media queries animation cookbook the css layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your sites. in addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer. tools for css development you can use the w3c css validation service to check if your css is valid. this is an invaluable debugging tool. firefox developer tools lets you view and edit a page's live css via the inspector ...
regexp:match() - EXSLT
Web › EXSLT › regexp › match
ne, the first match element has the value of the portion of the string matched by the entire regular expression. ...
Index - Event reference
Web › Events › Index
each event is represented by an object which is based on the event interface, and may have additional custom fields and/or functions used to get additional information about what happened. ...
Event reference
each event is represented by an object which is based on the event interface, and may have additional custom fields and/or functions used to get additional information about what happened. events can represent everything from basic user interactions to automated notifications of things happening in the rendering model. this article offers a list of events that can be sent; some are standard events defined in official specifications, while others are events used internally by specific browsers; for example, mozilla-specific events are listed so that add-ons can use them to interact with the browser. ...
Community - Developer guides
Web › Guide › AJAX › Community
if you know of useful mailing lists, newsgroups, forums, or other communities related to ajax, please link to them here. ...
WAI ARIA Live Regions/API Support - Developer guides
explicit user input? does not require author's cooperation. the "container-" prefix is so named because the attribute describes what the final computed property of similar name is for that node. this means that the at does not need to traverse up the parent chain to get this information. at this time, for properties where the container-[name] attribute has not been set, the at must have code to fall back on the default value as defined in the w3c spec. determining if event was from user input all events will now provide information about whether the event was caused by user input, or was something that the web page caused. this information is retrieved differently on each platform, because some platforms use asynchronous events. in iaccessible2, this is retrieved from the object attr...
Challenge solutions - Developer guides
big initial letters challenge without changing anything else, make all six initial letters twice the size in the browser's default serif font. solution add the following style declaration to the strong rule: font: 200% serif; if you use separate declarations for font-size and font-family, then the font-style setting on the first paragraph is not overridden. color three-digit color codes challenge in your css file, change all the color names to 3-digit color codes without affecting the result. solution the following values are reasonable approximations of the named colors: strong { color: #f00; /* red */ background-color: #ddf; /* pale blue */ font: 200% serif; } .carrot { color: #fa0; /* orange */ } .spinach { color: #080; /* dark green */ } p { color: #00...
Creating and triggering events - Developer guides
ispatch dom events. such events are commonly called synthetic events, as opposed to the events fired by the browser itself. creating custom events events can be created with the event constructor as follows: const event = new event('build'); // listen for the event. elem.addeventlistener('build', function (e) { /* ... */ }, false); // dispatch the event. elem.dispatchevent(event); the above code example uses the eventtarget.dispatchevent() method. this constructor is supported in most modern browsers (with internet explorer being the exception). for a more verbose approach (which works with internet explorer), see the old-fashioned way below. adding custom data – customevent() to add more data to the event object, the customevent interface exists and the detail property can be used ...
Media events - Developer guides
the time indicated by the element's currenttime attribute has changed. volumechange sent when the audio volume changes (both when the volume is set and when the muted attribute is changed). waiting sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). you can easily watch for these events, using code such as the following: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("seeked", function() { v.play(); }, true); v.currenttime = 10.0; this example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. the listener simply calls the element's play() method, w...
Mouse gesture events - Developer guides
so be large incompatibilities between implementations and the behavior may change in the future. gecko 1.9.1 added support for several mozilla-specific dom events used to handle mouse gestures. these are special movements that can be made with a mouse or trackpad and can be interpreted to perform specific tasks. note: these gesture events are available to add-ons and other browser chrome code, but are never sent to regular web page content. note: some operating systems, including mac os x and windows 7, provide default actions when gesture events occur. if you handle a gesture event and wish to prevent the default action from taking place as well, be sure to call the event's preventdefault() method. types of gesture events mozswipegesture the mozswipegesture event is sent when the u...
Using device orientation with 3D transforms - Developer guides
reen pointing 12:00), so the rotatez value should be alpha - 180 the y axis of the screen coordinate system is inverted, such that translatey(100px) moves an element 100px down, so the rotatey value should be -gamma finally, the order of the three different rotations is very important to accurately convert an orientation to a 3d rotation: rotatez, then rotatex and then rotatey. ...
Event developer guide - Developer guides
Web › Guide › Events
for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types. the overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers. the custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code. the remaining pages describe how to use events of different kinds defined by web browsers. unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying syst...
Making content editable - Developer guides
ment, br, for defaultparagraphseparator since firefox 55. this is useful if your web application expects the older firefox behavior, and you don't want to or don't have the time to update it to use the new behavior. you can use the older firefox behavior with this line: document.execcommand("defaultparagraphseparator", false, "br"); security for security reasons, firefox doesn't let javascript code use clipboard related features (copy, paste, etc.) by default. you can enable them by setting the preferences shown below using about:config: user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.clipboard.cutcopy", "allaccess"); user_pref("capability.policy.allowcl...
Introduction to HTML5 - Developer guides
y, which is no longer the case. now, faced with errors in the mark-up, all compliant browsers must behave exactly in the same way. this requirement helps web developers quite a bit. while it is true that all modern browsers now use these html5 parsing rules, non-html5-compliant browsers are still used by some. keep in mind that it's still highly recommended that one writes valid mark-up, as such code is easier to read and maintain, and it greatly decreases the prominence of incompatibilities that exists in various older browsers. don't worry — you don't have to change anything on your website. the web browsers' developers have done everything for you! ...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
attributes, authors can now be precise about the level of security and the wished rendering of an <iframe> element. mathml allows directly embedding mathematical formulas. introduction to html5 this article introduces how to indicate to the browser that you are using html5 in your web design or web application. html5 reference guide quick-reference html5 sheet containing markup generators, code examples and web developer tools. the guide is downloadable for ease of use and access. this page was created with help from the w3c as a quick guide for those who have some basic familiarity and experience using html5. downloadable html5 guide a quick guide to html5, including the common html tags as well as the new html5 tags. downloadable in pdf and png formats. html5 cheat sheet a handy ...
HTML attribute: accept - HTML: Hypertext Markup Language
regardless of the user's device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file. including the multiple attribute, as shown above, specifies that multiple files can be chosen at once. the user can choose multiple files from the file picker in any way that their chosen platform allows (...
HTML attribute: required - HTML: Hypertext Markup Language
lso applies to it. conversely, inputs that support the required attribute but don't have the attribute set match the :optional pseudo-class. in the case of a same named group of radio buttons, if a single radio button in the group has the required attribute, a radio button in that group must be check, though it doesn't have to be the one with the attribute is applied. for this reason, to improve code maintenance, it is recommened to either include the required attribute in every same-named radio button in the group or none. in the case of a same named group of checkbox input types, only the checkboxes with the required attribute are required. note: setting aria-required="true" tells a screen reader that an element (any element) is required, but has no bearing on the optionality of the elem...
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
rious bit rates. to start with you'll only need the ffpmeg program from ffmpeg.org, with libvpx and libvorbis support for webm video and audio, at least version 2.5 (probably; this was tested ith 3.2.5). 1. use your existing webm file to create one audio file and multiple video files. for example: the file in.video can be any container with at least one audio and one video stream that can be decoded by ffmpeg, create the audio using: ffmpeg -i in.video -vn -acodec libvorbis -ab 128k -dash 1 my_audio.webm create each video variant. ffmpeg -i in.video -c:v libvpx-vp9 -keyint_min 150 -g 150 -tile-columns 4 -frame-parallel 1 -f webm -dash 1 \ -an -vf scale=160:90 -b:v 250k -dash 1 video_160x90_250k.webm ffmpeg -i in.video -c:v libvpx-vp9 -keyint_min 150 -g 150 -tile-columns 4 -frame-par...
<button>: The Button element - HTML: Hypertext Markup Language
Web › HTML › Element › button
not just inside a <form>. it can also override an ancestor <form> element. formaction html5 the url that processes the information submitted by the button. overrides the action attribute of the button's form owner. does nothing if there is no form owner. formenctype html5 if the button is a submit button (it's inside/associated with a <form> and doesn't have type="button"), specifies how to encode the form data that is submitted. possible values: application/x-www-form-urlencoded: the default if the attribute is not used. multipart/form-data: use to submit <input> elements with their type attributes set to file. text/plain: specified as a debugging aid; shouldn’t be used for real form submission. if this attribute is specified, it overrides the enctype attribute of the button...
<caption>: The Table Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › caption
ment, as its first descendant. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmltablecaptionelement attributes this element includes the global attributes. deprecated attributes the following attributes are deprecated and should not be used. they are documented below for reference when updating existing code and for historical interest only. align this enumerated attribute indicates how the caption must be aligned with respect to the table. it may have one of the following values: left the caption is displayed to the left of the table. top the caption is displayed above the table. right the caption is displayed to the right of the table. bottom the caption is displayed below t...
<del>: The Deleted Text element - HTML: Hypertext Markup Language
Web › HTML › Element › del
the <ins> element can be used for the opposite purpose: to indicate text that has been added to the document. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this element is often (but need not be) rendered by applying a strike-through style to the text. ...
<dl>: The Description List element - HTML: Hypertext Markup Language
Web › HTML › Element › dl
dentation of a description term, use the css margin property. accessibility concerns each screen reader announces <dl> content differently. some screen readers, such as voiceover on ios, will not announce that <dl> content is a list. because of this, make sure each list item's content is written in such a way that it communicates its relationship to the other list items in the list grouping. codepen - html buddies: dt & dd specifications specification status comment html living standardthe definition of '<dl>' in that specification. living standard html5the definition of '<dl>' in that specification. recommendation html 4.01 specificationthe definition of '<dl>' in that specification. recommendation initial definition ...
<form> - HTML: Hypertext Markup Language
Web › HTML › Element › form
he following attributes control behavior during form submission. action the url that processes the form submission. this value can be overridden by a formaction attribute on a <button>, <input type="submit">, or <input type="image"> element. enctype if the value of the method attribute is post, enctype is the mime type of the form submission. possible values: application/x-www-form-urlencoded: the default value. multipart/form-data: use this if the form contains <input> elements with type=file. text/plain: introduced by html5 for debugging purposes. this value can be overridden by formenctype attributes on <button>, <input type="submit">, or <input type="image"> elements. method the http method to submit the form with. possible (case insensitive) values: post: the pos...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
ack the access-control-allow-credentials: true response header), then the browser marks the image as tainted and restricts access to its image data. if the attribute has an invalid value, browsers handle it as if the anonymous value was used. see cors settings attributes for additional information. decoding provides an image decoding hint to the browser. allowed values: sync decode the image synchronously, for atomic presentation with other content. async decode the image asynchronously, to reduce delay in presenting other content. auto default: no preference for the decoding mode. the browser decides what is best for the user. height the intrinsic height of the image, in pixels. must be an integer without a unit. importance indicates the relative download...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
he browser may use its own heuristics to decide the priority of the resource. high: indicates to the browser that the resource is of high priority. low: indicates to the browser that the resource is of low priority. note: the importance attribute may only be used for the <link> element if rel="preload" or rel="prefetch" is present. integrity contains inline metadata — a base64-encoded cryptographic hash of the resource (file) you’re telling the browser to fetch. the browser can use this to verify that the fetched resource has been delivered free of unexpected manipulation. see subresource integrity. media this attribute specifies the media that the linked resource applies to. its value must be a media type / media query. this attribute is mainly useful when linking to ext...
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
Web › HTML › Element › meta
ame attribute is set, the meta element provides document-level metadata, applying to the whole page. if the http-equiv attribute is set, the meta element is a pragma directive, providing information equivalent to what can be given by a similarly-named http header. if the charset attribute is set, the meta element is a charset declaration, giving the character encoding in which the document is encoded. if the itemprop attribute is set, the meta element provides user-defined metadata. attributes this element includes the global attributes. note: the attribute name has a specific meaning for the <meta> element, and the itemprop attribute must not be set on the same <meta> element that has any existing name, http-equiv or charset attributes. charset this attribute declares the documen...
<object> - HTML: Hypertext Markup Language
Web › HTML › Element › object
ludes the global attributes. archivehtml 4 onlyobsolete since html5 a space-separated list of uris for archives of resources for the object. borderdeprecated since html4.01obsolete since html5 the width of a border around the control, in pixels. classidhtml 4 onlyobsolete since html5 the uri of the object's implementation. it can be used together with, or in place of, the data attribute. codebasehtml 4 onlyobsolete since html5 the base path used to resolve relative uris specified by classid, data, or archive. if not specified, the default is the base uri of the current document. codetypehtml 4 onlyobsolete since html5 the content type of the data specified by classid. data the address of the resource as a valid url. at least one of data and type must be defined. declarehtml 4 on...
<plaintext>: The Plain Text element (Deprecated) - HTML: Hypertext Markup Language
n html5; browsers that accept it may instead treat it as a <pre> element that still interprets html within. if <plaintext> is the first element on the page (other than any non-displayed elements, like <head>), do not use html at all. instead serve a text file with the text/plain mime-type. instead of <plaintext>, use the <pre> element or, if semantically accurate (such as for inline text), the <code> element. escape any <, > and & characters, to prevent browsers inadvertently parsing content the element content as html. a monospaced font can be applied to any html element via a css font-family style with the monospace generic value. attributes this element has no other attributes than the global attributes common to all elements. dom interface this element implements the htmlelement i...
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
Web › HTML › Element › rb
s this element only includes the global attributes. usage notes ruby annotations are for showing pronunciation of east asian characters, like using japanese furigana or taiwanese bopomofo characters. the <rb> element is used to separate out each segment of the ruby base text. even though <rb> is not an empty element, it is common to just include the opening tag of each element in the source code, so that the ruby markup is less complex and easier to read. the browser can then fill in the full element in the rendered version. you need to include one <rt> element for each base segment/<rb> element that you want to annotate. examples in this example, we provide an annotation for the original character equivalent of "kanji": <ruby> <rb>漢<rb>字 <rp>(</rp><rt>kan<rt>ji<rp>)</rp> </...
<samp>: The Sample Output element - HTML: Hypertext Markup Language
Web › HTML › Element › samp
n use a css rule to override the browser's default font face for the <samp> element; however, it's possible that the browser's preferences may take precedence over any css you specify. the css to override the default font face would look like this: samp { font-family: "courier"; } if you need an element which will serve as a container for output generated by your website or app's javascript code, you should instead use the <output> element. examples basic example in this simple example, a paragraph includes an example of the output of a program. <p>when the process is complete, the utility will output the text <samp>scan complete. found <em>n</em> results.</samp> you can then proceed to the next step.</p> the resulting output looks like this: sample output including user input ...
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
Web › HTML › Element › shadow
g are mandatory. permitted parents any element that accepts flow content. permitted aria roles none dom interface htmlshadowelement attributes this element includes the global attributes. example here is a simple example of using the <shadow> element. it is an html file with everything needed in it. note: this is an experimental technology. for this code to work, the browser you display it in must support web components. see enabling web components in firefox. <html> <head></head> <body> <!-- this <div> will hold the shadow roots. --> <div> <!-- this heading will not be displayed --> <h4>my original heading</h4> </div> <script> // get the <div> above with its content var origcontent = document.queryselector('div');...
<slot> - HTML: Hypertext Markup Language
Web › HTML › Element › slot
f } .name {font-weight: bold; color: #217ac0; font-size: 120% } h4 { margin: 10px 0 -8px 0; background: #217ac0; color: white; padding: 2px 6px; border: 1px solid #cee9f9; border-radius: 4px; } .attributes { margin-left: 22px; font-size: 90% } .attributes p { margin-left: 16px; font-style: italic } </style> <details> <summary> <code class="name">&lt;<slot name="element-name">need name</slot>&gt;</code> <i class="desc"><slot name="description">need description</slot></i> </summary> <div class="attributes"> <h4>attributes</h4> <slot name="attributes"><p>none</p></slot> </div> </details> <hr> </template> note: you can see this complete example in action at element-details (see it running live...
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
Web › HTML › Element › source
criptor to be valid. among the list, there must be only one string containing the same tuple of width descriptor and pixel density descriptor. the browser chooses the most adequate image to display at a given point of time. the srcset attribute has an effect only when the <source> element is the direct child of a <picture> element. type the mime media type of the resource, optionally with a codecs parameter. if the type attribute isn't specified, the media's type is retrieved from the server and checked to see if the user agent can handle it; if it can't be rendered, the next <source> is checked. if the type attribute is specified, it's compared against the types the user agent can present, and if it's not recognized, the server doesn't even get queried; instead, the next <source> elem...
<strike> - HTML: Hypertext Markup Language
Web › HTML › Element › strike
, and obsoleted in html5. if semantically appropriate, i.e., if it represents deleted content, use <del> instead. in all other cases use <s>. dom interface htmlelement attributes this element includes the global attributes. example &lt;strike&gt;: <strike>today's special: salmon</strike> sold out<br /> &lt;s&gt;: <s>today's special: salmon</s> sold out the result of this code is: specifications specification status comment html5the definition of '<strike>' in that specification. recommendation make obsolete in favor of <del> and <s>. html 4.01 specificationthe definition of '<strike>' in that specification. recommendation make deprecated in favor of <del> and <s>. ...
<tbody>: The Table Body element - HTML: Hypertext Markup Language
Web › HTML › Element › tbody
if this attribute is not set, the left value is assumed. as this attribute is deprecated, use the css text-align property instead. note: the equivalent text-align property for the align="char" is not implemented in any browsers yet. see the text-align's browser compatibility section for the <string> value. bgcolor the background color of the table. it is a 6-digit hexadecimal rgb code, prefixed by a '#'. one of the predefined color kewords can also be used. as this attribute is deprecated, use the css background-color property instead. char this attribute is used to set the character to align the cells in a column on. typical values for this include a period (.) when attempting to align numbers or monetary values. if align is not set to char, this attribute is ignore...
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
Web › HTML › Element › td
achieve the same effect as the char value, give the text-align property the same value you would use for the char. unimplemented in css3. axis this attribute contains a list of space-separated strings. each string is the id of a group of cells that this header applies to. bgcolor this attribute defines the background color of each cell in a column. it is a 6-digit hexadecimal rgb code, prefixed by a '#'. one of the predefined color kewords can also be used. to achieve a similar effect, use the css background-color property. char the content in the cell element is aligned to a character. typical values include a period (.) to align numbers or monetary values. if align is not set to char, this attribute is ignored. charoff this attribute is used to shift column da...
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › template
mltemplateelement has a content property, which is a read-only documentfragment containing the dom subtree which the template represents. note that directly using the value of the content could lead to unexpected behavior, see avoiding documentfragment pitfall section below. examples first we start with the html portion of the example. <table id="producttable"> <thead> <tr> <td>upc_code</td> <td>product_name</td> </tr> </thead> <tbody> <!-- existing data could optionally be included here --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template> first, we have a table into which we will later insert content using javascript code. then comes the template, which describes the structure of an html fr...
<textarea> - HTML: Hypertext Markup Language
Web › HTML › Element › textarea
is associated with (its "form owner"). the value of the attribute must be the id of a form element in the same document. if this attribute is not specified, the <textarea> element must be a descendant of a form element. this attribute enables you to place <textarea> elements anywhere within a document, not just as descendants of form elements. maxlength the maximum number of characters (utf-16 code units) that the user can enter. if this value isn't specified, the user can enter an unlimited number of characters. minlength the minimum number of characters (utf-16 code units) required that the user should enter. name the name of the control. placeholder a hint to the user of what can be entered in the control. carriage returns or line-feeds within the placeholder text must be treated a...
<tfoot>: The Table Foot element - HTML: Hypertext Markup Language
Web › HTML › Element › tfoot
ndard. to achieve the same effect as the left, center, right or justify values, use the css text-align property on it. to achieve the same effect as the char value, in css3, you can use the value of the char as the value of the text-align property unimplemented. bgcolor this attribute defines the background color of each cell of the column. it is one of the 6-digit hexadecimal code as defined in srgb, prefixed by a '#'. one of the sixteen predefined color strings may be used: black = "#000000" green = "#008000" silver = "#c0c0c0" lime = "#00ff00" gray = "#808080" olive = "#808000" white = "#ffffff" yellow = "#ffff00" maroon = "#800000" navy = "#...
<th> - HTML: Hypertext Markup Language
Web › HTML › Element › th
css3. axis obsolete since html5 this attribute contains a list of space-separated strings. each string is the id of a group of cells that this header applies to. note: do not use this attribute as it is obsolete in the latest standard: use the scope attribute instead. bgcolor this attribute defines the background color of each cell in a column. it consists of a 6-digit hexadecimal code as defined in srgb and is prefixed by '#'. this attribute may be used with one of sixteen predefined color strings: black = "#000000" green = "#008000" silver = "#c0c0c0" lime = "#00ff00" gray = "#808080" olive = "#808000" white = "#ffffff" yellow = "#ffff00" maroon = "#800000...
<thead>: The Table Head element - HTML: Hypertext Markup Language
Web › HTML › Element › thead
ndard. to achieve the same effect as the left, center, right or justify values, use the css text-align property on it. to achieve the same effect as the char value, in css3, you can use the value of the char as the value of the text-align property unimplemented. bgcolor this attribute defines the background color of each cell of the column. it is one of the 6-digit hexadecimal code as defined in srgb, prefixed by a '#'. one of the sixteen predefined color strings may be used: black = "#000000" green = "#008000" silver = "#c0c0c0" lime = "#00ff00" gray = "#808080" olive = "#808000" white = "#ffffff" yellow = "#ffff00" maroon = "#800000" navy = "#...
<wbr> - HTML: Hypertext Markup Language
Web › HTML › Element › wbr
empty tag omission it is an empty element; it must have a start tag, but must not have an end tag. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. notes on utf-8 encoded pages, <wbr> behaves like the u+200b zero-width space code point. in particular, it behaves like a unicode bidi bn code point, meaning it has no effect on bidi-ordering: <div dir=rtl>123,<wbr>456</div> displays, when not broken on two lines, 123,456 and not 456,123. for the same reason, the <wbr> element does not introduce a hyphen at the line break point. to make a hyphen appear only at ...
<xmp> - HTML: Hypertext Markup Language
Web › HTML › Element › xmp
interpreting the html in between and using a monospaced font. the html2 specification recommended that it should be rendered wide enough to allow 80 characters per line. note: do not use this element. it has been deprecated since html3.2 and was not implemented in a consistent way. it was completely removed from the language in html5. use the <pre> element or, if semantically adequate, the <code> element instead. note that you will need to escape the '<' character as '&lt;' to make sure it is not interpreted as markup. a monospaced font can also be obtained on any element, by applying an adequate css style using monospace as the generic-font value for the font-family property. attributes this element has no other attributes than the global attributes, common to all elements. dom in...
dir - HTML: Hypertext Markup Language
e element until it finds a character with a strong directionality, then applies that directionality to the whole element. usage notes: this attribute is mandatory for the <bdo> element where it has a different semantic meaning. this attribute is not inherited by the <bdi> element. if not set, its value is auto. this attribute can be overridden by the css properties direction and unicode-bidi, if a css page is active and the element supports these properties. as the directionality of the text is semantically related to its content and not to its presentation, it is recommended that web developers use this attribute instead of the related css properties when possible. that way, the text will display correctly even on a browser that doesn't support css or has the css deactiva...
id - HTML: Hypertext Markup Language
ctive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. this attribute's value is an opaque string: this means that web authors should not rely on it to convey human-readable information (although having your ids somewhat human-readable can be useful for code comprehension, e.g. consider ticket-18659 versus r45tgfe-freds&$@). id's value must not contain whitespace (spaces, tabs etc.). browsers treat non-conforming ids that contain whitespace as if the whitespace is part of the id. in contrast to the class attribute, which allows space-separated values, elements can only have one single id value. note: using characters except ascii letters, digits,...
is - HTML: Hypertext Markup Language
the is global attribute allows you to specify that a standard html element should behave like a defined custom built-in element (see using custom elements for more details). this attribute can only be used if the specified custom element name has been successfully defined in the current document, and extends the element type it is being applied to. examples the following code is taken from our word-count-web-component example (see it live also). // create a class for the element class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // constructor contents ommitted for brevity ... } } // define the new element customelements.define('word-count', wordcount, { extends: 'p' }); <p is="word-count"></p> specifi...
itemscope - HTML: Hypertext Markup Language
recipeingredient">thinly-sliced apples: 6 cups<br></span> <span itemprop="recipeingredient">white sugar: 3/4 cup<br></span> ... </p> directions: <br> <div itemprop="recipeinstructions"> 1. cut and peel apples<br> 2. mix sugar and cinnamon. use additional sugar for tart apples. <br> ... </div> </div> results html the following is an example rendering of the preceding code example. structured data itemscope itemtype recipe itemprop name grandma's holiday apple pie itemprop image https://c1.staticflickr.com/1/30/42759561_8631e2f905_n.jpg itemprop datepublished 2009-11-05 itemprop description this is my grandmother's apple pie recipe. i like to add a dash of nutmeg. itemprop pr...
title - HTML: Hypertext Markup Language
a real <label> labeling controls in data tables additional semantics are attached to the title attributes of the <link>, <abbr>, <input>, and <menuitem> elements. multiline titles the title attribute may contain several lines. each u+000a line feed (lf) character represents a line break. some caution must be taken, as this means the following renders across two lines: html <p>newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on. if this attribute is set to the empty string, it means its ancestors' titles are irrelevant and shouldn't be used...
Inline elements - HTML: Hypertext Markup Language
hand, typically cause a line break to occur (although, as usual, this can be changed using css). ...
Using the application cache - HTML: Hypertext Markup Language
ires online access. network entries in an application cache are essentially an "online whitelist"—uris specified in the network section are loaded from the server instead of the cache. this lets the browser's security model protect the user from potential security breaches by limiting access to approved resources. as an example, you can use network entries to load and execute scripts and other code from the server instead of the cache: cache manifest network: /api the cache manifest section listed above ensures that requests to load resources contained in the http://www.example.com/api/ subtree always go to the network without attempting to access the cache. note: simply omitting master entries (files that have the manifest attribute set in the html element) from the manifest file would...
Choosing between www and non-www URLs - HTTP
ain. this will redirect the browser trying to access the non-canonical urls to their canonical equivalent. for example, if you've chosen to use non-www urls as the canonical type, you should redirect all www urls to their equivalent url without the www. example: a server receives a request for http://www.example.org/whaddup (when the canonical domain is example.org) the server answers with a code 301 with the header location: http://example.org/whaddup. the client issues a request to the canonical domain: http://example.org/whatddup the html5 boilerplate project has an example on how to configure an apache server to redirect one domain to the other. using <link rel="canonical"> it is possible to add a special html <link> element to a page to indicate what the canonical address of a p...
Identifying resources on the Web - HTTP
cols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols. common schemes are: scheme description data data uris file host-specific file names ftp file transfer protocol http/https hyper text transfer protocol (secure) javascript url-embedded javascript code mailto electronic mail address ssh secure shell tel telephone urn uniform resource names view-source source code of the resource ws/wss (encrypted) websocket connections authority www.example.com is the domain name or authority that governs the namespace. it indicates which web server is being requested. alternati...
Resource URLs - HTTP
reats because some of the information shared by resource: urls is available to websites, a web page could run internal scripts and inspect internal resources of firefox, including the default preferences, which could be a serious security and privacy issue. for example, a script on browserleaks highlights what firefox reveals when queried by a simple script running on the site (you can find the code in https://browserleaks.com/firefox#more). the file firefox.js passes preference names and values to the pref() function. for example: http://searchfox.org/mozilla-central/rev/48ea452803907f2575d81021e8678634e8067fc2/browser/app/profile/firefox.js#575 web sites can easily collect firefox default preferences by overriding this pref() function and using the script resource:///defaults/preference...
Basics of HTTP - HTTP
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 connection and pipelining. this article explains both concepts. connection management in http/2 http/2 completely revisited how connections are created and maintained. this article explains how http frames allow multiplexing and solve the 'head-of-line' blocking problem of former http versions. c...
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
reason reason: cors header 'access-control-allow-origin' does not match 'xyz' what went wrong? simply put, the origin making the request does not match any of the origins permitted by the access-control-allow-origin header. this error can also occur if the response includes more than one access-control-allow-origin header. if the service your code is accessing using a cors request is under your control, make sure that it's configured to include your origin in its access-control-allow-origin header, and that only one such header is included in responses. the header itself accepts a comma-delineated list of origins, so adding a new origin is not difficult. for example, in apache, add a line such as the following to the server's configuration (within the appropriate <directory>, <location...
Reason: CORS request external redirect not allowed - HTTP
...
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
access-control-allow-methods header. this header specifies a comma-delineated list of the http methods which may be used when using cors to access the url specified in the request; if the request is using any other method, this error occurs. for example, if the response includes: access-control-allow-methods: get,head,post trying to use a put request will fail with this error. make sure your code only uses the permitted http methods when accessing the service. note: if the server includes any unrecognized or undefined method names in its access-control-allow-methods header, a different error occurs: reason: invalid token ‘xyz' in cors header ‘access-control-allow-methods’. ...
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
reason reason: expected ‘true’ in cors header ‘access-control-allow-credentials’ what went wrong? the cors request requires that the server permit the use of credentials, but the server's access-control-allow-credentials header's value isn't set to true to enable their use. to fix this problem on the client side, revise the code to not request the use of credentials. if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true. if using server-sent events, make sure eventsource.withcredentials is false (it's the default value). if using the fetch api, make sure request.credentials is "omit". to eliminate this error by changing the server's configuration, adjust the server's configuration to set the access-control-allow-credential...
Reason: CORS header ‘Origin’ cannot be added - HTTP
...
Reason: CORS preflight channel did not succeed - HTTP
the preflight request simply suffered any kind of networking error that might ordinarily occur. ...
CORS errors - HTTP
Web › HTTP › CORS › Errors
on error message. it will probably look like this: the text of the error message will be something similar to the following: cross-origin request blocked: the same origin policy disallows reading the remote resource at https://some-url-here. (reason: additional information here). note: for security reasons, specifics about what went wrong with a cors request are not available to javascript code. all the code knows is that an error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. cors error messages firefox's console displays messages in its console when requests fail due to cors. part of the error text is a "reason" message that provides added insight into what went wrong. the reason messages are listed below; click th...
HTTP caching - HTTP
Web › HTTP › Caching
ull response is downloaded each and every time. cache-control: no-store cache but revalidate a cache will send the request to the origin server for validation before releasing a cached copy. cache-control: no-cache private and public caches the "public" directive indicates that the response may be cached by any cache. this can be useful if pages with http authentication, or response status codes that aren't normally cacheable, should now be cached. on the other hand, "private" indicates that the response is intended for a single user only and must not be stored by a shared cache. a private browser cache may store the response in this case. cache-control: private cache-control: public expiration the most important directive here is "max-age=<seconds>" which is the maximum amount of ...
Content negotiation - HTTP
and there are several ways of negotiating between the client and the server. the determination of the best suited representation is made through one of two mechanisms: specific http headers by the client (server-driven negotiation or proactive negotiation), which is the standard way of negotiating a specific kind of resource. the 300 (multiple choices) or 406 (not acceptable) http response codes by the server (agent-driven negotiation or reactive negotiation), that are used as fallback mechanisms. over the years, other content negotiation proposals, like transparent content negotiation and the alternates header, have been proposed. they failed to get traction and got abandoned. server-driven content negotiation in server-driven content negotiation, or proactive content negotiation, ...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
de requirements such as: notifying users that your site uses cookies. allowing users to opt out of receiving some or all cookies. allowing users to use the bulk of your service without receiving cookies. there may be other regulations governing the use of cookies in your locality. the burden is on you to know and comply with these regulations. there are companies that offer "cookie banner" code that helps you comply with these regulations. other ways to store information in the browser another approach to storing data in the browser is the web storage api. the window.sessionstorage and window.localstorage properties correspond to session and permanent cookies in duration, but have larger storage limits than cookies, and are never sent to a server. more structured and larger amounts of...
Feature Policy - HTTP
ut controls features instead of security behavior. the feature-policy header has now been renamed to permissions-policy in the spec, and this article will eventually be updated to reflect that change. in a nutshell feature policy provides a mechanism to explicitly declare what functionality is used (or not used), throughout your website. this allows you to lock in best practices, even as the codebase evolves over time — as well as to more safely compose third-party content — by limiting which features are available. with feature policy, you opt-in to a set of "policies" for the browser to enforce on specific features used throughout a website. these policies restrict what apis the site can access or modify the browser's default behavior for certain features. examples of what you can...
Accept-Charset - HTTP
es it, and informs the client of its choice within the content-type response header, usually in a charset= parameter. browsers usually don't send this header, as the default value for each resource is usually correct and transmitting it would allow fingerprinting. if the server cannot serve any character encoding from this request header, it can theoretically send back a 406 not acceptable error code. but for a better user experience, this is rarely done and the accept-charset header is ignored. in early versions of http/1.1, a default character encoding was defined: iso-8859-1. this is no longer recommended, and now each content-type may have its own default. utf-8 is now well-supported and the overwhelmingly preferred character encoding. to guarantee better privacy through less configura...
Accept-Language - HTTP
er never overrides an explicit decision. the content of the accept-language is often out of the control of the user (like when traveling and using an internet cafe in a different country); the user may also want to visit a page in another language than the locale of their user interface. if the server cannot serve any matching language, it can theoretically send back a 406 (not acceptable) error code. but, for a better user experience, this is rarely done and more common way is to ignore the accept-language header in this case. header type request header forbidden header name no cors-safelisted request header yes, with the additional restriction that values can only be 0-9, a-z, a-z, space or *,-.;=. syntax accept-language: <language> accept-langua...
Allow - HTTP
Web › HTTP › Headers › Allow
an empty allow header indicates that the resource allows no request methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax allow: <http-methods> directives <http-methods> the comma-separated list of allowed http request methods. ...
Authorization - HTTP
ives <type> authentication type. a common type is "basic". other types: iana registry of authentication schemes authentification for aws servers (aws4-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 n...
Content-Encoding - HTTP
the recommendation is to compress data as much as possible and therefore to use this field, but some types of resources, such as jpeg images, are already compressed. sometimes, using additional compression doesn't reduce payload size and can even make the payload longer. ...
Content-Language - HTTP
tag consists of a primary language subtag that identifies a broad family of related languages (e.g., "en" = english), which is optionally followed by a series of subtags that refine or narrow that language's range (e.g., "en-ca" = the variety of english as communicated in canada). note: language tags are formaly defined in rfc 5646, which rely on the iso 639 standard (quite often the iso 639-1 code list) for language codes to be used. examples indicating the language a document is written in the global lang attribute is used on html elements to indicate the language of an entire html document or parts of it. <html lang="de"> do not use this meta element like this for stating a document language: <!-- /!\ this is bad practice --> <meta http-equiv="content-language" content="de"> indi...
CSP: trusted-types - HTTP
the http content-security-policy (csp) trusted-types directive instructs user agents to restrict usage of known dom xss sinks to a predefined set of functions that only accept non-spoofable, typed values in place of strings. this allows authors to define rules guarding writing values to the dom and thus reducing the dom xss attack surface to small, isolated parts of the web application codebase, facilitating their monitoring and code review. this directive declares a white-list of trusted type policy names created with trustedtypes.createpolicy from trusted types api. syntax content-security-policy: trusted-types; content-security-policy: trusted-types <policyname>; content-security-policy: trusted-types <policyname> <policyname> 'allow-duplicates'; <domstring> any string can be a tr...
Content-Security-Policy-Report-Only - HTTP
he violation occurred. effective-directive the directive whose enforcement caused the violation. original-policy the original policy as specified by the content-security-policy-report-only http header. referrer the referrer of the document in which the violation occurred. script-sample the first 40 characters of the inline script, event handler, or style that caused the violation. status-code the http status code of the resource on which the global object was instantiated. violated-directive the name of the policy section that was violated. sample violation report let's consider a page located at http://example.com/signup.html. it uses the following policy, disallowing everything but stylesheets from cdn.example.com. content-security-policy-report-only: default-src 'none'; sty...
Content-Security-Policy - HTTP
src http://example.com/; script-src http://example.com/ examples example: disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) over https: // header content-security-policy: default-src https: // meta tag <meta http-equiv="content-security-policy" content="default-src https:"> example: pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and to disable plugins: content-security-policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none' example: do not implement the above policy yet; instead just report violations that would have occurred: content-security-policy-report-only: default-src https:; report-uri /csp-violation-report-endpoint/ see mozil...
Content-Type - HTTP
forbidden header name no cors-safelisted response header yes cors-safelisted request header yes, with the additional restriction that values can't contain a cors-unsafe request header byte: 0x00-0x1f (except 0x08 (tab)), "():<>?@[\]{}, and 0x7f (delete). it also needs to have a mime type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain. syntax content-type: text/html; charset=utf-8 content-type: multipart/form-data; boundary=something directives media-type the mime type of the resource or the data. charset the character encoding standard. boundary for multipart entities the boundary directive is required, which consists of 1 to 70 characters from a set of characters known t...
Date - HTTP
Web › HTTP › Headers › Date
<day> 2 digit day number, e.g. ...
Early-Data - HTTP
the early-data header is not set by the originator of the request (i.e., a browser). ...
Feature-Policy: geolocation - HTTP
by default, the geolocation api can be used within top-level documents and their same-origin child frames. ...
Feature-Policy - HTTP
ther the current document is allowed to use element.requestfullscreen(). when this policy is disabled, the returned promise rejects with a typeerror. geolocation controls whether the current document is allowed to use the geolocation interface. when this policy is disabled, calls to getcurrentposition() and watchposition() will cause those functions' callbacks to be invoked with a positionerror code of permission_denied. gyroscope controls whether the current document is allowed to gather information about the orientation of the device through the gyroscope interface. layout-animations controls whether the current document is allowed to show layout animations. legacy-image-formats controls whether the current document is allowed to display images in legacy formats. magnetometer ...
Host - HTTP
Web › HTTP › Headers › Host
the host request header specifies the host and port number of the server to which the request is being sent. if no port is included, the default port for the service requested (e.g., 443 for an https url, and 80 for an http url) is implied. a host header field must be sent in all http/1.1 request messages. a 400 (bad request) status code may be sent to any http/1.1 request message that lacks a host header field or that contains more than one. header type request header forbidden header name yes syntax host: <host>:<port> directives <host> the domain name of the server (for virtual hosting). <port> optional tcp port number on which the server is listening. examples host: developer.cdn.mozilla.net specifications specification title ...
If-None-Match - HTTP
quest conditional. for get and head methods, the server will send back the requested resource, with a 200 status, only if it doesn't have an etag matching the given ones. for other methods, the request will be processed only if the eventually existing resource's etag doesn't match any of the values listed. when the condition fails for get and head methods, then the server must return http status code 304 (not modified). for methods that apply server-side changes, the status code 412 (precondition failed) is used. note that the server generating a 304 response must generate any of the following header fields that would have been sent in a 200 (ok) response to the same request: cache-control, content-location, date, etag, expires, and vary. the comparison with the stored etag uses the weak com...
Location - HTTP
Web › HTTP › Headers › Location
d and of the kind of redirection: if 303 (see also) responses always lead to the use of a get method, 307 (temporary redirect) and 308 (permanent redirect) don't change the method used in the original request; 301 (permanent redirect) and 302 (found) doesn't change the method most of the time, though older user-agents may (so you basically don't know). all responses with one of these status codes send a location header. in cases of resource creation, it indicates the url to the newly created resource. location and content-location are different: location indicates the target of a redirection (or the url of a newly created resource), while content-location indicates the direct url to use to access the resource when content negotiation happened, without the need of further content negoti...
Proxy-Authorization - HTTP
eader forbidden header name no syntax proxy-authorization: <type> <credentials> directives <type> authentication type. a common type is "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, ...
Public-Key-Pins-Report-Only - HTTP
public key pinning article. header type response header forbidden header name no syntax public-key-pins-report-only: pin-sha256="<pin-value>"; max-age=<expire-time>; includesubdomains; report-uri="<uri>" directives pin-sha256="<pin-value>" the quoted string is the base64 encoded subject public key information (spki) fingerprint. it is possible to specify multiple pins for different public keys. some browsers might allow other hashing algorithms than sha-256 in the future. max-age=<expire-time> this directive is meaningless for the public-key-pins-report-only header, it will be ignored by user agents and the header will not be cached. includesubdomains optional if th...
Public-Key-Pins - HTTP
der instead. for more information, see the http public key pinning article. header type response header forbidden header name no syntax public-key-pins: pin-sha256="<pin-value>"; max-age=<expire-time>; includesubdomains; report-uri="<uri>" directives pin-sha256="<pin-value>" the quoted string is the base64 encoded subject public key information (spki) fingerprint. it is possible to specify multiple pins for different public keys. some browsers might allow other hashing algorithms than sha-256 in the future. max-age=<expire-time> the time, in seconds, that the browser should remember that this site is only to be accessed using one of the defined keys. includesubdomains optional if this optional paramet...
Range - HTTP
Web › HTTP › Headers › Range
ould return. several parts can be requested with one range header at once, and the server may send back these ranges in a multipart document. if the server sends back ranges, it uses the 206 partial content for the response. if the ranges are invalid, the server returns the 416 range not satisfiable error. the server can also ignore the range header and return the whole document with a 200 status code. header type request header forbidden header name no syntax range: <unit>=<range-start>- range: <unit>=<range-start>-<range-end> range: <unit>=<range-start>-<range-end>, <range-start>-<range-end> range: <unit>=<range-start>-<range-end>, <range-start>-<range-end>, <range-start>-<range-end> range: <unit>=-<suffix-length> directives <unit> the unit in which rang...
Sec-WebSocket-Accept - HTTP
m that server is willing to initiate a websocket connection. header type response header forbidden header name no syntax sec-websocket-accept: <hashed key> directives <hashed key> the server takes the value of the sec-websocket-key sent in the handshake request, appends 258eafa5-e914-47da-95ca-c5ab0dc85b11, takes sha-1 of the new value, and is then base64 encoded. examples sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo= specification specification title rfc 6455, section 11.3.3: sec-websocket-accept the websocket protocol ...
Set-Cookie - HTTP
the set-cookie http response header is used to send a cookie from the server to the user agent, so the user agent can send it back to the server later. to send multiple cookies, multiple set-cookie headers should be sent in the same response. browsers block frontend javascript code from accessing the set cookie header, as required by the fetch spec, which defines set-cookie as a forbidden response-header name that must be filtered out from any response exposed to frontend code. for more information, see the guide on http cookies. header type response header forbidden header name no forbidden response-header name yes syntax set-cookie: <cookie-name>=<cookie-value> set-cookie: <cookie-name>=<cookie-value>; expires=<date> set-cookie: <cookie-name>...
SourceMap - HTTP
header type response header forbidden header name no syntax sourcemap: <url> x-sourcemap: <url> (deprecated) directives <url> a relative (to the request url) or absolute url pointing to a source map file. ...
User-Agent - HTTP
services to different browsers is usually a bad idea. header type request header forbidden header name no syntax user-agent: <product> / <product-version> <comment> common format for web browsers: user-agent: mozilla/5.0 (<system-information>) <platform> (<platform-details>) <extensions> directives <product> a product identifier — its name or development codename. <product-version> version number of the product. <comment> zero or more comments containing more details; sub-product information, for example. firefox ua string for more on firefox- and gecko-based user agent strings, see the firefox user agent string reference. the ua string of firefox is broken down into 4 components: mozilla/5.0 (platform; rv:geckoversion) gecko/geckotrail firefo...
HTTP headers - HTTP
Web › HTTP › Headers
ure. signed-headers the signed-headers header field identifies an ordered list of response header fields to include in a signature. server-timing communicates one or more metrics and descriptions for the given request-response cycle. service-worker-allowed used to remove the path restriction by including this header in the response of the service worker script. sourcemap links generated code to a source map. upgrade the relevant rfc document for the upgrade header field is rfc 7230, section 6.7. the standard establishes rules for upgrading or changing to a different protocol on the current client, server, transport protocol connection. for example, this header standard allows a client to change from http 1.1 to http 2.0, assuming the server decides to acknowledge and implement the ...
DELETE - HTTP
Web › HTTP › Methods › DELETE
deletes the specified resource. request has body may successful response has body may safe no idempotent yes cacheable no allowed in html forms no syntax delete /file.html http/1.1 example request delete /file.html http/1.1 responses if a delete method is successfully applied, there are several response status codes possible: a 202 (accepted) status code if the action will likely succeed but has not yet been enacted. a 204 (no content) status code if the action has been enacted and no further information is to be supplied. a 200 (ok) status code if the action has been enacted and the response message includes a representation describing the status. http/1.1 200 ok date: wed, 21 oct 2015 07:28:00 gmt ...
An overview of HTTP - HTTP
Web › HTTP › Overview
veloper.mozilla.org), or the tcp port (here, 80). the version of the http protocol. optional headers that convey additional information for the servers. or a body, for some methods like post, similar to those in responses, which contain the resource sent. responses an example response: responses consist of the following elements: the version of the http protocol they follow. a status code, indicating if the request was successful, or not, and why. a status message, a non-authoritative short description of the status code. http headers, like those for requests. optionally, a body containing the fetched resource. apis based on http the most commonly used api based on http is the xmlhttprequest api, which can be used to exchange data between a user agent and a server. the moder...
Proxy Auto-Configuration (PAC) file - HTTP
the pac file is named proxy.pac command line: pactester -p ~/pacparser-master/tests/proxy.pac -u http://www.mozilla.org (passes the host parameter www.mozilla.org and the url parameter http://www.mozilla.org) isplainhostname...
HTTP resources and specifications - HTTP
agement mechanism defines cookies proposed standard draft spec cookie prefixes ietf draft draft spec same-site cookies ietf draft draft spec deprecate modification of 'secure' cookies from non-secure origins ietf draft rfc 2145 use and interpretation of http version numbers informational rfc 6585 additional http status codes proposed standard rfc 7538 the hypertext transfer protocol status code 308 (permanent redirect) proposed standard rfc 7725 an http status code to report legal obstacles on the standard track rfc 2397 the "data" url scheme proposed standard rfc 3986 uniform resource identifier (uri): generic syntax internet standard rfc 5988 ...
100 Continue - HTTP
Web › HTTP › Status › 100
the http 100 continue informational status response code indicates that everything so far is ok and that the client should continue with the request or ignore it if it is already finished. to have a server check the request's headers, a client must send expect: 100-continue as a header in its initial request and receive a 100 continue status code in response before sending the body. status 100 continue specifications specification title rfc 7231, section 6.2.1: 100 continue hypertext transfer protocol (http/1.1): semantics and content ...
101 Switching Protocols - HTTP
Web › HTTP › Status › 101
the server includes in this response an upgrade response header to indicate the protocol it switched to. the process is described in detail in the article protocol upgrade mechanism. status 101 switching protocols examples switching protocols might be used with websockets. ...
103 Early Hints - HTTP
Web › HTTP › Status › 103
syntax 103 early hints specifications specification status comments rfc 8297: 103 early hints ietf rfc initial definition browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. no compatibility data found. ...
200 OK - HTTP
Web › HTTP › Status › 200
a 200 response is cacheable by default. the meaning of a success depends on the http request method: get: the resource has been fetched and is transmitted in the message body. head: the entity headers are in the message body. post: the resource describing the result of the action is transmitted in the message body. trace: the message body contains the request message as received by the server. the successful result of a put or a delete is often not a 200 ok but a 204 no content (or a 201 created when the resource is uploaded for the first time). ...
201 Created - HTTP
Web › HTTP › Status › 201
the http 201 created success status response code indicates that the request has succeeded and has led to the creation of a resource. the new resource is effectively created before this response is sent back and the new resource is returned in the body of the message, its location being either the url of the request, or the content of the location header. the common use case of this status code is as the result of a post request. status 201 created specifications specification title rfc 7231, section 6.3.2: 201 created hypertext transfer protocol (http/1.1): semantics and content ...
202 Accepted - HTTP
Web › HTTP › Status › 202
the request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. 202 is non-committal, meaning that there is no way for the http to later send an asynchronous response indicating the outcome of processing the request. it is intended for cases where another process or server handles the request, or for batch processing. ...
203 Non-Authoritative Information - HTTP
Web › HTTP › Status › 203
the http 203 non-authoritative information response status indicates that the request was successful but the enclosed payload has been modified by a transforming proxy from that of the origin server's 200 (ok) response . the 203 response is similar to the value 214, meaning transformation applied, of the warning header code, which has the additional advantage of being applicable to responses with any status code. status 203 non-authoritative information specifications specification title rfc 7231, section 6.3.4: 203 non-authoritative information hypertext transfer protocol (http/1.1): semantics and content ...
204 No Content - HTTP
Web › HTTP › Status › 204
a 204 response is cacheable by default. an etag header is included in such a response. the common use case is to return 204 as a result of a put request, updating a resource, without changing the current content of the page displayed to the user. if the resource is created, 201 created is returned instead. if the page should be changed to the newly updated page, the 200 should be used instead. ...
206 Partial Content - HTTP
Web › HTTP › Status › 206
if there is only one range, the content-type of the whole response is set to the type of the document, and a content-range is provided. if several ranges are sent back, the content-type is set to multipart/byteranges and each fragment covers one range, with content-range and content-type describing it. ...
301 Moved Permanently - HTTP
Web › HTTP › Status › 301
the hypertext transfer protocol (http) 301 moved permanently redirect status response code indicates that the resource requested has been definitively moved to the url given by the location headers. a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the new url). even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents align with it - you can still find this type of bugged software out there. it is therefore recommended to use the 301 code only as a response for get or head methods and to use the 308 permanent redirect for post methods instead, as the method change is explicitly prohibited with this status. status 301 ...
302 Found - HTTP
Web › HTTP › Status › 302
the hypertext transfer protocol (http) 302 found redirect status response code indicates that the resource requested has been temporarily moved to the url given by the location header. a browser redirects to this page but search engines don't update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is not sent to the new url). even if the specification requires the method (and the body) not to be altered when the redirection is performed, not all user-agents conform here - you can still find this type of bugged software out there. it is therefore recommended to set the 302 code only as a response for get or head methods and to use 307 temporary redirect instead, as the method change is explicitly prohibited in that case. in the cases where you want the method use...
304 Not Modified - HTTP
Web › HTTP › Status › 304
it is an implicit redirection to a cached resource. this happens when the request method is safe, like a get or a head request, or when the request is conditional and uses a if-none-match or a if-modified-since header. the equivalent 200 ok response would have included the headers cache-control, content-location, date, etag, expires, and vary. many developer tools' network panels of browsers create extraneous requests leading to 304 responses, so that access to the local cache is visible to developers. ...
307 Temporary Redirect - HTTP
Web › HTTP › Status › 307
the method and the body of the original request are reused to perform the redirected request. in the cases where you want the method used to be changed to get, use 303 see other instead. this is useful when you want to give an answer to a put method that is not the uploaded resources, but a confirmation message (like "you successfully uploaded xyz"). the only difference between 307 and 302 is that 307 guarantees that the method and the body will not be changed when the redirected request is made. ...
400 Bad Request - HTTP
Web › HTTP › Status › 400
the client should not repeat this request without modification. ...
401 Unauthorized - HTTP
Web › HTTP › Status › 401
this status is sent with a www-authenticate header that contains information on how to authorize correctly. this status is similar to 403, but in this case, authentication is possible. ...
402 Payment Required - HTTP
Web › HTTP › Status › 402
originally it was created to enable digital cash or (micro) payment systems and would indicate that the requested content is not available until the client makes a payment. however, no standard use convention exists and different entities use it in different contexts. ...
403 Forbidden - HTTP
Web › HTTP › Status › 403
this status is similar to 401, but in this case, re-authenticating will make no difference. the access is permanently forbidden and tied to the application logic, such as insufficient rights to a resource. ...
404 Not Found - HTTP
Web › HTTP › Status › 404
the http 404 not found client error response code indicates that the server can't find the requested resource. links that lead to a 404 page are often called broken or dead links and can be subject to link rot. a 404 status code does not indicate whether the resource is temporarily or permanently missing. but if a resource is permanently removed, a 410 (gone) should be used instead of a 404 status. status 404 not found custom error pages many web sites customize the look of a 404 page to be more helpful to the user and provide guidance on what to do next. apache servers can be configured using an .htaccess file and a code snippet like the following example. errordocument 404 /notfound.html for an example of a custom 404 page, see mdn's 404 page. custom design is a good thing, in mode...
405 Method Not Allowed - HTTP
Web › HTTP › Status › 405
the server must generate an allow header field in a 405 response containing a list of the target resource's currently supported methods. ...
406 Not Acceptable - HTTP
Web › HTTP › Status › 406
the hypertext transfer protocol (http) 406 not acceptable client error response code indicates that the server cannot produce a response matching the list of acceptable values defined in the request's proactive content negotiation headers, and that the server is unwilling to supply a default representation. proactive content negotiation headers include: accept accept-charset accept-encoding accept-language in practice, this error is very rarely used. instead of responding using this error code, which would be cryptic for the end user and difficult to fix, servers ignore the relevant header and serve an actual page to the user. it is assumed that even if the user won't be completely happy, they will prefer this to an error code. if a server returns such an error status, the body of t...
407 Proxy Authentication Required - HTTP
Web › HTTP › Status › 407
this status is sent with a proxy-authenticate header that contains information on how to authorize correctly. ...
408 Request Timeout - HTTP
Web › HTTP › Status › 408
it is sent on an idle connection by some servers, even without any previous request by the client. a server should send the "close" connection header field in the response, since 408 implies that the server has decided to close the connection rather than continue waiting. this response is used much more since some browsers, like chrome, firefox 27+, and ie9, use http pre-connection mechanisms to speed up surfing. note: some servers merely shut down the connection without sending this message. ...
409 Conflict - HTTP
Web › HTTP › Status › 409
conflicts are most likely to occur in response to a put request. for example, you may get a 409 response when uploading a file which is older than the one already on the server resulting in a version control conflict. ...
411 Length Required - HTTP
Web › HTTP › Status › 411
note: by specification, when sending data in a series of chunks, the content-length header is omitted and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format. see transfer-encoding for more details. ...
412 Precondition Failed - HTTP
Web › HTTP › Status › 412
this happens with conditional requests on methods other than get or head when the condition defined by the if-unmodified-since or if-none-match headers is not fulfilled. in that case, the request, usually an upload or a modification of a resource, cannot be made and this error response is sent back. status 412 precondition failed examples etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" etag: w/"0815" avoiding mid-air collisions with the help of the etag and the if-match headers, you can detect mid-air edit collisions. ...
413 Payload Too Large - HTTP
Web › HTTP › Status › 413
the http 413 payload too large response status code indicates that the request entity is larger than limits defined by server; the server might close the connection or return a retry-after header field. status 413 payload too large specifications specification title rfc 7231, section 6.5.11: 413 payload too large hypertext transfer protocol (http/1.1): semantics and content ...
414 URI Too Long - HTTP
Web › HTTP › Status › 414
there are a few rare conditions when this might occur: when a client has improperly converted a post request to a get request with long query information, when the client has descended into a loop of redirection (for example, a redirected uri prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit potential security holes. ...
415 Unsupported Media Type - HTTP
Web › HTTP › Status › 415
the format problem might be due to the request's indicated content-type or content-encoding, or as a result of inspecting the data directly. ...
416 Range Not Satisfiable - HTTP
Web › HTTP › Status › 416
the most likely reason is that the document doesn't contain such ranges, or that the range header value, though syntactically correct, doesn't make sense. the 416 response message contains a content-range indicating an unsatisfied range (that is a '*') followed by a '/' and the current length of the resource. e.g. content-range: bytes */12777 faced with this error, browsers usually either abort the operation (for example, a download will be considered as non-resumable) or ask for the whole document again. ...
417 Expectation Failed - HTTP
Web › HTTP › Status › 417
see the expect header for more details. ...
422 Unprocessable Entity - HTTP
Web › HTTP › Status › 422
important: the client should not repeat this request without modification. ...
425 Too Early - HTTP
Web › HTTP › Status › 425
the hypertext transfer protocol (http) 425 too early response status code indicates that the server is unwilling to risk processing a request that might be replayed, which creates the potential for a replay attack. status 425 too early specifications specification title rfc 8470, section 5.2: 425: early data using early data in http ...
426 Upgrade Required - HTTP
Web › HTTP › Status › 426
the server sends an upgrade header with this response to indicate the required protocol(s). ...
500 Internal Server Error - HTTP
Web › HTTP › Status › 500
the hypertext transfer protocol (http) 500 internal server error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. this error response is a generic "catch-all" response. usually, this indicates the server cannot find a better 5xx error code to response. sometimes, server administrators log error responses like the 500 status code with more details about the request to prevent the error from happening again in the future. status 500 internal server error specifications specification title rfc 7231, section 6.6.1: 500 internal server error hypertext transfer protocol (http/1.1): semantics and content ...
501 Not Implemented - HTTP
Web › HTTP › Status › 501
this status can also send a retry-after header, telling the requester when to check back to see if the functionality is supported by then. 501 is the appropriate response when the server does not recognize the request method and is incapable of supporting it for any resource. the only methods that servers are required to support (and therefore that must not return 501) are get and head. if the server does recognize the method, but intentionally does not support it, the appropriate response is 405 method not allowed. ...
502 Bad Gateway - HTTP
Web › HTTP › Status › 502
note: a gateway might refer to different things in networking and a 502 error is usually not something you can fix, but requires a fix by the web server or the proxies you are trying to get access through. ...
503 Service Unavailable - HTTP
Web › HTTP › Status › 503
common causes are a server that is down for maintenance or that is overloaded. this response should be used for temporary conditions and the retry-after http header should, if possible, contain the estimated time for the recovery of the service. note: together with this response, a user-friendly page explaining the problem should be sent. caching-related headers that are sent along with this response should be taken care of, as a 503 status is often a temporary condition and responses shouldn't usually be cached. ...
504 Gateway Timeout - HTTP
Web › HTTP › Status › 504
note: a gateway might refer to different things in networking and a 504 error is usually not something you can fix, but requires a fix by the web server or the proxies you are trying to get access through. ...
505 HTTP Version Not Supported - HTTP
Web › HTTP › Status › 505
the hypertext transfer protocol (http) 505 http version not supported response status code indicates that the http version used in the request is not supported by the server. status 505 http version not supported specifications specification title rfc 7231, section 6.6.6: 505 http version not supported hypertext transfer protocol (http/1.1): semantics and content ...
506 Variant Also Negotiates - HTTP
Web › HTTP › Status › 506
the hypertext transfer protocol (http) 506 variant also negotiates response status code may be given in the context of transparent content negotiation (see rfc 2295). this protocol enables a client to retrieve the best variant of a given resource, where the server supports multiple variants. the variant also negotiates status code indicates an internal server configuration error in which the chosen variant is itself configured to engage in content negotiation, so is not a proper negotiation endpoint. status 506 variant also negotiates specifications specification title rfc 2295, section 8.1: 506 variant also negotiates transparent content negotiation in http ...
507 Insufficient Storage - HTTP
Web › HTTP › Status › 507
it indicates that a method could not be performed because the server cannot store the representation needed to successfully complete the request. ...
508 Loop Detected - HTTP
Web › HTTP › Status › 508
it indicates that the server terminated an operation because it encountered an infinite loop while processing a request with "depth: infinity". this status indicates that the entire operation failed. ...
510 Not Extended - HTTP
Web › HTTP › Status › 510
the hypertext transfer protocol (http) 510 not extended response status code is sent in the context of the http extension framework, defined in rfc 2774. in that specification a client may send a request that contains an extension declaration, that describes the extension to be used. if the server receives such a request, but any described extensions are not supported for the request, then the server responds with the 510 status code. status 510 not extended specifications specification title rfc 2774, section 7: 510 not extended an http extension framework ...
HTTP
Web › HTTP
server or the client. custom proprietary headers can be added using the x- prefix; others in an iana registry, whose original content was defined in rfc 4229. iana also maintains a registry of proposed new http message headers. http request methods the different operations that can be done with http: get, post, and also less common requests like options, delete, or trace. http status response codes http response codes indicate whether a specific http request has been successfully completed. responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors. csp directives the content-security-policy response header fields allows web site administrators to control resources the user agent is allowed to load for a given...
Equality comparisons and sameness - JavaScript
ate to true, generally it is easier to special-case the nan checks (using the isnan method available from previous versions of ecmascript) than it is to work out how surrounding computations might affect the sign of any zeros you encounter in your comparison. here's a non-exhaustive list of built-in methods and operators that might cause a distinction between -0 and +0 to manifest itself in your code: - (unary negation) let stoppingforce = obj.mass * -obj.velocity; if obj.velocity is 0 (or computes to 0), a -0 is introduced at that place and propogates out into stoppingforce. math.atan2 math.ceil math.pow math.round in some cases,it's possible for a -0 to be introduced into an expression as a return value of these methods even when no -0 exists as one of the parameters. for ...
Meta programming - JavaScript
pply function in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). ...
Groups and ranges - JavaScript
, yes sir!". \k is used literally here to indicate the beginning of a back reference to a named capture group. (?<name>x) named capturing group: matches "x" and stores it on the groups property of the returned matches under the name specified by <name>. the angle brackets (< and >) are required for group name. for example, to extract the united states area code from a phone number, we could use /\((?<area>\d\d\d)\)/. the resulting number would appear under matches.groups.area. (?:x) non-capturing group: matches "x" but does not remember the match. the matched substring cannot be recalled from the resulting array's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9). examples counting vowels v...
Quantifiers - JavaScript
characters meaning x* matches the preceding item "x" 0 or more times. ...
JavaScript technologies overview - JavaScript
e syntax (parsing rules, keywords, control flow, object literal initialization, ...) error handling mechanisms (throw, try...catch, ability to create user-defined error types) types (boolean, number, string, function, object, ...) the global object. in a browser, this global object is the window object, but ecmascript only defines the apis not specific to browsers, e.g. parseint, parsefloat, decodeuri, encodeuri... a prototype-based inheritance mechanism built-in objects and functions (json, math, array.prototype methods, object introspection methods, etc.) strict mode browser support as of october 2016, the current versions of the major web browsers implement ecmascript 5.1 and ecmascript 2015, but older versions (still in use) implement ecmascript 5 only. future the major 6th edit...
JavaScript language resources - JavaScript
is a dynamic name that refers to whatever the next version is at the time of‍ writing. es.next features are more correctly called proposals, because, by definition, the specification has not been finalized yet. see wikipedia ecmascript entry for more information on ecmascript history. you can participate in or just track the work on the next revisions of the ecmascript language specification, code-named "harmony", and the ecmascript internationalization api specification via public wiki and the es-discuss mailing list linked from ecmascript.org. implementations spidermonkey - the javascript engine used in various mozilla products, including firefox; rhino - the javascript engine is written in java; tamarin - the actionscript virtual machine (used in the adobe® flash® player); othe...
About the JavaScript reference - JavaScript
if you're learning javascript, or need help understanding some of its capabilities or features, check out the javascript guide. the javascript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. for the most part, this reference attempts to be environment-agnostic and does not target a web browser environment. ...
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
message warning: -file- is being assigned a //# sourcemappingurl, but already has one. error type a warning. javascript execution won't be halted. what went wrong? a source map has been specified more than once for a given javascript source. javascript sources are often combined and minified to make delivering them from the server more efficient. with source maps, the debugger can map the code being executed to the original source files. there are two ways to assign a source map, either by using a comment or by setting a header to the javascript file. examples setting source maps setting a source map by using a comment in the file: //# sourcemappingurl=http://example.com/path/to/your/sourcemap.map or, alternatively, you can set a header to your javascript file: x-sourcemap: /path...
SyntaxError: return not in function - JavaScript
be in a function, because they end (or pause and resume) function execution and specify a value to be returned to the function caller. examples missing curly brackets var cheer = function(score) { if (score === 147) return 'maximum!'; }; if (score > 100) { return 'century!'; } } // syntaxerror: return not in function the curly brackets look correct at a first glance, but this code snippet is missing a { after the first if statement. correct would be: var cheer = function(score) { if (score === 147) { return 'maximum!'; } if (score > 100) { return 'century!'; } }; ...
TypeError: can't assign to property "x" on "y": not an object - JavaScript
roperty. the problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a string or a number is expected. examples invalid cases 'use strict'; var foo = "my string"; // the following line does nothing if not in strict mode. foo.bar = {}; // typeerror: can't assign to property "bar" on "my string": not an object fixing the issue either fix the code to prevent the primitive from being used in such places, or fix the issue is to create the object equivalent object. 'use strict'; var foo = new string("my string"); foo.bar = {}; ...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
fox) typeerror: cannot delete property 'x' of #<object> (chrome) error type typeerror in strict mode only. what went wrong? it was attempted to delete a property, but that property is non-configurable. the configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed. this error happens only in strict mode code. in non-strict code, the operation returns false. examples attempting to delete non-configurable properties non-configurable properties are not super common, but they can be created using object.defineproperty() or object.freeze(). 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); delete obj.score; // typeerror 'use strict'; var obj = {}; object.defineproperty(obj, 'foo', {...
TypeError: can't redefine non-configurable property "x" - JavaScript
ject.defineproperty() creates non-configurable properties if you haven't specified them as configurable. var obj = object.create({}); object.defineproperty(obj, "foo", {value: "bar"}); object.defineproperty(obj, "foo", {value: "baz"}); // typeerror: can't redefine non-configurable property "foo" you will need to set the "foo" property to configurable, if you intend to redefine it later in the code. var obj = object.create({}); object.defineproperty(obj, "foo", {value: "bar", configurable: true}); object.defineproperty(obj, "foo", {value: "baz", configurable: true}); ...
TypeError: can't access dead object - JavaScript
ce to a dom element that persists even after it was destroyed in the dom. to avoid these issues, references to dom nodes in foreign document should instead be stored in an object which is specific to that document, and cleaned up when the document is unloaded, or stored as weak references. examples checking if an object is dead components.utils offers a isdeadwrapper() method, which privileged code might use. if (components.utils.isdeadwrapper(window)) { // dead } unprivileged code has no access to component.utils and might just be able catch the exception. try { string(window); } catch (e) { console.log("window is likely dead"); } ...
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
lete operator can only delete properties on an object. object properties are "qualified" if they are configurable. unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. memory management is done indirectly via breaking references, see the memory management page and the delete operator page for more details. this error only happens in strict mode code. in non-strict code, the operation just returns false. examples freeing the contents of a variable attempting to delete a plain variable, doesn't work in javascript and it throws an error in strict mode: 'use strict'; var x; // ... delete x; // syntaxerror: applying the 'delete' operator to an unqualified name // is deprecated to free the contents of a variable, you can set it to null: ...
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
ng //@ to indicate sourcemappingurl pragmas is deprecated. use //# instead error type a warning that a syntaxerror occurred. javascript execution won't be halted. what went wrong? there is a deprecated source map syntax in a javascript source. javascript sources are often combined and minified to make delivering them from the server more efficient. with source maps, the debugger can map the code being executed to the original source files. the source map specification changed the syntax due to a conflict with ie whenever it was found in the page after //@cc_on was interpreted to turn on conditional compilation in the ie jscript engine. the conditional compilation comment in ie is a little known feature, but it broke source maps with jquery and other libraries. examples deprecated synt...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
? there was an assignment (=) when you would normally expect a test for equality (==). to help debugging, javascript (with strict warnings enabled) warns about this pattern. examples assignment within conditional expressions it is advisable to not use simple assignments in a conditional expression (such as if...else), because the assignment can be confused with equality when glancing over the code. for example, do not use the following code: if (x = y) { // do the right thing } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. for example: if ((x = y)) { // do the right thing } otherwise, you probably meant to use a comparison operator (e.g. == or ===): if (x == y) { // do the right thing } ...
SyntaxError: identifier starts immediately after numeric literal - JavaScript
digit. identifiers can only start with a letter, underscore (_), or dollar sign ($). message syntaxerror: unexpected identifier after numeric literal (edge) syntaxerror: identifier starts immediately after numeric literal (firefox) syntaxerror: unexpected number (chrome) error type syntaxerror what went wrong? the names of variables, called identifiers, conform to certain rules, which your code must adhere to! a javascript identifier must start with a letter, underscore (_), or dollar sign ($). they can't start with a digit! only subsequent characters can be digits (0-9). examples variable names starting with numeric literals variable names can't start with numbers in javascript. the following fails: var 1life = 'foo'; // syntaxerror: identifier starts immediately after numeric lit...
SyntaxError: JSON.parse: bad parsing - JavaScript
the javascript exceptions thrown by json.parse() occur when string failed to be parsed as json. ...
SyntaxError: Malformed formal parameter - JavaScript
the javascript exception "malformed formal parameter" occurs when the argument list of a function() constructor call is invalid somehow. message syntaxerror: expected {x} (edge) syntaxerror: malformed formal parameter (firefox) error type syntaxerror what went wrong? there is a function() constructor with at least two arguments passed in the code. the last argument is the source code for the new function you're creating. all the rest make up your new function's argument list. the argument list is invalid somehow. perhaps you accidentally picked a keyword like if or var as an argument name, or perhaps there's some stray punctuation in your argument list. or maybe you accidentally passed an invalid value, like a number or object. ok, that fixed my problem. but why didn't you say that i...
SyntaxError: missing : after property id - JavaScript
properties. somehow, this colon is missing or misplaced. message syntaxerror: expected ':' (edge) syntaxerror: missing : after property id (firefox) error type syntaxerror what went wrong? when creating objects with the object initializer syntax, a colon (:) separates keys and values for the object's properties. var obj = { propertykey: 'value' }; examples colons vs. equal signs this code fails, as the equal sign can't be used this way in this object initializer syntax. var obj = { propertykey = 'value' }; // syntaxerror: missing : after property id correct would be to use a colon, or to use square brackets to assign a new property after the object has been created already. var obj = { propertykey: 'value' }; // or alternatively var obj = { }; obj['propertykey'] = 'value'; ...
SyntaxError: missing formal parameter - JavaScript
calling functions are two separate steps. declarations require identifier as parameters, and only when calling (invoking) the function, you provide the values the function should use. in javascript, identifiers can contain only alphanumeric characters (or "$" or "_"), and may not start with a digit. an identifier differs from a string in that a string is data, while an identifier is part of the code. examples provide proper function parameters function parameters must be identifiers when setting up a function. all these function declarations fail, as they are providing values for their parameters: function square(3) { return number * number; }; // syntaxerror: missing formal parameter function greet("howdy") { return greeting; }; // syntaxerror: missing formal parameter function lo...
SyntaxError: missing name after . operator - JavaScript
se see the examples below. examples property access property accessors in javascript use either the dot (.) or square brackets ([]), but not both. square brackets allow computed property access. var obj = { foo: { bar: "baz", bar2: "baz2" } }; var i = 2; obj.[foo].[bar] // syntaxerror: missing name after . operator obj.foo."bar"+i; // syntaxerror: missing name after . operator to fix this code, you need to access the object like this: obj.foo.bar; // "baz" // or alternatively obj["foo"]["bar"]; // "baz" // computed properties require square brackets obj.foo["bar" + i]; // "baz2" property access vs. concatenation if you are coming from another programming language (like php), it is also easy to mix up the dot operator (.) and the concatenation operator (+). console.log("hello" . "...
SyntaxError: missing ; before statement - JavaScript
the javascript exception "missing ; before statement" occurs when there is a semicolon (;) missing somewhere and can't be added by automatic semicolon insertion (asi). you need to provide a semicolon, so that javascript can parse the source code correctly. message syntaxerror: expected ';' (edge) syntaxerror: missing ; before statement (firefox) error type syntaxerror. what went wrong? there is a semicolon (;) missing somewhere. javascript statements must be terminated with semicolons. some of them are affected by automatic semicolon insertion (asi), but in this case you need to provide a semicolon, so that javascript can parse the source code correctly. however, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. yo...
SyntaxError: missing variable name - JavaScript
probably a comma is wrong somewhere or you struggled with coming up with a name. ...
ReferenceError: "x" is not defined - JavaScript
defined error type referenceerror. what went wrong? there is a non-existent variable referenced somewhere. this variable needs to be declared, or you need to make sure it is available in your current script or scope. note: when loading a library (such as jquery), make sure it is loaded before you access library variables, such as "$". put the <script> tag that loads the library before your code that uses it. examples variable not declared foo.substring(1); // referenceerror: foo is not defined the "foo" variable isn't defined anywhere. it needs to be some string, so that the string.prototype.substring() method will work. var foo = 'bar'; foo.substring(1); // "ar" wrong scope a variable needs to be available in the current context of execution. variables defined inside a functio...
TypeError: "x" is read-only - JavaScript
ror: 0 is read-only (firefox) typeerror: cannot assign to read only property 'x' of #<object> (chrome) typeerror: cannot assign to read only property '0' of [object array] (chrome) error type typeerror what went wrong? the global variable or object property that was assigned to is a read-only property. (technically, it is a non-writable data property.) this error happens only in strict mode code. in non-strict code, the assignment is silently ignored. examples invalid cases read-only properties are not super common, but they can be created using object.defineproperty() or object.freeze(). 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); obj.score = 0; // typeerror 'use strict'; object.defineproperty(this, 'lung_count', {value: 2, writable: false}); lung_count = 3;...
SyntaxError: "x" is a reserved identifier - JavaScript
e of a future reserved word for an identifier is invalid (edge) syntaxerror: "x" is a reserved identifier (firefox) syntaxerror: unexpected reserved word (chrome) error type syntaxerror what went wrong? reserved keywords will throw in if they are used as identifiers. these are reserved in strict mode and sloppy mode: enum the following are only reserved when they are found in strict mode code: implements interface let package private protected public static examples strict and non-strict reserved keywords the enum identifier is generally reserved. var enum = { red: 0, green: 1, blue: 2 }; // syntaxerror: enum is a reserved identifier in strict mode code, more identifiers are reserved. "use strict"; var package = ["potatoes", "rice", "fries"]; // syntaxerror: package ...
InternalError: too much recursion - JavaScript
error: out of stack space (edge) internalerror: too much recursion (firefox) rangeerror: maximum call stack size exceeded (chrome) error type internalerror. what went wrong? a function that calls itself is called a recursive function. once a condition is met, the function stops calling itself. this is called a base case. in some ways, recursion is analogous to a loop. both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). when there are too many function calls, or a function is missing a base case, javascript will throw this error. examples this recursive function runs 10 times, as per the exit condition. function loop(x) { if (x >= 10) // "x >= 10" is the exit condition return; // do st...
SyntaxError: function statement requires a name - JavaScript
the javascript exception "function statement requires a name" occurs when there is a function statement in the code that requires a name. message syntax error: expected identifier (edge) syntaxerror: function statement requires a name [firefox] syntaxerror: unexpected token ( [chrome] error type syntaxerror what went wrong? there is a function statement in the code that requires a name. you'll need to check how functions are defined and if you need to provide a name for it, or if the function in question needs to be a function expression, an iife, or if the function code is placed correctly in this context at all. examples statements vs expressions a function statement (or function declaration) requires a name, this won't work: function () { return 'hello world'; } // syntaxerror...
TypeError: variable "x" redeclares argument - JavaScript
a function body again. message typeerror: variable "x" redeclares argument (firefox) error type typeerror warning in strict mode only. what went wrong? the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again. this might be a naming conflict and thus javascript warns about it. this error occurs as a warning in strict mode code only. in non-strict code, the redeclaration is silently ignored. examples invalid cases in this case, the variable "arg" redeclares the argument. 'use strict'; function f(arg) { var arg = 'foo'; } valid cases to fix this warning, the var statement can just be omitted, because the variable exists already. in other cases, you might to rename either the function parameter or the variable n...
Method definitions - JavaScript
sync* generator( parameters… ) {}, // with computed keys get [property]() {}, set [property](value) {}, [property]( parameters… ) {}, *[generator]( parameters… ) {}, async [property]( parameters… ) {}, async* [generator]( parameters… ) {}, }; description the shorthand syntax is similar to the getter and setter syntax introduced in ecmascript 2015. given the following code: const obj = { foo: function() { // ... }, bar: function() { // ... } } you are now able to shorten this to: const obj = { foo() { // ... }, bar() { // ... } } generator methods generator methods can be defined using the shorthand syntax as well. when doing so: the asterisk (*) in the shorthand syntax must be before the generator property name. (that is...
getter - JavaScript
you desire this behavior. in the following example, the object has a getter as its own property. on getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. finally, the value gets returned. get notifier() { delete this.notifier; return this.notifier = document.getelementbyid('bookmarked-notification-anchor'); }, for firefox code, see also the xpcomutils.jsm code module, which defines the definelazygetter() function. get vs. defineproperty while using the get keyword and object.defineproperty() have similar results, there is a subtle difference between the two when used on classes. when using get the property will be defined on the instance's prototype, while using object.defineproperty() the property will be defined o...
Rest parameters - JavaScript
ntains all arguments passed to the function; the arguments object is not a real array, while rest parameters are array instances, meaning methods like sort, map, foreach or pop can be applied on it directly; the arguments object has additional functionality specific to itself (like the callee property). ...
Array.prototype[@@unscopables] - JavaScript
pywithin() entries() fill() find() findindex() includes() keys() values() see symbol.unscopables for how to set unscopables for your own objects. property attributes of array.prototype[@@unscopables] writable no enumerable no configurable yes examples use in with environments the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environments, "keys" would now be the method and not the variable. this is where now the built-in @@unscopables array.prototype[@@unscopables] symbol property comes into play and prevents that some of the array methods are being scoped into the with sta...
Array.prototype.reduceRight() - JavaScript
fourth call 19 1 1 [0, 1, 2, 3, 4] 20 fifth call 20 0 0 [0, 1, 2, 3, 4] 20 the value returned by reduceright this time would be, of course, 20. polyfill reduceright was added to the ecma-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of reduceright in implementations which do not natively support it. // production steps of ecma-262, edition 5, 15.4.4.22 // reference: http://es5.github.io/#x15.4.4.22 if ('function' !== typeof array.prototype.reduceright) { array.prototype.reduceright = function(callback /*, initialvalue*/) { 'use strict'; if (null === this || 'undefined...
Array.prototype.every() - JavaScript
visited. every acts like the "for all" quantifier in mathematics. in particular, for an empty array, it returns true. (it is vacuously true that all elements of the empty set satisfy any given condition.) polyfill every was added to the ecma-262 standard in the 5th edition, and it may not be present in other implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values, and that callbackfn.call evaluates to the original value of function.prototype.call. if (!array.prototype.every) { array.prototype.every = function(callbackfn...
Array.prototype.filter() - JavaScript
h are appended to the array (from callback) after the call to filter() begins will not be visited by callback. if existing elements of the array are deleted in the same way they will not be visited. polyfill filter() was added to the ecma-262 standard in the 5th edition. therefore, it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of filter() in ecma-262 implementations which do not natively support it. this algorithm is exactly equivalent to the one specified in ecma-262, 5th edition, assuming that fn.call evaluates to the original value of function.prototype.bind(), and that array.prototype.push() has its original value. if (!array.prototype.filter){ array.prototype.filte...
Array.prototype.indexOf() - JavaScript
und. description indexof() compares searchelement to elements of the array using strict equality (the same method used by the === or triple-equals operator). note: for the string method, see string.prototype.indexof(). polyfill indexof() was added to the ecma-262 standard in the 5th edition; as such it may not be present in all browsers. you can work around this by utilizing the following code at the beginning of your scripts. this will allow you to use indexof() when there is still no native support. this algorithm matches the one specified in ecma-262, 5th edition, assuming typeerror and math.abs() have their original values. // this version tries to optimize by only checking for "in" when looking for undefined and // skipping the definitely fruitless nan search. other parts are mer...
Array.isArray() - JavaScript
ameters value the value to be checked. return value true if the value is an array; otherwise, false. description if the value is an array, true is returned; otherwise, false is. see the article “determining with absolute accuracy whether or not a javascript object is an array” for more details. given a typedarray instance, false is always returned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); arr...
Array.of() - JavaScript
ay of 7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array. return value a new array instance. description this function is part of the ecmascript 2015 standard. for more information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available. if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(und...
Array.prototype.push() - JavaScript
y cannot be converted into a number, the index used is 0. this includes the possibility of length being nonexistent, in which case length will also be created. although strings are native, array-like objects, they are not suitable in applications of this method, as strings are immutable. similarly for the native, array-like object arguments. examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it. the total variable contains the new length of the array. let sports = ['soccer', 'baseball'] let total = sports.push('football', 'swimming') console.log(sports) // ['soccer', 'baseball', 'football', 'swimming'] console.log(total) // 4 merging two arrays this example uses apply() to push all elements from a ...
Array.prototype.shift() - JavaScript
eric; this method can be called or applied to objects resembling arrays. objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner. array.prototype.pop() has similar behavior to shift, but applied to the last element in an array. examples removing an element from an array the following code displays the myfish array before and after removing its first element. it also displays the removed element: var myfish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myfish before:', json.stringify(myfish)); // myfish before: ['angel', 'clown', 'mandarin', 'surgeon'] var shifted = myfish.shift(); console.log('myfish after:', myfish); // myfish after: ['clown', 'mandarin', 'surgeon...
Array.prototype.some() - JavaScript
ng callback will be the value at the time that some() visits that element's index. elements that are deleted are not visited. caution: calling this method on an empty array returns false for any condition! polyfill some() was added to the ecma-262 standard in the 5th edition, and it may not be present in all implementations of the standard. you can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. this algorithm is exactly the one specified in ecma-262, 5th edition, assuming object and typeerror have their original values and that fun.call evaluates to the original value of function.prototype.call(). // production steps of ecma-262, edition 5, 15.4.4.17 // reference: http://es5.g...
Boolean.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax booleanobj.tosource() boolean.tosource() return value a string representing the source code of the object. examples native function for the built-in boolean object, tosource returns the following string indicating that the source code is not available: function boolean() { [native code] } specifications not part of any standard. ...
Boolean.prototype.toString() - JavaScript
s a string representation of the object. javascript calls the tostring() method automatically when a boolean is to be represented as a text value or when a boolean is referred to in a string concatenation. for boolean objects and values, the built-in tostring() method returns the string "true" or "false" depending on the value of the boolean object. examples using tostring() in the following code, flag.tostring() returns "true": var flag = new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification. ...
Boolean.prototype.valueOf() - JavaScript
les project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax bool.valueof() return value the primitive value of the given boolean object description the valueof() method of boolean returns the primitive value of a boolean object or literal boolean as a boolean data type. this method is usually called internally by javascript and not explicitly in code. examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specification. ...
Boolean - JavaScript
o not confuse the primitive boolean values true and false with the true and false values of the boolean object. any object of which the value is not undefined or null, including a boolean object whose value is false, evaluates to true when passed to a conditional statement. for example, the condition in the following if statement evaluates to true: var x = new boolean(false); if (x) { // this code is executed } this behavior does not apply to boolean primitives. for example, the condition in the following if statement evaluates to false: var x = false; if (x) { // this code is not executed } do not use a boolean object to convert a non-boolean value to a boolean value. to perform this task, instead, use boolean as a function, or a double not operator: var x = boolean(expression); ...
Date.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax dateobj.tosource() date.tosource() return value a string representing the source code of the given date object. examples native function for the built-in date object, tosource() returns the following string indicating that the source code is not available: function date() { [native code] } specifications not part of any standard. ...
Date.prototype.valueOf() - JavaScript
er of milliseconds between 1 january 1970 00:00:00 utc and the given date. description the valueof() method returns the primitive value of a date object as a number data type, the number of milliseconds since midnight 01 january, 1970 utc. this method is functionally equivalent to the date.prototype.gettime() method. this method is usually called internally by javascript and not explicitly in code. examples using valueof() var x = new date(56, 6, 17); var myvar = x.valueof(); // assigns -424713600000 to myvar specifications specification ecmascript (ecma-262)the definition of 'date.prototype.valueof' in that specification. ...
Date - JavaScript
high-resolution time feature, performance.now() can provide more reliable and precise measurements of elapsed time than date.now(). get the number of seconds since the ecmascript epoch let seconds = math.floor(date.now() / 1000) in this case, it's important to return only an integer—so a simple division won't do. it's also important to only return actually elapsed seconds. (that's why this code uses math.floor(), and not math.round().) specifications specification ecmascript (ecma-262)the definition of 'date' in that specification. ...
Error() constructor - JavaScript
linenumber optional the value for the linenumber property on the created error object. ...
Error.prototype.fileName - JavaScript
the filename property contains the path to the file that raised this error. description this non-standard property contains the path to the file that raised this error. if called from a debugger context, the firefox developer tools for example, "debugger eval code" is returned. examples using filename var e = new error('could not parse input'); throw e; // e.filename could look like "file:///c:/example.html" specifications not part of any standard. ...
EvalError() constructor - JavaScript
the evalerror constructor creates a new error regarding the global eval() function. this exception is not thrown by javascript anymore, however the evalerror object remains for compatibility. syntax new evalerror([message[, filename[, linenumber]]]) parameters message optional. human-readable description of the error filename optional. the name of the file containing the code that caused the exception linenumber optional. the line number of the code that caused the exception examples evalerror is not used in the current ecmascript specification and will thus not be thrown by the runtime. however, the object itself remains for backwards compatibility with earlier versions of the specification. creating an evalerror try { throw new evalerror('hello', 'somefile.js', 10); } ca...
FinalizationRegistry - JavaScript
nt during execution, but those calls may be substantially after the related object was reclaimed. there are also situations where even implementations that normally call cleanup callbacks are unlikely to call them: when the javascript program shuts down entirely (for instance, closing a tab in a browser). when the finalizationregistry instance itself is no longer reachable by javascript code. examples creating a new registry you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // .... }); registering objects for cleanup then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it: registry.register(theobject, "some value"); specifica...
Function.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. this method is usually called internally by javascript and not explicitly in code. you can call tosource() while debugging to examine the contents of an object. syntax function.tosource(); return value a string representing the source code of the object. examples native functions for the built-in function object, tosource() returns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() returns the javascript source that defines the object as a string. // for example: function hello() { console.log("hello, world!"); } hello.tosource(); // results in: "function hello() { consol...
InternalError() constructor - JavaScript
the internalerror() constructor creates an error that indicates an error that occurred internally in the javascript engine. for example: "internalerror: too much recursion". syntax new internalerror([message[, filename[, linenumber]]]) parameters message optional. human-readable description of the error filename optional. the name of the file containing the code that caused the exception linenumber optional. the line number of the code that caused the exception examples creating a new internalerror new internalerror("engine failure"); specifications not part of any standard. ...
Intl.Collator - JavaScript
this is because the values are implementation-specific. that is, the specification requires only that the before and after values are negative and positive. using locales the results provided by collator.prototype.compare() vary between languages. in order to get the sort order of the language used in the user interface of your application, ...
Intl.DateTimeFormat() constructor - JavaScript
hub repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax new intl.datetimeformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings. to use the browser's default locale, omit this argument or pass undefined. unicode extension are supported (for example "en-us-u-ca-buddhist"). for the general form and interpretation of the locales argument, see the intl page. the following unicode extension keys are allowed: nu numbering system. possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya...
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
active-examples and send us a pull request. syntax datetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given datetimeformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. calendar e.g. "gregory" numberingsystem the values requested using the unicode extension keys "ca" and "nu" or filled in as default values. timezone the value provided for this property in the options argu...
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
the construction of the current listformat object. syntax listformat.resolvedoptions() return value an object with properties reflecting the locale and formatting options computed during the construction of the given listformat object. description the object returned by resolvedoptions() has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. style the value provided for this property in the options argument of the constructor or the default value ("long"). its value is either "long", "short", or "narrow". type the value provided for this propert...
Intl.Locale.prototype.baseName - JavaScript
le object represents a parsed local and options for that locale. the basename property returns basic, core information about the locale in the form of a substring of the complete data string. specifically, the property returns the substring containing the language, and the script and region if available. basename returns the language ["-" script] ["-" region] *("-" variant) subsequence of the unicode_language_id grammar. examples basic example let myloc = new intl.locale("fr-latn-ca"); // sets locale to canadian french console.log(myloc.tostring()); // prints out "fr-latn-ca-u-ca-gregory" console.log(myloc.basename); // prints out "fr-latn-ca" example with options in the input string // sets language to japanese, region to japan, // calendar to gregorian, hour cycle to 24 hours let japa...
Intl.Locale.prototype.caseFirst - JavaScript
first property. there are 3 values that the casefirst property can have, outlined in the table below. casefirst values value description upper upper case to be sorted before lower case. lower lower case to be sorted before upper case. false no special case ordering. examples setting the casefirst value via the locale string in the unicode locale string spec, the values that casefirst represents correspond to the key kf. kf is treated as a locale string "extension subtag". these subtags add additional data about the locale, and are added to locale identifiers by using the -u extension key. thus, the casefirst value can be added to the inital locale identifier string that is passed into the locale constructor. to add the casefirst v...
Intl.Locale.prototype.hourCycle - JavaScript
h11 hour system using 0–11; corresponds to 'k' in patterns. the 12 hour clock, with midnight starting at 0:00 am. h24 hour system using 1–24; corresponds to 'k' in pattern. the 24 hour clock, with midnight starting at 24:00. examples these examples will show you how to add hour cycle data to your locale object. adding an hour cycle via the locale string in the unicode locale string spec, the hour cycle is a locale string "extension subtag". these subtags add additional data about the locale, and are added to locale identifiers by using the -u extension key. thus, the hour cycle type can be added to the inital locale identifier string that is passed into the locale constructor. to add the hour cycle type, first add the -u extension key to the string. next, add ...
Intl.Locale.prototype.numeric - JavaScript
be no special handling of numeric values in strings. if numeric is set to true, then the locale will take numeric characters into account when collating strings. this special numeric handling means that sequences of decimal digits will be compared as numbers. for example, the string "a-21" will be considered less than "a-123". examples setting the numeric value via the locale string in the unicode locale string spec, the values that numeric represents correspond to the key kn. kn is considered a locale string "extension subtag". these subtags add additional data about the locale, and are added to locale identifiers by using the -u extension key. thus, the numeric value can be added to the inital locale identifier string that is passed into the locale constructor. to set the numeric value, ...
Intl.Locale.prototype.region - JavaScript
but there are differences in spelling and other language conventions between those two countries. knowing the locale's region helps javascript programmers make sure that the content from their sites and applications is correctly displayed when viewed from different areas of the world. examples setting the region in the locale identifer string argument the region is the third part of a valid unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the locale constructor. the region is a mandatory part of a let regionstr = new intl.locale("en-latn-us"); console.log(regionstr.region); // prints "us" setting the region via the configuration object the locale constructor takes a configuration object, which can be used to set the regi...
Intl.Locale.prototype.script - JavaScript
age. for instance, the script associated with english is latin, whereas the script typically associated with korean is hangul. in many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. there are exceptions to this rule, however, and it is important to indicate the script whenever possible, in order to have a complete unicode language identifier. examples setting the script in the locale identifer string argument the script is the second part of a valid unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the locale constructor. note that the script is not a required part of a locale identifier. let scriptstr = new intl.locale("en-latn-us"); console.l...
Intl.Locale.prototype.toString() - JavaScript
the intl.locale.prototype.tostring() returns the locale's full locale identifier string. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax locale.tostring() return value the locale's unicode locale identifier string. description the locale object is a javascript representation of a concept unicode locale identifier. information about a particular locale (language, script, calendar type, etc.) can be encoded in a locale identifier string. to make it easier to work with these locale identifiers, the locale object was introduced to javascript. calling the tostring method on a locale object will return the ide...
Intl.Locale - JavaScript
the intl.locale object is a standard built-in property of the intl object that represents a unicode locale identifier. description the intl.locale object was created to allow for easier manipulation of unicode locales. unicode represents locales with a string, called a locale identifier. the locale identifier consists of a language identifier and extension tags. language identifiers are the core of the locale, consisting of language, script, and region subtags. additional information about the locale is stored in the optional extension tags. extension tags hold information about locale aspects such as calendar type, clock type, and numbering system type. traditionally, the intl api used strings to represent locales, just as unicode does. this is a simple and lightweight solution that wor...
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
m/mdn/interactive-examples and send us a pull request. syntax numberformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given numberformat object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. numberingsystem the value provided for this properties in the options argument, if present, or the value requested using the unicode extension key "nu" or filled in as a default. notation the value provided ...
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
omputed during initialization of this pluralrules object. syntax pluralrule.resolvedoptions() return value a new object with properties reflecting the locale and plural formatting options computed during the initialization of the given pluralrules object. description the resulting object has the following properties: locale the bcp 47 language tag for the locale actually used. if any unicode extension values were requested in the input bcp 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in locale. pluralcategories an array of plural categories used by the given locale, seleced from the list "zero", "one", "two", "few", "many" and "other". type the type used (cardinal or ordinal). only one of the fol...
JSON - JavaScript
al to make all json text valid ecma-262. in engines that haven't implemented the proposal, u+2028 line separator and u+2029 paragraph separator are allowed in string literals and property keys in json; but their use in these features in javascript string literals is a syntaxerror. consider this example where json.parse() parses the string as json and eval executes the string as javascript: let code = '"\u2028\u2029"' json.parse(code) // evaluates to "\u2028\u2029" in all engines eval(code) // throws a syntaxerror in old engines other differences include allowing only double-quoted strings and having no provisions for undefined or comments. for those who wish to use a more human-friendly configuration format based on json, there is json5, used by the babel compiler, and the more co...
Map.prototype.forEach() - JavaScript
e is visited once, except in the case when it was deleted and re-added before foreach has finished. callback is not invoked for values deleted before being visited. new values added before foreach has finished will be visited. foreach executes the callback function once for each element in the map object. it does not return a value. ...
Math.clz32() - JavaScript
integer << 16; integer |= integer << 8; integer |= integer << 4; integer |= integer << 2; integer |= integer << 1; // 2. now, inversing the bits reveals the lowest bits return 32 - clz(~integer) |0; // `|0` ensures integer coercion } function ctron(integer){ // count trailing ones // no shift-filling-in-with-ones operator is available in // javascript, so the below code is the fastest return ctrz(~integer); /* alternate implementation for demonstrational purposes: // 1. erase all the higher bits after the first zero integer &= (integer << 16) | 0xffff; integer &= (integer << 8 ) | 0x00ff; integer &= (integer << 4 ) | 0x000f; integer &= (integer << 2 ) | 0x0003; integer &= (integer << 1 ) | 0x0001; // 2. no...
Number.MAX_VALUE - JavaScript
merable no configurable no description the max_value property has a value of approximately 1.79e+308, or 21024. values larger than max_value are represented as infinity. because max_value is a static property of number, you always use it as number.max_value, rather than as a property of a number object you created. examples using max_value the following code multiplies two numeric values. if the result is less than or equal to max_value, the func1 function is called; otherwise, the func2 function is called. if (num1 * num2 <= number.max_value) { func1(); } else { func2(); } specifications specification ecmascript (ecma-262)the definition of 'number.max_value' in that specification. ...
Number.MIN_VALUE - JavaScript
y is the number closest to 0, not the most negative number, that javascript can represent. min_value has a value of approximately 5e-324. values smaller than min_value ("underflow values") are converted to 0. because min_value is a static property of number, you always use it as number.min_value, rather than as a property of a number object you created. examples using min_value the following code divides two numeric values. if the result is greater than or equal to min_value, the func1 function is called; otherwise, the func2 function is called. if (num1 / num2 >= number.min_value) { func1(); } else { func2(); } specifications specification ecmascript (ecma-262)the definition of 'number.min_value' in that specification. ...
Number.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax numobj.tosource() number.tosource() return value a string representing the source code of the object. examples native function for the built-in number object, tosource() returns the following string indicating that the source code is not available: function number() { [native code] } for instances of number, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
Number.prototype.valueOf() - JavaScript
ample is stored in a github repository. if 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 numobj.valueof() return value a number representing the primitive value of the specified number object. description this method is usually called internally by javascript and not explicitly in web code. examples using valueof let numobj = new number(10) console.log(typeof numobj) // object let num = numobj.valueof() console.log(num) // 10 console.log(typeof num) // number specifications specification ecmascript (ecma-262)the definition of 'number.prototype.valueof' in that specification. ...
Number - JavaScript
754 value, like double in java or c#. this means it can represent fractional values, but there are some limits to what it can store. a number only keeps about 17 decimal places of precision; arithmetic is subject to rounding. the largest value a number can hold is about 1.8×10308. numbers beyond that are replaced with the special number constant infinity. a number literal like 37 in javascript code is a floating-point value, not an integer. there is no separate integer type in common everyday use. (javascript now has a bigint type, but it was not designed to replace number for everyday uses. 37 is still a number, not a bigint.) number may also be expressed in literal forms like 0b101, 0o13, 0x0a. learn more on numeric lexical grammar here. description when used as a function, number(v...
Object.entries() - JavaScript
examples const obj = { foo: 'bar', baz: 42 }; console.log(object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] // array like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // a...
Object.getOwnPropertyDescriptor() - JavaScript
s { // value: 8675309, // writable: false, // enumerable: false, // configurable: false // } non-object coercion in es5, if the first argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object first argument will be coerced to an object at first. object.getownpropertydescriptor('foo', 0); // typeerror: "foo" is not an object // es5 code object.getownpropertydescriptor('foo', 0); // object returned by es2015 code: { // configurable: false, // enumerable: true, // value: "f", // writable: false // } specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertydescriptor' in that specification. ...
Object.getOwnPropertyDescriptors() - JavaScript
a shallow copy between two unknown objects: object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj) ); creating a subclass a typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance. this can get awkward especially for getters and setters. ...
Object.getOwnPropertyNames() - JavaScript
the properties of the object. the ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined. in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be coerced to an object. object.getownpropertynames('foo'); // typeerror: "foo" is not an object (es5 code) object.getownpropertynames('foo'); // ["0", "1", "2", "length"] (es2015 code) examples using object.getownpropertynames() var arr = ['a', 'b', 'c']; console.log(object.getownpropertynames(arr).sort()); // .sort() is an array method. // logs ["0", "1", "2", "length"] // array-like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.getownpropertynames(obj).sort()); // .sort() i...
Object.getPrototypeOf() - JavaScript
inherited properties, null is returned. examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an object. in es2015, the parameter will be coerced to an object. object.getprototypeof('foo'); // typeerror: "foo" is not an object (es5 code) object.getprototypeof('foo'); // string.prototype (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.getprototypeof' in that specification. ...
Object.isExtensible() - JavaScript
ion non-extensible. var frozen = object.freeze({}); object.isextensible(frozen); // === false non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return false. object.isextensible(1); // typeerror: 1 is not an object (es5 code) object.isextensible(1); // false (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.isextensible' in that specification. ...
Object.isFrozen() - JavaScript
zen); // === false // also by definition, a frozen object is sealed. object.issealed(frozen); // === true non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a frozen ordinary object, simply return true. object.isfrozen(1); // typeerror: 1 is not an object (es5 code) object.isfrozen(1); // true (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.isfrozen' in that specification. ...
Object.prototype.isPrototypeOf() - JavaScript
for example, check if baz object descends from foo.prototype: if (foo.prototype.isprototypeof(baz)) { // do something safe } specifications specification ecmascript (ecma-262)the definition of 'ob...
Object.keys() - JavaScript
for a simple browser polyfill, see javascript - object.keys browser compatibility. examples using object.keys // simple array const arr = ['a', 'b', 'c']; console.log(object.keys(arr)); // console: ['0', '1', '2'] // array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(obj...
Object.preventExtensions() - JavaScript
ed = object.preventextensions({}); // throws a 'typeerror'. fixed.__proto__ = { oh: 'hai' }; non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror. in es2015, a non-object argument will be treated as if it was a non-extensible ordinary object, simply return it. object.preventextensions(1); // typeerror: 1 is not an object (es5 code) object.preventextensions(1); // 1 (es2015 code) specifications specification ecmascript (ecma-262)the definition of 'object.preventextensions' in that specification. ...
Object.setPrototypeOf() - JavaScript
t or null. warning: changing the [[prototype]] of an object is, by the nature of how modern javascript engines optimize property accesses, currently a very slow operation in every browser and javascript engine. in addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the object.setprototypeof(...) statement, but may extend to any code that has access to any object whose [[prototype]] has been altered. because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[prototype]] of an object. instead, create a new object with the desired [...
Promise.race() - JavaScript
ollowing example demonstrates the asynchronicity of promise.race: // we are passing as argument an array of promises that are already resolved, // to trigger promise.race as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.race(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function(){ console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 33 } an empty iterable causes the returned promise to be forever pending: var foreverpendingpromise = promise.race([]); console.log(foreverpendingpromise); se...
handler.apply() - JavaScript
s a trap for a function call. interceptions this trap can intercept these operations: proxy(...args) function.prototype.apply() and function.prototype.call() reflect.apply() invariants if the following invariants are violated, the proxy will throw a typeerror. the target must be a callable itself. that is, it must be a function object. examples trapping a function call the following code traps a function call. const p = new proxy(function() {}, { apply: function(target, thisarg, argumentslist) { console.log('called: ' + argumentslist.join(', ')); return argumentslist[0] + argumentslist[1] + argumentslist[2]; } }); console.log(p(1, 2, 3)); // "called: 1, 2, 3" // 6 specifications specification ecmascript (ecma-262)the...
handler.defineProperty() - JavaScript
may not be non-configurable, if a corresponding configurable property of the target object exists. if a property has a corresponding target object property then object.defineproperty(target, prop, descriptor) will not throw an exception. in strict mode, a false return value from the defineproperty() handler will throw a typeerror exception. examples trapping of defineproperty the following code traps object.defineproperty(). const p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); return true; } }); const desc = { configurable: true, enumerable: true, value: 10 }; object.defineproperty(p, 'a', desc); // "called: a" when calling object.defineproperty() or reflect.defineproperty(), the descriptor passed to definepropert...
handler.deleteProperty() - JavaScript
ator. interceptions this trap can intercept these operations: property deletion: delete proxy[foo] and delete proxy.foo reflect.deleteproperty() invariants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be deleted, if it exists as a non-configurable own property of the target object. examples trapping the delete operator the following code traps the delete operator. const p = new proxy({}, { deleteproperty: function(target, prop) { if (prop in target){ delete target[prop] console.log('property removed: ' + prop) return true } else { console.log('property not found: ' + prop) return false } } }) let result p.a = 10 console.log('a' in p) // true result = delete p.a // "propert...
handler.get() - JavaScript
e the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable own data property. the value reported for a property must be undefined if the corresponding target object property is a non-configurable own accessor property that has undefined as its [[get]] attribute. examples trap for getting a property value the following code traps getting a property value. const p = new proxy({}, { get: function(target, property, receiver) { console.log('called: ' + property); return 10; } }); console.log(p.a); // "called: a" // 10 the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: false });...
handler.has() - JavaScript
variants if the following invariants are violated, the proxy will throw a typeerror: a property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object. a property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. examples trapping the in operator the following code traps the in operator. const p = new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return true; } }); console.log('a' in p); // "called: a" // true the following code violates an invariant. const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { has: function(target, prop) { return false; } }); ...
handler.isExtensible() - JavaScript
er.isextensible() method is a trap for object.isextensible(). interceptions this trap can intercept these operations: object.isextensible() reflect.isextensible() invariants if the following invariants are violated, the proxy will throw a typeerror: object.isextensible(proxy) must return the same value as object.isextensible(target). examples trapping of isextensible the following code traps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant. const p = new proxy({}, { isextensible: function(target) { return false; } }); object.isextensible(p); // ...
handler.ownKeys() - JavaScript
keys() must be an array. the type of each array element is either a string or a symbol. the result list must contain the keys of all non-configurable own properties of the target object. if the target object is not extensible, then the result list must contain all the keys of the own properties of the target object and no other values. examples trapping of getownpropertynames the following code traps object.getownpropertynames(). const p = new proxy({}, { ownkeys: function(target) { console.log('called'); return ['a', 'b', 'c']; } }); console.log(object.getownpropertynames(p)); // "called" // [ 'a', 'b', 'c' ] the following code violates an invariant. const obj = {}; object.defineproperty(obj, 'a', { configurable: false, en...
handler.preventExtensions() - JavaScript
is a trap for object.preventextensions(). interceptions this trap can intercept these operations: object.preventextensions() reflect.preventextensions() invariants if the following invariants are violated, the proxy will throw a typeerror: object.preventextensions(proxy) only returns true if object.isextensible(proxy) is false. examples trapping of preventextensions the following code traps object.preventextensions(). const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant. const p = new proxy({}, { preventextensions: function(...
ReferenceError() constructor - JavaScript
the referenceerror object represents an error when a non-existent variable is referenced. syntax new referenceerror([message[, filename[, linenumber]]]) parameters message optional optional. human-readable description of the error. filename optional optional. the name of the file containing the code that caused the exception. linenumber optional optional. the line number of the code that caused the exception. examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) ...
Reflect.apply() - JavaScript
use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). function.prototype.apply.call(math.floor, undefined, [1.75]); with reflect.apply() this becomes less verbose and easier to understand. examples using reflect.apply() reflect.apply(math.floor, undefined, [1.75]); // 1; reflect.apply(string.fromcharcode, undefined, [104, 101, 108, 108, 111]) // "hello" reflect.apply(regexp.prototype.exec, /ab/, ['confabulation']).index // 4 reflect.apply(''.charat, 'ponies', [3]) // "i" specifications specification ecmascript (ecma-262)the definition of 'reflect.apply' in that specification. ...
RegExp() constructor - JavaScript
s flags (and lastindex will be reset to 0) (as of es2015). if flags is not specified and a regular expressions object is supplied, that object's flags (and lastindex value) will be copied over. flags may contain any combination of the following characters: g (global match) find all matches rather than stopping after the first match. i (ignore case) if u flag is also enabled, use unicode case folding. m (multiline) treat beginning and end characters (^ and $) as working over multiple lines. in other words, match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string. s ("dotall") allows . to match newlines. u (unicode) treat pattern as a sequence of unicode code points. (see also binary strings). y (st...
RegExp.prototype.dotAll - JavaScript
used; otherwise, false. the "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: u+000a line feed (lf) ("\n") u+000d carriage return (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will match any character on the unicode basic multilingual plane (bmp). to allow it to match astral characters, the "u" (unicode) flag should be used. using both flags in conjunction allows the dot to match any unicode character, without exceptions. you cannot change this property directly. examples using dotall var str1 = 'bar\nexample foo example'; var regex1 = new regexp('bar.example','s'); console.log(regex1.dotall); // outpu...
RegExp.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax regexobj.tosource() return value a string representing the source code of the given regexp object. examples native function for the built-in regexp object, tosource() returns the following string indicating that the source code is not available: function regexp() { [native code] } for instances of regexp, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
Set.prototype.forEach() - JavaScript
visited once, except in the case when it was deleted and re-added before foreach() has finished. callback is not invoked for values deleted before being visited. new values added before foreach() has finished will be visited. foreach() executes the callback function once for each element in the set object; it does not return a value. ...
String.prototype[@@iterator]() - JavaScript
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str[symbol.iterator] return value a new iterator object. ...
String.prototype.link() - JavaScript
syntax str.link(url) parameters url any string that specifies the href attribute of the <a> tag; it should be a valid url (relative or absolute), with any & characters escaped as &amp;, and any " characters escaped as &quot;. return value a string containing an <a> html element. description use the link() method to create an html snippet for a hypertext link. the returned string can then be added to the document via document.write() or element.innerhtml. links created with the link() method become elements in the links array of the document object. see document.links. ...
String.prototype.match() - JavaScript
ay. const str = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; const regexp = /[a-e]/gi; const matches_array = str.match(regexp); console.log(matches_array); // ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'] note: see also string.prototype.matchall() and advanced searching with flags. using named capturing groups in browsers which support named capturing groups, the following code captures "fox" or "cat" into a group named "animal": const paragraph = 'the quick brown fox jumps over the lazy dog. it barked.'; const capturingregex = /(?<animal>fox|cat) jumps over/; const found = paragraph.match(capturingregex); console.log(found.groups); // {animal: "fox"} using match() with no parameter const str = "nothing will come of nothing."; str.match(); // returns [""] a non...
String.raw() - JavaScript
) is used with template strings. the first syntax mentioned above is only rarely used, because the javascript engine will call this with proper arguments for you, (just like with other tag functions). string.raw() is the only built-in tag function of template strings. it works just like the default template function and performs concatenation. you can even re-implement it with normal javascript code. examples using string.raw() string.raw`hi\n${2+3}!`; // 'hi\n5!', the character after 'hi' // is not a newline character, // '\' and 'n' are two characters. string.raw`hi\u000a!`; // 'hi\u000a!', same here, this time we will get the // \, u, 0, 0, 0, a, 6 characters. // all kinds of escape characters will be ineffective // and backslashes will be present in the output string. // you can con...
String.prototype.substr() - JavaScript
length is omitted, substr() extracts characters to the end of the string. if length is undefined, substr() extracts characters to the end of the string. if length is a negative number, it is treated as 0. for both start and length, nan is treated as 0. polyfill microsoft's jscript does not support negative values for the start index. ...
String.prototype.substring() - JavaScript
fulls.length) } } return fulls } replacestring('world', 'web', 'brave new world') note that this can result in an infinite loop if olds is itself a substring of news — for example, if you attempted to replace 'world' with 'otherworld' here. a better method for replacing strings is as follows: function replacestring(olds, news, fulls) { return fulls.split(olds).join(news) } the code above serves as an example for substring operations. if you need to replace substrings, most of the time you will want to use string.prototype.replace(). specifications specification ecmascript (ecma-262)the definition of 'string.prototype.substring' in that specification. ...
String.prototype.toLocaleLowerCase() - JavaScript
e string. description the tolocalelowercase() method returns the value of the string converted to lower case according to any locale-specific case mappings. tolocalelowercase() does not affect the value of the string itself. in most cases, this will produce the same result as tolowercase(), but for some locales, such as turkish, whose case mappings do not follow the default case mappings in unicode, there may be a different result. examples using tolocalelowercase() 'alphabet'.tolocalelowercase(); // 'alphabet' '\u0130'.tolocalelowercase('tr') === 'i'; // true '\u0130'.tolocalelowercase('en-us') === 'i'; // false let locales = ['tr', 'tr', 'tr-tr', 'tr-u-co-search', 'tr-x-turkish']; '\u0130'.tolocalelowercase(locales) === 'i'; // true specifications specification ...
String.prototype.toLocaleUpperCase() - JavaScript
e string. description the tolocaleuppercase() method returns the value of the string converted to upper case according to any locale-specific case mappings. tolocaleuppercase() does not affect the value of the string itself. in most cases, this will produce the same result as touppercase(), but for some locales, such as turkish, whose case mappings do not follow the default case mappings in unicode, there may be a different result. also notice that conversion is not necessarily a 1:1 character mapping, as some characters might result in two (or even more) characters when transformed to upper-case. therefore the length of the result string can differ from the input length. this also implies that the conversion is not stable, so i.e. the following can return false: x.tolocalelowercase() ===...
String.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. syntax string.tosource() str.tosource() return value a string representing the source code of the calling object. examples native function for the built-in string object, tosource() returns the following string indicating that the source code is not available: function string() { [native code] } for instances of string or string literals, tosource() returns a string representing the source code. this method is usually called internally by javascript and not explicitly in web code. specifications not part of any standard. ...
String.prototype.trim() - JavaScript
e interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax str.trim() return value a new string representing the str stripped of whitespace from both ends. description the trim() method returns the string stripped of whitespace from both ends. trim() does not affect the value of the str itself. polyfill running the following code before any other code will create trim() if it's not natively available. if (!string.prototype.trim) { string.prototype.trim = function () { return this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; } examples using trim() the following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim()); // 'foo' // another example of .trim() removi...
String.prototype.valueOf() - JavaScript
s the primitive value of a string object. syntax str.valueof() return value a string representing the primitive value of a given string object. description the valueof() method of string returns the primitive value of a string object as a string data type. this value is equivalent to string.prototype.tostring(). this method is usually called internally by javascript and not explicitly in code. examples using valueof() var x = new string('hello world'); console.log(x.valueof()); // displays 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.valueof' in that specification. ...
Symbol() constructor - JavaScript
pull request. syntax symbol([description]) parameters description optional a string. a description of the symbol which can be used for debugging but not to access the symbol itself. examples creating symbols to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols. note that symbol("foo") does not coerce the string "foo" into a symbol. it creates a new symbol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol va...
Symbol.for() - JavaScript
...
Symbol.match - JavaScript
peerror if they are. now, if the match symbol is set to false (or a falsy value), it indicates that the object is not intended to be used as a regular expression object. property attributes of symbol.match writable no enumerable no configurable no examples disabling the isregexp check the following code will throw a typeerror: '/bar/'.startswith(/bar/); // throws typeerror, as /bar/ is a regular expression // and symbol.match is not modified. however, if you set symbol.match to false, the isregexp check (that uses the match property) will indicate that the object is not a regular expression object. the methods startswith and endswith won't throw a typeerror as a consequence. var re = /foo/; ...
Symbol.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object. this method is usually called internally by javascript. syntax symbol.tosource() var sym = symbol() sym.tosource() return value a string representing the source code of the object. examples native function for the built-in symbol object, tosource returns the following string indicating that the source code is not available: "function symbol() { [native code] }" for instances of symbol, tosource returns a string representing the source code. "symbol()" specifications not part of any standard. ...
Symbol.unscopables - JavaScript
pable and therefore it won't appear in lexical scope variables. setting a property to false will make it scopable and thus it will appear in lexical scope variables. property attributes of symbol.unscopables writable no enumerable no configurable no examples scoping in with statements the following code works fine in es5 and below. however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced. that means that inside with environment "keys" would now be the method and not the variable. that's when the unscopables symbol was introduced. a built-in unscopables setting is implemented as array.prototype[@@unscopables] to prevent that some of the array methods are being scope...
TypedArray.prototype.forEach() - JavaScript
sting elements of the typed array are changed, the value passed to callback will be the value at the time foreach() visits them; elements that are deleted before being visited are not visited. foreach() executes the callback function once for each typed array element; unlike every() and some() it, always returns the value undefined. ...
TypedArray.from() - JavaScript
then creates an instance of thisarg using the count, then sets the values on the instance. array.from() sets each value as it receives them from the iterator, then sets its length at the end. when array.from() gets an array-like which isn't an iterator, it respects holes. typedarray.from() will ensure the result is dense. polyfill you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of from() in implementations that do not natively support it. if (!int8array.__proto__.from) { (function () { int8array.__proto__.from = function (obj, func, thisobj) { var typedarrayclass = int8array.__proto__; if(typeof this !== 'function') { throw new typeerror('# i...
TypedArray.prototype.toString() - JavaScript
.com/mdn/interactive-examples and send us a pull request. syntax typedarray.tostring() return value a string representing the elements of the typed array. examples the typedarray objects override the tostring method of object. for typedarray objects, the tostring method joins the array and returns one string containing each typed array element separated by commas. for example, the following code creates a typed array and uses tostring to convert the array to a string. var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "2,5,8,1,4" javascript calls the tostring method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation. compatibility if a browser doesn't support the typedarray.prototype.tostr...
URIError - JavaScript
ror. urierror.prototype.filename path to file that raised this error. inherited from error. urierror.prototype.linenumber line number in file that raised this error. inherited from error. urierror.prototype.columnnumber column number in line that raised this error. inherited from error. urierror.prototype.stack stack trace. inherited from error. ...
WebAssembly.Global() constructor - JavaScript
.then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running live on github; see also the source code. specifications specification webassembly javascript interfacethe definition of 'webassembly.global() constructor' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. des...
WebAssembly.Global - JavaScript
.then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running live on github; see also the source code. specifications specification webassembly javascript interfacethe definition of 'webassembly.global()' in that specification. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilese...
WebAssembly.Instance.prototype.exports - JavaScript
the exports readonly property of the webassembly.instance object prototype returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript. instance.exports examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process. we then call an exported webassembly function that is exported by the instance. var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported...
WebAssembly.Instance - JavaScript
constructor webassembly.instance() creates a new instance object. instance properties instance.prototype.exports returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript. read-only. ...
WebAssembly.Memory.prototype.buffer - JavaScript
it then stores some values in that memory, then exports a function and uses it to sum some values. ...
WebAssembly.Module.customSections() - JavaScript
m command available as part of the wabt tool has a --debug-names option — specify this during conversion to get a .wasm with a names custom section, for example: wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names examples using customsections the following example (see the custom-section.html source and live example) compiles the loaded simple-name-section.wasm byte code. we then do a check using webassembly.module.customsections, looking to see whether the module instance contains a "name" custom section by checking that its length is more than 0. since there is a "name" section in the example, an arraybuffer object is returned. webassembly.compilestreaming(fetch('simple-name-section.wasm')) .then(function(mod) { var namesections = webassembly.module.customs...
WebAssembly.Module.exports() - JavaScript
e); parameters module a webassembly.module object. return value an array containing objects representing the exported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. whe...
WebAssembly.Module.imports() - JavaScript
declared imports of the given module. syntax webassembly.module.imports(module); parameters module a webassembly.module object. return value an array containing objects representing the imported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module. this module is then queried for its imports. webassembly.compilestreaming(fetch('simple.wasm')) .then(function(mod) { var imports = webassembly.module.imports(mod); console.log(imports[0]); }); the output looks like this: { module: "imports", name: "imported_func", kind: "function" } specifications specification ...
WebAssembly.Table() constructor - JavaScript
of elements of the webassembly table. maximum optional the maximum number of elements the webassembly table is allowed to grow to. exceptions if tabledescriptor is not of type object, a typeerror is thrown. if maximum is specified and is smaller than initial, a rangeerror is thrown. examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null. var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" consol...
WebAssembly.Table.prototype.get() - JavaScript
want to retrieve. return value a function reference — this is an exported webassembly function, a javascript wrapper for an underlying wasm function. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method. it then retrieves the references stored in the exported table. webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 }); note how you've got to include a second function invocation operator at the end of the acce...
WebAssembly.Table.prototype.set() - JavaScript
e the reference to. this must be an exported webassembly function, a javascript wrapper for an underlying wasm function. return value void. exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. if value is not an exported webassembly function or null, a typeerror is thrown. examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references. we then print out the table length and contents of the two indexes (retrieved via table.prototype.get()) to show that the length is two, and the indexes currently contain no function references (they currently return null). var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(...
WebAssembly.instantiateStreaming() - JavaScript
syntax promise<resultobject> webassembly.instantiatestreaming(source, importobject); parameters source a response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream, compile, and instantiate. ...
WebAssembly.validate() - JavaScript
the webassembly.validate() function validates a given typed array of webassembly binary code, returning whether the bytes form a valid wasm module (true) or not (false). syntax webassembly.validate(buffersource); parameters buffersource a typed array or arraybuffer containing webassembly binary code to be validated. return value a boolean that specifies whether buffersource is valid wasm code (true) or not (false). exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array. the validate() method is then used to check whether the module is valid. fetch('simple.wasm').then(response => respon...
Iteration protocols - JavaScript
atisfies both the iterator protocol and iterable let myiterator = { next: function() { // ... ...
Comma operator (,) - JavaScript
comma operator when you want to include multiple expressions in a location that requires a single expression. the most common usage of this operator is to supply multiple parameters in a for loop. the comma operator is fully different from the comma within arrays, objects, and function arguments and parameters. examples if a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once. the following code prints the values of the diagonal elements in the array: for (var i = 0, j = 9; i <= 9; i++, j--) console.log('a[' + i + '][' + j + '] = ' + a[i][j]); note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. in the f...
Less than (<) - JavaScript
s project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax x < y description the operands are compared using the abstract relational comparison algorithm, which is roughly summarised below: first, objects are converted to primitives using symbol.toprimitive. if both values are strings, they are compared as strings, based on the values of the unicode code points they contain. otherwise javascript attempts to convert non-numeric types to numeric values: boolean values true and false are converted to 1 and 0 respectively. null is converted to 0. undefined is converted to nan. strings are converted based on the values they contain, and are converted as nan if they do not contain numeric values. if either value is nan, the o...
Logical AND (&&) - JavaScript
ng value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using and the following code shows examples of the && (logical and) operator. a1 = true && true // t && t returns true a2 = true && false // t && f returns false a3 = false && true // f && t returns false a4 = false && (3 == 4) // f && f returns false a5 = 'cat' && 'dog' // t && t returns "dog" a6 = false && 'cat' // f && t returns false a7 = 'cat' && false // t && f returns false a8 = ''...
Logical NOT (!) - JavaScript
d. even though the ! operator can be used with operands that are not boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. to explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double not operator or the boolean constructor. examples using not the following code shows examples of the ! (logical not) operator. n1 = !true // !t returns false n2 = !false // !f returns true n3 = !'' // !f returns true n4 = !'cat' // !t returns false double not (!!) it is possible to use a couple of not operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. the conv...
Logical OR (||) - JavaScript
ing value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using or the following code shows examples of the || (logical or) operator. o1 = true || true // t || t returns true o2 = false || true // f || t returns true o3 = true || false // t || f returns true o4 = false || (3 == 4) // f || f returns false o5 = 'cat' || 'dog' // t || t returns "cat" o6 = false || 'cat' // f || t returns "cat" o7 = 'cat' || false // t || f returns "cat" o8 = '' ...
Pipeline operator (|>) - JavaScript
the experimental pipeline operator |> (currently at stage 1) pipes the value of an expression into a function. this allows the creation of chained function calls in a readable manner. the result is syntactic sugar in which a function call with a single argument can be written like this: let url = "%21" |> decodeuri; the equivalent call in traditional syntax looks like this: let url = decodeuri("%21"); syntax expression |> function the value of the specified expression is passed into the function as its sole parameter. parameters expression any valid expression. function any function. examples chaining function calls the pipeline operator can improve readability when chaining several functions. const double = (n) => n * 2; const increment = (n) => n + 1; // without pipelin...
Spread syntax (...) - JavaScript
with spread syntax this becomes much more succinct: const parts = ['shoulders', 'knees']; const lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders", "knees", "and", "toes"] just like spread for argument lists, ... can be used anywhere in the array literal, and may be used more than once. copy an arra...
Function expression - JavaScript
s it to x. the function returns the square of its argument: var x = function(y) { return y * y; }; using a function as a callback more commonly it is used as a callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) using an immediately executed function expression an anonymous function is created and called: (function() { console.log('code runs!') })(); specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification. ...
super - JavaScript
in any method definition in both classes and object literals. syntax super([arguments]); // calls the parent constructor. super.functiononparent([arguments]); description when used in a constructor, the super keyword appears alone and must be used before the this keyword is used. the super keyword can also be used to call functions on a parent object. examples using super in classes this code snippet is taken from the classes sample (live demo). here super() is called to avoid duplicating the constructor parts' that are common between rectangle and square. class rectangle { constructor(height, width) { this.name = 'rectangle'; this.height = height; this.width = width; } sayname() { console.log('hi, i am a ', this.name + '.'); } get area() { return this.h...
yield* - JavaScript
nd send us a pull request. syntax yield* expression; expression the expression which returns an iterable object. description the yield* expression iterates over the operand and yields each value returned by it. the value of yield* expression itself is the value returned by that iterator when it's closed (i.e., when done is true). examples delegating to another generator in following code, values yielded by g1() are returned from next() calls just like those which are yielded by g2(). function* g1() { yield 2; yield 3; yield 4; } function* g2() { yield 1; yield* g1(); yield 5; } const iterator = g2(); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, done: fa...
block - JavaScript
roduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. in other words, block statements do not introduce a scope. for example: var x = 1; { var x = 2; } console.log(x); // logs 2 this logs 2 because the var x statement within the block is in the same scope as the var x statement before the block. in non-strict code, function declarations inside blocks behave strangely. do not use them. block scoping rules with let, const or function declaration in strict mode by contrast, identifiers declared with let and const do have block scope: let x = 1; { let x = 2; } console.log(x); // logs 1 the x = 2 is limited in scope to the block in which it was defined. the same is true of const: const c = 1; { const ...
debugger - JavaScript
the debugger statement invokes any available debugging functionality, such as setting a breakpoint. if no debugging functionality is available, this statement has no effect. syntax debugger; examples using the debugger statement the following example shows code where a debugger statement has been inserted, to invoke a debugger (if one exists) when the function is called. function potentiallybuggycode() { debugger; // do potentially buggy stuff to examine, step through, etc. } when the debugger is invoked, execution is paused at the debugger statement. it is like a breakpoint in the script source. specifications specification ecmascript (ecma-262)the definition of 'debugger statement' in that specification. ...
for await...of - JavaScript
// the for-await-of loop. async iterates over each portion of the response. for await (const chunk of streamasynciterable(response.body)) { // incrementing the total response length. responsesize += chunk.length; } console.log(`response size: ${responsesize} bytes`); // expected output: "response size: 1071472" return responsesize; } getresponsesize('https://jsonplaceholder.typicode.com/photos'); iterating over sync iterables and generators for await...of loop also consumes sync iterables and generators. in that case it internally awaits emitted values before assign them to the loop control variable. function* generator() { yield 0; yield 1; yield promise.resolve(2); yield promise.resolve(3); yield 4; } (async function() { for await (let num of generator()) {...
for...in - JavaScript
prototype.foreach() or the for...of loop) when iterating over arrays where the order of access is important. iterating over own properties only if you only want to consider properties attached to the object itself, and not its prototypes, use getownpropertynames() or perform a hasownproperty() check (propertyisenumerable() can also be used). alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method. why use for...in? given that for...in is built for iterating object properties, not recommended for use with arrays, and options like array.prototype.foreach() and for...of exist, what might be the use of for...in at all? it may be most practically used for debugging purposes, being an easy way to check the properties of an ...
for...of - JavaScript
object.prototype.objcustom = function() {}; array.prototype.arrcustom = function() {}; const iterable = [3, 5, 7]; iterable.foo = 'hello'; every object will inherit the objcustom property and every object that is an array will inherit the arrcustom property since these properties have been added to object.prototype and array.prototype, respectively. the object iterable inherits t...
function* - JavaScript
of the object returned by it will be set to true). if a value is returned, it will be set as the value property of the object returned by the generator. much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. when a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done: true}. examples simple example function* idmaker() { var index = 0; while (true) yield index++; } var gen = idmaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ... example with yield* function* anothergener...
return - JavaScript
ng return statements all break the function execution: return; return true; return false; return x; return x + y / 3; automatic semicolon insertion the return statement is affected by automatic semicolon insertion (asi). no line terminator is allowed between the return keyword and the expression. return a + b; is transformed by asi into: return; a + b; the console will warn "unreachable code after return statement". starting with firefox 40, a warning is shown in the console if unreachable code is found after a return statement. to avoid this problem (to prevent asi), you could use parentheses: return ( a + b ); examples interrupt a function a function immediately stops at the point where return is called. function counter() { for (var count = 1; ; count++) { // infinite...
switch - JavaScript
specifications specification ecmascript (ecma-262)the definition of 'switch statement' in that specification. ...
dir - Web app manifests
Web › Manifest › dir
gether with the lang member, it helps to correctly display right-to-left languages. the dir member can be set to one of the following values: auto — text direction is determined by the user agent ltr — left to right rtl — right to left the directionality-capable members are: name short_name description note: if the value is omitted or set to auto, the browser will use the unicode bidirectional algorithm to make a best guess about the text's direction. example "dir": "rtl", "lang": "ar", "short_name": "!أنا من التطبيق" specification specification status comment feedback web app manifestthe definition of 'dir' in that specification. working draft initial definition. web app manifest wor...
iarc_rating_id - Web app manifests
type string mandatory no the iarc_rating_id member is a string that represents the international age rating coalition (iarc) certification code of the web application. it is intended to be used to determine which ages the web application is appropriate for. note: the same code can be shared across multiple participating storefronts, as long as the distributed product remains the same (i.e., doesn’t serve totally different code paths on different storefronts). examples "iarc_rating_id": "e84b072d-71b3-4d3e-86ae-31a8ce4e53b7" specification specification status comment feedback web app manifestthe definition of 'iarc_rating_id' in that specification. working draft initial definition. ...
<mglyph> - MathML
Web › MathML › Element › mglyph
it may be used within token elements. attributes alt this attribute defines the alternative text describing the image. users will see this displayed if the image url is wrong, the image is not in one of the supported formats, or until the image is downloaded. class, id, style provided for use with stylesheets. height the height of the image. href used to set a hyperlink to a specified uri. mathbackground the background color (if the image has transparency). you can use #rgb, #rrggbb and html color names. src the image url. ...
<semantics> - MathML
the mathml elements <semantics>, <annotation> and <annotation-xml> are used to combine presentation and content markup and to provide both, layout information and semantic meaning of mathematical expressions. the <semantics> element acts as a container element associating annotations and must have child elements (it will raise an invalid markup error otherwise). ...
Handling media support issues in web content - Web media technologies
opularity and with a variety of capabilities. the availability of choices is good for the user, in that they can choose the format that suits their needs best. there is a drawback, however: because there are so many to choose from, with so many different kinds of licenses and design principles involved, each web browser developer is left to its own devices when deciding which media file types and codecs to support. this places a small, but reasonably easily overcome, burden on the web developer: to properly handle the situation when the user's browser can't handle a particular type of media. this guide covers techniques you can use to develop web content that meets your media needs while providing the most broadly compatible experience possible. topics we will examine fallbacks, baseline medi...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
lt in the <img> not displaying the image correctly. therefore, once the image is loaded, we start using the intrinsic aspect ratio of the loaded image rather than the aspect ratio from the attributes, so it displays at the correct aspect ratio. summary so there you have it — eliminating another piece of jank from web layout! there is no need for a web developer to do anything special to their code to take advantage of this, besides returning to the habit of using width and height attributes in their html. they'll just get it for free. note: this new mechanism is enabled in firefox 69 in beta and nightly as the spec is worked out (controlled by the layout.css.width-and-height-map-to-aspect-ratio.enabled pref), and it is currently being implemented in chrome. it will ship with firefox 71. ...
Web media technologies
udio> and <video> elements. accessibility guide for media in web design in this guide, we cover ways web designers and developers can create content that is accessible to people with different capabilities. this ranges from simply using the alt attribute on <img> elements to captions to tagging media for screen readers. guide to media types and formats on the web a guide to the file types and codecs available for images, audio, and video media on the web. this includes recommendations for what formats to use for what kinds of content, best practices including how to provide fallbacks and how to prioritize media types, and also includes general browser support information for each media container and codec. streaming audio and video a guide which covers how to stream audio and video, as w...
Recommended Web Performance Timings: How long is too long? - Web Performance
single threaded (though background threads are supported for web workers). this means that user interaction, painting, and script execution are all on the same thread. if the thread is busy doing complex javascript execution, the main thread will not be available to react to user input, such as pressing a button. for this reason, script execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less. this makes the thread available for user interactions. animation goal for scrolling and other animations to look smooth and feel responsive, the content repaints should occur at 60 frames per second (60fps), which is once every 16.7ms. the 16.7 milliseconds includes scripting, reflow, and repaint. realize a document takes about 6ms to render a frame, leavin...
Performance budgets - Web Performance
use bot integrates with travis ci and can be used to gather lighthouse and webpage test metrics from a development url. the bot will pass or fail based on the provided minimum scores. how do i enforce a performance budget? the sooner that you can identify a potential addition pushing the budget, the better you can analyze the current state of your site, and pinpoint optimizations or unnecessary code. however, you should have multiple budgets and be dynamic. they are meant to reflect your ongoing goals but allow risks and experiments. for example, you may introduce a feature that increases overall load time but attempts to increase user engagement. (i.e. how long a user stays on a page or site). a performance budget helps you protect optimal behavior for your current users while enabling yo...
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
n and, from a monitoring perspective, allows you to identify key areas to target for optimization and performance improvements. rum v synthetic synthetic is well suited for catching regressions during development life cycles, especially with network throttling. it is fairly easy, inexpensive, and great for spot-checking performance during development as an effective way to measure the effect of code changes, but it doesn’t reflect what real users are experiencing and provides only a narrow view of performance. rum, on the other hand, provides real metrics from real users using the site or application. while this is more expensive and likely less convenient, it provides vital user experience data. performance apis there are many monitoring services. if you do want to roll your own monit...
Installing and uninstalling web apps - Progressive web apps (PWAs)
sung internet from version 4 onward, and firefox for android version 58 and later. safari on ios is a little different. some parts of the pwa ecosystem are supported, while others are not. ios 13 introduced a much more comparable install experience, which is also described here. the install user experience we've written a very simple example web site (see our demo live, and also see the source code) that doesn't do much, but was developed with the necessary code to allow it to be installed, as well as a service worker to enable it to be used offline. the example displays a series of fox pictures.if you have a web application compatible device available, use it to navigate to our demo at https://mdn.github.io/pwa-examples/a2hs/. you'll see fox pictures, but more importantly, some form of use...
How to make PWAs installable - Progressive web apps (PWAs)
background color to use in loading or splash screens. this information is needed for the browser to present the web app properly during the installation process, as well as within the device's app-launching interface, such as the home screen of a mobile device. the js13kpwa.webmanifest file of the js13kpwa web app is included in the <head> block of the index.html file using the following line of code: <link rel="manifest" href="js13kpwa.webmanifest"> there are a few common kinds of manifest file that have been used in the past: manifest.webapp was popular in firefox os app manifests, and many use manifest.json for web manifests as the contents are organized in a json structure. however, the .webmanifest file format is explicitly mentioned in the w3c manifest specification, so that's what w...
Web API reference - Web technology reference
Web › Reference › API
each individual interface across all apis is listed in the index. there's also a listing of all available events in the event reference. document object model the dom is an api that allows access to and modification of the current document. it allows manipulation of document node and element. html, xml and svg have extended it to manipulate their specific elements. ...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
e origin as the referencing document. using embedded svg to apply an svg effect using css styles, you first need to create the css style that references the svg to apply. <style>p { mask: url(#my-mask); }</style> in the above example, all paragraphs are masked by an svg <mask> with the id my-mask. ...
direction - SVG: Scalable Vector Graphics
the direction attribute specifies the inline-base direction of a <text> or <tspan> element. it defines the start and end points of a line of text as used by the text-anchor and inline-size properties. it also may affect the direction in which characters are positioned if the unicode-bidi property's value is either embed or bidi-override. it applies only to glyphs oriented perpendicular to the inline-base direction, which includes the usual case of horizontally-oriented latin or arabic text and the case of narrow-cell latin or arabic characters rotated 90 degrees clockwise relative to a top-to-bottom inline-base direction. in many cases, the bidirectional unicode algorithm produces the desired result automatically, so this attribute doesn't need to be specified in those cases. for other case...
href - SVG: Scalable Vector Graphics
Web › SVG › Attribute › href
table yes radialgradient for <radialgradient>, href defines url referring to a template gradient element; to be valid, the reference must be to a different <lineargradient> or <radialgradient> element. value <url> default value none animatable yes script for <script>, href defines a url referring to an external resource containing the script code. value <url> default value none animatable no textpath for <textpath>, href defines a url referring to the <path> element or basic shape onto which the text will be rendered if no path attribute is provided. on the <textpath> element, the href attribute is animatable. value <url> default value none animatable yes ...
textLength - SVG: Scalable Vector Graphics
div class="controls"> <input type="range" id="widthslider" min="80" max="978"> <span id="widthdisplay"></span> </div> the <input> element, of type "range", is used to create the slider control the user will manipulate to change the width of the text. a <span> element of id "widthdisplay" is provided to display the current width value. javascript finally, let's have a look at the javascript code. it starts by stashing references to the elements it will need to access, using document.getelementbyid(): const widthslider = document.getelementbyid("widthslider"); const widthdisplay = document.getelementbyid("widthdisplay"); const textelement = document.getelementbyid("hello"); const baselength = math.floor(textelement.textlength.baseval.value); widthslider.value = baselength; widthslider.
writing-mode - SVG: Scalable Vector Graphics
writing-mode attribute specifies whether the initial inline-progression-direction for a <text> element shall be left-to-right, right-to-left, or top-to-bottom. the writing-mode attribute applies only to <text> elements; the attribute is ignored for <tspan>, <tref>, <altglyph> and <textpath> sub-elements. (note that the inline-progression-direction can change within a <text> element due to the unicode bidirectional algorithm and properties direction and unicode-bidi.) note: as a presentation attribute, writing-mode can be used as a css property. see the css writing-mode property for more information. as a presentation attribute, it can be applied to any element but it has effect only on the following five elements: <altglyph>, <text>, <textpath>, <tref>, and <tspan> usage notes de...
xlink:href - SVG: Scalable Vector Graphics
indirect to an arbitrary level; thus, if the referenced element inherits attribute or gradient stops due to its own xlink:href attribute, then the current element can inherit those attributes or gradient stops. value <iri> default value none animatable yes script for <script>, xlink:href defines a reference to an external resource containing the script code. value <iri> default value none animatable no textpath for <textpath>, xlink:href defines a reference to the <path> element onto which the glyphs will be rendered. value <iri> default value none animatable yes use for <use>, xlink:href defines the location of the referenced object. value <iri> ...
Compatibility sources - SVG: Scalable Vector Graphics
story for firefox http://www.webkit.org/projects/svg/status.xml together with its recorded archive for webkit, safari and chrome http://www.opera.com/docs/specs/opera9/svg/ and accompanying pages for opera >= 9, http://www.opera.com/docs/specs/opera8/ for opera 8 http://blogs.msdn.com/b/ie/archive/2010/03/18/svg-in-ie9-roadmap.aspx for hints on ie9 support status the svg support charts at codedread.com for basic checks against the w3c test suite wikipedia for basic hints, not normative ...
Content type - SVG: Scalable Vector Graphics
a <transform-list> is used to specify a list of coordinate system transformations. a detailed description of the possible values for a <transform-list> is given in the transform attribute definition. within the svg dom, a <transform-list> value is represented using an svgtransformlist or svganimatedtransformlist object. url url a uniform resource locator. a url is a sequence of unicode characters, building an address to an internal or external resource. before svg 2, the more limited iri content type was used instead, because the url specification was not standardized before. ...
<font-face> - SVG: Scalable Vector Graphics
Web › SVG › Element › font-face
font-face> svg element corresponds to the css @font-face rule. it defines a font's outer properties. usage context categoriesfont elementpermitted contentany number of descriptive elements » and at most one <font-face> element, in any order. ...
Linking - SVG: Scalable Vector Graphics
Web › SVG › Linking
...
Namespaces crash course - SVG: Scalable Vector Graphics
are the namespaces you use in your xml files. if you don't, user agents such as firefox won't recognize your content and will simply show the xml markup or inform the user that there's an error in the xml. it's a good idea to use a template that includes all the commonly used namespace declarations when creating new svg files. if you don't already have one, make one up starting with the following code: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> </svg> even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations. it may save you from some annoying errors if you end up adding content from one of the unused namespaces at a later date. a full example for a full example see svg: namesp...
Scripting - SVG: Scalable Vector Graphics
Web › SVG › Scripting
one can override default browser behaviors with the evt.preventdefault( ) method, add eventlisteners to objects with the syntax element.addeventlistener(event, function, usecapture), and set element properties with syntax svgelement.style.setproperty("fill-opacity", "0.0", ""). note the existence of all three arguments setting properties. preventing default behavior in event code when writing drag and drop code, sometimes you'll find that text on the page gets accidently selected while dragging. or if you want to use the backspace key in your code, you want to override the browser's default behavior when the backspace key is pressed, which is to go back to the previous page. the evt.preventdefault() method lets you do this. using eventlisteners with objects the methods addeventlist...
Specification Deviations - SVG: Scalable Vector Graphics
consciously decided to make gecko deviate from or extend the svg specification. this page lists those deviations/extensions and our reasoning for them. the 'class' and 'style' attributes unlike html and mathml, the svg specification does not specify the 'style' and 'class' attributes on all svg elements. nevertheless, to allow mozilla to more cleanly share internal 'class' and 'style' related code, we will implement these attributes on all svg elements as of firefox 3. in general this change will not be visible to svg authors (the elements for which the svg specification does not define the 'class' and 'style' attribute are elements that are not displayed directly). however, there are two exceptions. extending the 'class' attribute to apply to all svg elements will allow svg authors to use...
Basic shapes - SVG: Scalable Vector Graphics
ment in the document. different elements correspond to different shapes and take different parameters to describe the size and position of those shapes. some are slightly redundant in that they can be created by other shapes, but they're all there for your convenience and to keep your svg documents as short and as readable as possible. all the basic shapes are shown in the image to the right. ...
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
n > regedit) and search for "svg". change every occurance of "image/svg-xml" (or whatever the invalid media type is) to "image/svg+xml". normally, this matters just for the entry "hkey_classes_root\.svg\content type". after correcting the os file associations you will probably need to re-clean your mimetypes.rdf as described in the section above. fixing the bug need to look at the exthandler code. related bugs: bug 332690 and bug 303581. ...
Mixed content - Web security
r of the https page and potentially steal sensitive data from the user. hence, in addition to the risks described for mixed display content above, mixed active content is vulnerable to a few other attack vectors. in the mixed active content case, a man-in-the-middle attacker can intercept the request for the http content. the attacker can also rewrite the response to include malicious javascript code. malicious active content can steal the user's credentials, acquire sensitive data about the user, or attempt to install malware on the user's system (by leveraging vulnerabilities in the browser or its plugins, for example). the risk involved with mixed content does depend on the type of website the user is visiting and how sensitive the data exposed to that site may be. the webpage may have pu...
How to turn off form autocompletion - Web security
r autofill (that is, pre-populate certain fields upon load). these features are usually enabled by default, but they can be a privacy concern for users, so browsers can let users disable them. however, some data submitted in forms either are not useful in the future (for example, a one-time pin) or contain sensitive information (for example, a unique government identifier or credit card security code). as website author, you might prefer that the browser not remember the values for such fields, even if the browser's autocomplete feature is enabled. note that the wcag 2.1 success criterion 1.3.5: identify input purpose does not require that autocomplete/autofill actually work - merely that form fields that relate to specific personal user information are programmatically identified. this mean...
Securing your site - Web security
ing used improperly; in addition, you can use it to establish resources that other sites are expressly permitted to use. content security policy an added layer of security that helps to detect and mitigate certain types of attacks, including cross site scripting (xss) and data injection attacks. these attacks are used for everything from data theft to site defacement or distribution of malware. code is executed by the victims and lets the attackers bypass access controls and impersonate users. according to the open web application security project, xss was the seventh most common web app vulnerability in 2017. the x-frame-options response header the x-frame-options: http response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>. site...
current - XPath
outermost expression. thus within all of the following three expressions the current function (not the entire expressions) returns the same node. moreover, the latter two are semantically equivalent. <xsl:value-of select="current()"/> <xsl:value-of select="foo/bar[current() = x]"/> <xsl:variable name="current" select="current()"/> <xsl:value-of select="foo/bar[$current = x]"/> and the next code is also semantically equivalent to the latter two, since the . occurs in an outermost expression. <xsl:variable name="current" select="."/> <xsl:value-of select="foo/bar[$current = x]"/> but the . always relate to the narrowest context. thus in <xsl:value-of select="foo/bar[. = x]"/> the . returns the bar node, which may be different from the current node. defined xslt 1.0 12.4 gecko sup...
XPath
documentation introduction to using xpath in javascript describes a non-xslt use of xpath. xpath:axes list and definition of the axes defined in the xpath specification. axes are used to describe the relationships between nodes. xpath:functions list and description of the core xpath functions and xslt-specific additions to xpath. transforming xml with xslt xslt uses xpath to address code segments in an xml document that it wishes to transform. xpath snippets these are javascript utility functions, that can be used in your own code, based on dom level 3 xpath apis. what is xslt? this extensive introduction to xslt and xpath assumes no prior knowledge of the technologies, and guides the reader through background, context, structure, concepts, and introductory terminology. jxo...
Common XSLT Errors - XSLT: Extensible Stylesheet Language Transformations
t works. however firefox never serializes the output document and so the attribute isn't really applicable. while we could try to add some heuristics to serialize and reparse just the part of the output document which has disable-output-escaping applied, heuristics often get things wrong and lead to surprising results, hence we've been reluctant to add this so far. often times stylesheets contain code like <xsl:text disable-output-escaping="yes">&nbsp;</xsl:text>, this is equivalent to simply putting &#160; in the stylesheet which will work great in all xslt engines. we do realize that the lack of disable-output-escaping is a problem and we'd like to find a solution for it, however so far we haven't found any good solutions. the <xsl:namespace-alias> element. if you'd like to help out with ...
<xsl:number> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › number
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:number> element counts things sequentially. it can also be used to quickly format a number. syntax <xsl:number count=expression level="single" | "multiple" | "any" from=expression value=expression format=format-string lang=xml:lang-code letter-value="alphabetic" | "traditional" grouping-separator=character grouping-size=number /> required attributes none. optional attributes count specifies what in the source tree should be numbered sequentially. it uses an xpath expression. level defines how levels of the source tree should be considered in generating sequential numbers. it has three valid values: single, multiple, and any. the default value is single: sin...
<xsl:sort> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › sort
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:sort> element defines a sort key for nodes selected by <xsl:apply-templates> or <xsl:for-each> and determines the order in which they are processed. syntax <xsl:sort select=expression order="ascending" | "descending" case-order="upper-first" | "lower-first" lang=xml:lang-code data-type="text" | "number" /> required attributes none. optional attributes select uses an xpath expression to specify the nodes to be sorted. order specifies whether the nodes should be processed in "ascending" or "descending" order. the default is "ascending". case-order indicates whether upper- or lowercase letters are to be ordered first. the allowable values are "upper-first" and "lower-...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
advanced example this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). the xslt file has a parameter called myorder that javascript sets to change the sorting method. the xsl:sort element's order attribute can access the value...
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
for example, javascript and xslt could be used to sort xml data and then display it. the sorting would have to alternate between ascending and descending sorting. xslt provides the xsl:param element, which is a child of the xsl:stylesheet element. xsltprocessor provides three javascript methods to interact with these parameters: xsltprocessor.setparameter(), xsltprocessor.getparameter() and xsltprocessor.removeparameter(). ...
Web technology for developers
useful how-to content to help you actually use web technologies to do what you want or need to do. tutorials for web developers a list of tutorials to take you step-by-step through learning apis, technologies, or broad topic areas. developing web applications documentation for web application developers; web apps are true write-once, deploy anywhere apps for mobile, desktop, and firefox os. code snippets this is a quick list of useful code snippets (small code samples) available for developers of extensions for the various mozilla applications. many of these samples can also be used in xulrunner applications, as well as in actual mozilla code itself. view all... web technology references web apis reference material for each of the individual apis that comprise the web's powerfu...
Exported WebAssembly functions - WebAssembly
example in a webassembly-supporting browser, and run the following lines in your console: var testfunc = othertable.get(0); typeof testfunc; you'll get the result function returned. you can then go on to do pretty much anything to this function that you can do to other functions in javascript — call(), bind(), etc. testfunc.tostring() returns an interesting result: function 0() { [native code] } this gives you more of an idea of its wrapper-type nature. some other particulars to be aware of with exported webassembly functions: their length property is the number of declared arguments in the wasm function signature. their name property is the tostring() result of the function's index in the wasm module. if you try to call a exported wasm function that takes or returns an i64 typ...
Converting WebAssembly text format to wasm - WebAssembly
age to set up the tool. once you’ve got the tool built, add the /wabt/out/clang/debug directory to your system path. next, execute the wat2wasm program, passing it the path to the input file, followed by an -o parameter, followed by the path to the output file: wat2wasm simple.wat -o simple.wasm this will convert the wasm into a file called simple.wasm, which contains the .wasm assembly code. note: you can also convert the assembly back into the text representation using the wasm2wat tool; for example wasm2wat simple.wasm -o text.wat. viewing the assembly output because the output file is assembly-based, it can’t be viewed in a normal text editor. however, you can view it using the wat2wasm tool’s -v option. try this: wat2wasm simple.wat -v this will give you an output in ...
onunload - XUL
« xul reference home onunload type: script code specifies a set of scripts to execute when the browser window is closed by the user. this code is used by some programmers to annoyingly pop up alert boxes preventing the users from leaving the page. closing the window calls this eventhandler on the prefwindow. ...