Search completed in 2.99 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.
...And 19 more matches
<code>: The Inline Code element - HTML: Hypertext Markup Language
WebHTMLElementcode
the html <code> element displays its contents styled in a fashion intended to indicate that the text is a short fragment of computer code.
... 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.
...And 4 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().
...And 2 more matches
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.
... 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.
Web audio codec guide - Web media technologies
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.
...And 90 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.
...And 83 more matches
Web video codec guide - Web media technologies
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.
...And 80 more matches
Codecs used by WebRTC - Web media technologies
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.
...which codecs can be within those tracks is not mandated by the webrtc specification.
...And 68 more matches
Bytecode Descriptions
bytecode listing this document is automatically generated from opcodes.h by make_opcode_doc.py.
...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.
...And 58 more matches
The "codecs" parameter in common media types - Web media technologies
for that reason, the codecs parameter can be added to the mime type describing media content.
...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.
...And 51 more matches
Looping code - Learn web development
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.
... 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!
...And 40 more matches
Making decisions in your code — conditionals - Learn web development
overview: building blocks next in any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs.
...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 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.
...And 33 more matches
imgIDecoderObserver
image/public/imgidecoderobserver.idlscriptable this interface is used both for observing imgidecoder objects and for observing imgirequest objects.
... 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.
...decode notifications are fired as the image is decoded.
...And 32 more matches
Functions — reusable blocks of code - Learn web development
previous overview: building blocks next another essential concept in coding is functions, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times.
... 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.
...And 21 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 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.
...And 19 more matches
HTTP response status codes - HTTP
WebHTTPStatus
http response status codes indicate whether a specific http request has been successfully completed.
... the below status codes are defined by section 10 of rfc 2616.
... 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.
...And 18 more matches
Working with windows in chrome code
this article describes working with multiple windows in mozilla chrome code (xul applications and extensions).
... it contains tips and example code on opening new windows, finding an already opened window, and passing data between different windows.
... the window.opendialog function works similarly, but lets you specify optional arguments that can be referenced from the javascript code.
...And 17 more matches
Unicode property escapes - JavaScript
unicode property escapes regular expressions allows for matching characters based on their unicode properties.
...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.
...And 16 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.
...a javascript code module is simply some javascript code located in a registered location.
... 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.
...And 15 more matches
Creating the Component Code
« previousnext » this chapter goes over the basic code required to handle the relationship between your component and xpcom.
... 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.
...there is more code in this chapter than you'll eventually need, however.
...And 14 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().
...And 14 more matches
String.fromCharCode() - JavaScript
the static string.fromcharcode() method returns a string created from the specified sequence of utf-16 code units.
... syntax string.fromcharcode(num1[, ...[, numn]]) parameters num1, ..., numn a sequence of numbers that are utf-16 code units.
... return value a string of length n consisting of the n specified utf-16 code units.
...And 14 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.
...And 12 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).
... syntax encodeuricomponent(str); parameters str string.
... return value a new string representing the provided string encoded as a uri component.
...And 12 more matches
TextEncoder - Web APIs
textencoder takes a stream of code points as input and emits a stream of utf-8 bytes.
... 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.
...And 11 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.
... syntax var code = event.charcode; return value a number that represents the unicode value of the character key that was pressed.
... example html <p>type anything into the input box below to log a <code>charcode</code>.</p> <input type="text" /> <p id="log"></p> javascript let input = document.queryselector('input'); let log = document.queryselector('#log'); input.addeventlistener('keypress', function(e) { log.innertext = `key pressed: ${string.fromcharcode(e.charcode)}\ncharcode: ${e.charcode}`; }); result notes in a keypress event, the unicode value of the key pressed is stored in either the keycode or charcode property, but never both.
...And 10 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).
... 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.
...And 10 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.
...And 10 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.
... 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.
...And 9 more matches
String.fromCodePoint() - JavaScript
the static string.fromcodepoint() method returns a string created by using the specified sequence of code points.
... 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.
...And 9 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).
... syntax encodeuri(uri) parameters uri a complete uri.
... return value a new string representing the provided string encoded as a uri.
...And 9 more matches
JavaScript code 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.
...And 8 more matches
JS_EncodeCharacters
syntax jsbool js_encodecharacters(jscontext *cx, const jschar *src, size_t srclen, char *dst, size_t *dstlen); name type description cx jscontext * a context.
... dst const char * the pointer to an array of bytes to be filled with encoded characters; or null.
... description js_encodecharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values.
...And 8 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.
...And 8 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.
...the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise.
... 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.
...And 8 more matches
imgIEncoder
modules/libpr0n/public/imgiencoder.idlscriptable please add a summary to this article.
... 1.0 66 introduced gecko 1.8 inherits from: nsiasyncinputstream 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 ou...
... apng: ----- the following options can be used with startimageencode(): transparency=[yes|no|none] -- default: "yes" overrides default from input format.
...And 7 more matches
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).
...And 7 more matches
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.
... properties payloadtype optional the rtp payload type used to identify this codec.
...And 7 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.
... 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 6 more matches
Solve common problems in your JavaScript code - Learn web development
common beginner's mistakes correct spelling and casing if your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc.
...for example: function myfunction() { alert('this is my function.'); }; this code won't do anything unless you call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e.
... 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.
...And 6 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...
... 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.
...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.
...And 6 more matches
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.
... 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.
...And 6 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.
...And 6 more matches
Building Firefox with Rust code - Archive of obsolete content
please instead refer to the documentation found within the modern firefox build system documentation; specifically, the section called including rust code in firefox.
... adding rust code we generally target stable rust, but sometimes issues temporarily require a beta or custom toolchain build.
... 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 5 more matches
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.
... 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.
...And 5 more matches
Error codes returned by Mozilla APIs
each error is listed by its name and an error code in parentheses.
... 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_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.
...And 5 more matches
Bytecodes
background spidermonkey bytecodes are the canonical form of code representation that is used in the javascript engine.
... the javascript frontend constructs an ast from the source text, then emits stack-based bytecodes from that ast as a part of the jsscript data structure.
... bytecodes can reference atoms and objects (typically by array index) which are also contained in the jsscript data structure.
...And 5 more matches
JS_EncodeString
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.
... 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).
...And 5 more matches
Mailnews and Mail code review requirements
thunderbird and seamonkey are the primary users of the code in mozilla/mailnews.
... thunderbird's front-end code is stored in mozilla/mail.
... (a fair amount of this code is forked from code in the mailnews/ directory).
...And 5 more matches
TextDecoder() - Web APIs
the textdecoder() constructor returns a newly created textdecoder object for the encoding specified in parameter.
... syntax decoder = new textdecoder(utflabel, options); parameters utflabeloptional is a domstring, defaulting to "utf-8", containing the label of the encoder.
... each label is associated with a specific encoding type: possible values of utflabel encoding "unicode-1-1-utf-8", "utf-8", "utf8" 'utf-8' "866", "cp866", "csibm866", "ibm866" 'ibm866' "csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592", "iso_8859-2", "iso_8859-2:1987", "l2", "latin2" 'iso-8859-2' "csisolatin3", "iso-8859-3", "iso-ir-109", "iso8859-3", "iso88593", "iso_8859-3", "iso_8859-3:1988", "l3", "latin3" 'iso-8859-3' "csisolatin4", "iso-8859-4", "iso-ir-110", "iso8859-4", "iso88594", "iso_8859-4", "iso_8859-4:1988", "l4", "latin4" 'iso-8859-4' "csisolatincyrillic", "cyrillic", "iso-8859-5", "iso-ir-144", "iso88595", "iso_8859-5", "iso_8859-5:1988" 'iso-88...
...And 5 more matches
Writing Web Audio API code that works in every browser - Developer guides
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.
...this little library will "normalise" the interfaces for you and make it look as if your code is running in a standards compliant browser, by aliasing prefixed names to the unprefixed versions.
...And 5 more matches
String.prototype.codePointAt() - JavaScript
the codepointat() method returns a non-negative integer that is the unicode code point value.
... 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.
...And 5 more matches
unicode - SVG: Scalable Vector Graphics
WebSVGAttributeunicode
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.
...And 5 more matches
Loading and running WebAssembly code - WebAssembly
this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it.
...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 quickest, most efficient way to fetch a wasm module is using the newer webassembly.instantiatestreaming() method, which can take a fetch() call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(results => { // do something with the results!
...And 5 more matches
Code Samples - Archive of obsolete content
this page contains sample code that you can use with the custom toolbar button tutorial.
...launch a file on your computer to launch a file on your computer, use code like this.
...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.
...And 4 more matches
Getting SpiderMonkey source code
you can get the spidermonkey source code in gzipped form or directly from the mercurial repository.
... downloading gzipped spidermonkey source code you can download gzipped spidermonkey source code from the following urls: http://ftp.mozilla.org/pub/spidermonkey/releases/ http://ftp.mozilla.org/pub/spidermonkey/prereleases/ here is a command-line example of downloading and unzipping spidermonkey source code version 59.0: mkdir mozilla cd mozilla wget http://ftp.mozilla.org/pub/spidermonkey/prereleases/59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell.
... getting the latest spidermonkey source code from mercurial the mercurial repository at https://hg.mozilla.org/mozilla-central/ hosts the latest spidermonkey sources.
...And 4 more matches
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.
...And 4 more matches
JS_EncodeStringToBuffer
syntax size_t js_encodestringtobuffer(jscontext *cx, jsstring *str, char *buffer, size_t length); name type description cx jscontext * a context.
... str jsstring * a string to encode.
... buffer char * a character buffer to receive encoded string.
...And 4 more matches
JS_SetPrincipalsTranscoder
set the runtime-wide principals transcoder callback.
...syntax jsprincipalstranscoder js_setprincipalstranscoder(jsruntime *rt, jsprincipalstranscoder px); name type description rt jsruntime * the runtime to configure.
... px jsprincipalstranscoder the new principals transcoder.
...And 4 more matches
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.
...init() initializes an image decoder.
...And 4 more matches
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.
...instead, you should use keyboardevent.code, if it's implemented.
...And 4 more matches
decodeURI() - JavaScript
the decodeuri() function decodes a uniform resource identifier (uri) previously created by encodeuri() or by a similar routine.
... 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).
...And 4 more matches
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.
...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.
...And 3 more matches
HTMLImageElement.decode() - Web APIs
the decode() method of the htmlimageelement interface returns a promise that resolves when the image is decoded and it is safe to append the image to the dom.
... syntax var promise = htmlimageelement.decode(); parameters none.
... 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.
...And 3 more matches
MediaError.code - Web APIs
WebAPIMediaErrorcode
the read-only property mediaerror.code returns a numeric value which represents the kind of error that occurred on a media element.
... 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.
...And 3 more matches
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.
...And 3 more matches
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.
...And 3 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.
... 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.
...And 3 more matches
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.
... 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.
...And 3 more matches
decodeURIComponent() - JavaScript
the decodeuricomponent() function decodes a uniform resource identifier (uri) component previously created by encodeuricomponent or by a similar routine.
... 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.
...And 3 more matches
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.
...And 3 more matches
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.
...this only works from privileged code, so web content can't do it.
...if you pass a path to the file constructor from unprivileged code (such as web content), an exception will be thrown.
...And 2 more matches
Measuring performance using the PerfMeasurement.jsm code module
the perfmeasurement.jsm javascript code module lets you take detailed performance measurements of your code.
... note: the perfmeasurement.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on.
...now we want to benchmark a function that is pretty 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.
...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.
... sample code 3 /* nspr headers */ #include <prthread.h> #include <plgetopt.h> #include <prerror.h> #include <prinit.h> #include <prlog.h> #include <prtypes.h> #include <plstr.h> /* nss headers */ #include <keyhi.h> #include <pk11priv.h> /* our samples utilities */ #include "util.h" #define buffersize 80 #define digestsize 16 #define ptext_mac_buffer_size 96 #define ciphersize 96 #define blocksize 32 #define cipher_header "-----begin cipher-----" #define cipher_trailer "-----end cipher-----" #define enckey_header "-----begin aeskey ckaid-----" #define enckey_trailer "-----end aeskey ckaid-----" #define mackey_header "-----begin mackey ckaid-----" #define mackey_trailer "-----end mackey ckaid-----" #...
... "note :"); fprintf(stderr, "%-7s <ipfilename>.enc and <ipfilename>.header as intermediate output files.\n\n", ""); fprintf(stderr, "%-7s for decrypt, it takes <ipfilename>.enc and <ipfilename>.header\n", ""); fprintf(stderr, "%-7s as input files and produces <opfilename> as a final output file.\n\n", ""); exit(-1); } /* this source code form is subject to the terms of the mozilla public * license, v.
...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.
... */ #include "nss.h" #include "pk11pub.h" #define base64_encoded_subjectpublickeyinfo "mfwwdqyjkozihvcnaqebbqadswawsajbal3f6tic3jeysugo+a2fpu3w+epv/feix21dc86wynpftw4srftz2onuzyluzdhzdb+k//8dct3iaozuui3r2emcaweaaq==" #define base64_encoded_privatekeyinfo "miibvqibadanbgkqhkig9w0baqefaascat8wgge7ageaakeavcxpmhzckriy6cj5rz89tdb4sm/8v4hfbumlzpziekw1biysw3pag1tpittmmdl1v6t//x1xpcga7nrsldhz4widaqabakeajh8+4qncwcmgivnm6ytbpqt+k/jeoexg2bqhjojvnxn3fazgcefxvpuibcjvfaijs9ybcmozzrato0+k2hwnoqihaoc4nvbo8fqhzs4yxm1m86kml47fa9ui//oufbhladw1aiea2dbmixnsbokb+ohver69p0gnewlvcjc9bjdvfdlvslcciqcptv3...
...And 2 more matches
Testing Mozilla code
testing your code is important!
... before you can even get your code committed into the source tree, you have to test it, and larger patches have to have automated tests.
... these articles will help you master (and continue to excel at) testing mozilla code.
...And 2 more matches
Finding the code for a feature
frequently you are trying to figure out the code that implements a specific feature of the user interface.
...i know the underlying code, but i don't remember the user interface level function to do it.
...the second is mozilla's source code search tool mxr.
...And 2 more matches
AddressErrors.regionCode - Web APIs
an object based on addresserrors includes a regioncode property when the address's regioncode property couldn't be validated.
... 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.
...And 2 more matches
BasicCardResponse.cardSecurityCode - Web APIs
the cardsecuritycode property of the basiccardresponse dictionary contains the security code of the card used to make the payment.
... syntax "cardsecuritycode" : "number" value a domstring representing the card security code.
...dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc.
...And 2 more matches
BlobEvent.timecode - Web APIs
the timecode readonlyinline property of the blobevent interface 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.
... syntax var timecode = blobevent.timecode value a domhighrestimestamp.
...And 2 more matches
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.
...And 2 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?
... string.fromcodepoint() throws this error when passed nan values, negative integers (-1), non-integers (5.4), or values larger than 0x10ffff (1114111).
...And 2 more matches
Canvas code snippets - Archive of obsolete content
code usable from web content getting the number of pixels of a certain color in a canvas the following function will return the number of pixels in a canvas that have the rgb color of r, g and b.
...ent.getelementbyid('canvas'); // use context to get access to underlying context var ctx = canvas2dcontext(canvas) .strokestyle('rgb(30, 110, 210)') .transform(10, 3, 4, 5, 1, 0) .strokerect(2, 10, 15, 20) .context; // use property name as a function (but without arguments) to get the value var strokestyle = canvas2dcontext(canvas) .strokestyle('rgb(50, 110, 210)') .strokestyle(); code usable only from privileged code these snippets are only useful from privileged code, such as extensions or privileged apps.
...if you try running the code as a plain webpage, you will get a 'security error" code: "1000' error.
...x.scale(remotecanvas.canvas_width / windowwidth, remotecanvas.canvas_height / windowheight); ctx.drawwindow(remotewindow, 0, 0, windowwidth, windowheight, 'rgb(255, 255, 255)'); ctx.restore(); }; usage: var remotecanvas = new remotecanvas(); remotecanvas.load(); convert image files to base64 strings the following code gets a remote image and converts its content to data uri scheme.
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.
... this date-picker code snippet will automatically create an html code like the following: <table id="zdp-cal-1" class="zdp-calendar" style="z-index: 1026; position: absolute; left: 294px; top: 47px;"> <caption><span id="zdp-decr-year-1" class="zdp-decrease-year">&laquo;</span><span id="zdp-decr-month-1" class="zdp-decrease-month">&lt;</span><span id="zdp-incr-year-1" class="zdp-increase-year">&raquo;</span><span id...
...for a full compatibility code you can see our crossbrowser possible solution for image preview.
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.
... 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.
... 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.
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
unicode is a standard character set that numbers and defines characters from the world's different languages, writing systems, and symbols.
... before unicode, it was difficult and error-prone to mix languages in the same data.
... the most common unicode character encoding on the web is utf-8.
... learn more unicode on wikipedia the unicode standard: a technical introduction ...
Writing localizable code
this page tells you about best practices and guidelines when dealing with ui code with respect to localization.
... 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.
...in most cases, you can just as well put the processing into the content code and reference different key-value pairs in l10n.
...using a directory structure like this eases the localization process without the source code and is especcially recommended to extension authors.
PRErrorCode
type for error codes that can be retrieved with pr_geterror.
... 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.
...at present less than 100 error codes have been defined.
... for nspr errors, see error codes.
NSS Sample Code Sample1
nss sample code 1: key generation and transport between servers.
...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.
...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...
...ble (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 *wrappedenckey = data; data = 0; done: if (data) secitem_freeitem(data, pr_true); if (pubkey) seckey_destroypublickey(pubkey); if (keyinfo) seckey_destroysubjectpublickeyinfo(keyinfo); return rv; } int server::importkeys(secitem *wrappedenckey, secitem *wrap...
NSS Sample Code sample2
nss sample code 2: symmetric encryption /* example code to illustrate des enccryption/decryption using nss.
... * the example skips the details of obtaining the key & iv to use, and * just uses a hardcoded key & iv.
... 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.....
Step through code - Firefox Developer Tools
ch case enter the function being called step out: run to the end of the current function, in which case, the debugger will skip the return value 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.
... 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.
AddressErrors.languageCode - Web APIs
an object based on addresserrors includes a languagecode property when the address's languagecode property couldn't be validated.
... 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.
... 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.
AddressErrors.postalCode - Web APIs
an object based on addresserrors includes a postalcode property when the address's postalcode property couldn't be validated.
... 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.
AddressErrors.sortingCode - Web APIs
an object based on addresserrors includes a sortingcode property when the address's sortingcode property couldn't be validated.
... 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.
DOMException.code - Web APIs
WebAPIDOMExceptioncode
the code read-only property of the domexception interface returns a short that contains one of the error code constants, or 0 if none match.
... syntax var domexceptioncode = domexceptioninstance.code; value a short number.
... specifications specification status comment web idlthe definition of 'code' in that specification.
... desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetcodechrome full support yesedge full support 12firefox full support 1ie ?
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.
msExtendedCode - Web APIs
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; //...
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.
... 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.
... if ("decodedbodysize" in perfentry) console.log("decodedbodysize = " + perfentry.decodedbodysize); else console.log("decodedbodysize = not supported"); if ("encodedbodysize" in perfentry) console.log("encodedbodysize = " + perfentry.encodedbodysize); else console.log("encodedbodysize = not supported"); if ("transfersize" in perfentry) console.log("transfersize = " + perfentry.transfersize); else console.log("transfersize = not supported"); } function check_performanceentries() { // use getentriesbytype() to just get the "resourc...
...e" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { log_sizes(p[i]); } } specifications specification status comment resource timing level 2the definition of 'decodedbodysize' in that specification.
PerformanceResourceTiming.encodedBodySize - Web APIs
the encodedbodysize read-only property represents the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings.
... 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.
... if ("decodedbodysize" in perfentry) console.log("decodedbodysize = " + perfentry.decodedbodysize); else console.log("decodedbodysize = not supported"); if ("encodedbodysize" in perfentry) console.log("encodedbodysize = " + perfentry.encodedbodysize); else console.log("encodedbodysize = not supported"); if ("transfersize" in perfentry) console.log("transfersize = " + perfentry.transfersize); else console.log("transfersize = not supported"); } function check_performanceentries() { // use getentriesbytype() to just...
... get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { log_sizes(p[i]); } } specifications specification status comment resource timing level 2the definition of 'encodedbodysize' in that specification.
Textures from code - Web APIs
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.
...experimental-webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
The Unicode Bidirectional Text Algorithm - Developer guides
the unicode® bidirectional algorithm (also known as the bidi algorithm) is part of the unicode text standard that describes how the user agent should order characters while rendering unicode text.
... overiding bidi using unicode control characters unicode provides a number of special control characters that make it possible to control directionality of ranges of text.
... initial unicode bidi algorithm control characters character code point html entity markup equivalent description left-to-right isolate (lri) u+2066 &#x2066; dir="ltr" sets the base direction to ltr, isolating the embedded content from the surrounding text right-to-left isolate (lri) u+2067 &#x2067; dir="rtl" sets the base direction to rtl, isolating the embedded content from the surrounding text first strong isolate (fsi) u+2068 &#x2068; dir="auto" isolates the content and sets the base direction accord...
...lover effects left-to-right override (lro) u+202d &#x202d; <bdo dir="ltr"> overrides the bidi algorithm, displaying the characters in memory order, from left to right right-to-left override (rlo) u+202e &#x202e; <bdo dir="rtl"> overrides the bidi algorithm and displays the embedded characters in reverse memory order, from right to left closing unicode bidi algorithm control characters character code point html entity markup equivalent description pop directional formatting (pdf) u+202c &#x202c; closing whatever opening tag used the dir attribute used for rle or lre </bdo> used for rlo or lro pop directional isolate (pdi) u+2069 &#x2069; closing whatever opening tag used...
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.
Static Analysis for Windows Code under Linux - Archive of obsolete content
this document will describe how to run mozilla static check for windows code under linux platform by creating a cross-compiler with dehydra support for mingw.
... check the build run: make check_treehydra run static analysis on mozilla windows code static analysis is hooked into mozilla repository from mozilla 2.
... you can obtain mozilla 2 code by: hg clone http://hg.mozilla.org/mozilla-central/ and compose a .mozconfig file for cross-compiling mozilla with static analysis hooked: #specify the cross compile cross_compile=1 ac_add_options --enable-application=browser ac_add_options --host=i686-linux ac_add_options --target=i686-mingw32 ac_add_options --enable-default-toolkit=cairo-windows mk_add_options moz_objdir=@topsrcdir@/../mozilla-mingw # mozilla trunk uses many vista only features on windows, so we should disable some components to make it buildable with mingw32.
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.
...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.
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.
... learn more general knowledge codec on wikipedia technical reference web video codec guide web audio codec guide guide to media types and formats on the web ...
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.
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.
... open the client.xcodeproj file in xcode.
... xcode will import your translated strings into the project by adding them to the project folder and replacing the existing strings.
NSS Sample Code sample6
nss sample code 6: persistent symmetric keys in nss database /* example code to illustrate generation of a secret symmetric key ring * that persists in the nss database.
...for example purposes, this function hardcodes the password.
... * error code: token is read-only.
GeolocationPositionError.code - Web APIs
the geolocationpositionerror.code read-only property is an unsigned short representing the error code.
... syntax let typeerr = geolocationpositionerrorinstance.code value an unsigned short representing the error code.
... specifications specification status comment geolocation apithe definition of 'positionerror.code' in that specification.
NavigatorID.appCodeName - Web APIs
the value of the navigatorid.appcodename property is always "mozilla", in any browser.
... syntax codename = navigator.appcodename value the string "mozilla".
... specifications specification status comment html living standardthe definition of 'navigatorid.appcodename' in that specification.
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.
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.
... specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.framesdecoded' in that specification.
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.
... specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.framesencoded' in that specification.
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.
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.
... html living standardthe definition of 'decode()' in that specification.
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.
TextDecoder.prototype.encoding - Web APIs
the textdecoder.prototype.encoding read-only property returns a domstring containing the name of the decoding algorithm used by the specific decoder.
... a special encoding, 'replacement', which only emits an error and an eof code point.
... syntax var b = decoder.decoding; specifications specification status comment encodingthe definition of 'textdecoder.encoding' in that specification.
Return Codes - Archive of obsolete content
return codes the methods described in this chapter can return any of the following return codes.
... name code explanation success 0 success.
privileged code - MDN Web Docs Glossary: Definitions of Web-related terms
privileged code - javascript code of your extension.
... for example, code in content scripts.
Using workers in JavaScript code modules
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.
NSS Sample Code Sample_1_Hashing
nss sample code 1: hashing a file.
... 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.
NSS Sample Code Sample_2_Initialization of NSS
nss sample code 2: initializing nss this example program demonstrates how to initialize the nss database.
... sample code 1 /* nspr headers */ #include <prthread.h> #include <plgetopt.h> #include <prprf.h> /* nss headers */ #include <nss.h> #include <pk11func.h> #include "util.h" /* print a usage message and exit */ static void usage(const char *progname) { fprintf(stderr, "\nusage: %s -d <dbdirpath> [-p <plainpasswc>]" " [-f <passwdffile>]\n\n", progname); fprintf(stderr, "%-15s specify a db directory path\n\n", "-d <dbdirpath>"); fprintf(stderr, "%-15s specify a plaintext password\n\n", "-p <plainpasswc>"); fprintf(stderr, "%-15s specify a password file\n\n", "-f <plainpasswc>"); exit(-1); } /* initialize the slot password */ char *initslotpassword(p...
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.
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.
... * this code uses the simplest of the init functions, which does not * require a nss database to exist */ nss_nodb_init("."); /* get a slot to use for the crypto operations */ slot = pk11_getinternalkeyslot(); if (!slot) { cout << "getinternalkeyslot failed" << endl; status = 1; goto done; } /* * part 1 - simple hashing */ cout << "part 1 -- simple hashing" << endl; /* initialize data */ memset(data, 0xbc, sizeof data); /* create a context for hashing (digesting) */ context = pk11_createdigestcontext(sec_oid_md5); if (!context) { cout << "createdigestcontext failed" << endl; goto done; } s = pk11_digestbegin(context); if (s != secsuccess) { cout << "digestbegin failed" << endl; goto done; } s = pk11_digestop(context, data, sizeo...
NSS Sample Code sample4
nss sample code 4: pki encryption /* example code to illustrate pki crypto ops (encrypt with public key, * decrypt with private key) * * code assumes that you have set up a nss database with a certificate * and a private key.
...for example purposes, this function hardcodes the password.
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.
... 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.
NSS Third-Party Code
this is a list of third-party code included in the nss repository, broken into two lists: code that can be compiled into the nss libraries, and code that is only used for testing.
... note that not all code that can be compiled into the nss libraries necessarily is.
Using JS in Mozilla code
js language features that are implemented in the mozilla js engine are ordinarily safe to use in mozilla code.
... 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.
Using Mozilla code in other projects
there are several ways you can use mozilla code in your own project.
... signing mozilla apps for mac os x how to code-sign applications based on mozilla code for mac os x's application security model.
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.
... 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".
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.
... syntax b = encoder.encoding; specifications specification status comment encodingthe definition of 'textencoder.encoding' in that specification.
XPathException.code - Web APIs
the code read-only property of the xpathexception interface returns a short that contains one of the error code constants.
... syntax var exceptioncode = exception.code; value a short number representing the error code.
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.
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'unicode-range' in that specification.
Finding the code to modify - Archive of obsolete content
dom inspector now that we've found the file to edit, we need to find the specific code within that file.
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.
Code Samples
getting the directory where your add-on is located if you need to determine the directory in which your add-on is installed, code like the following will do the trick.
NSS Code Coverage
nss - code coverage results link 2007-08-14 - solaris/sparc platform results explanation files results from every c file are on new line.
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 ...
Key Values - Web APIs
corresponding virtual keycodes for common platforms are included where available.
... 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.
... keyboardevent.key value description virtual keycode windows mac linux android "alt" [5] the alt (alternative) key.
...And 197 more matches
Index - Web APIs
WebAPIIndex
found 5328 pages: # page tags and summary 1 web apis api, dom, landing, reference, web when writing code for the web, there are a large number of web apis available.
... 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.
... 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.
...And 186 more matches
Index - Archive of obsolete content
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.
... 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.
...And 143 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...
... 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.
...And 97 more matches
Document - Web APIs
WebAPIDocument
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.
...And 86 more matches
Index
found 550 pages: # page tags and summary 1 spidermonkey: the mozilla javascript runtime spidermonkey standalone source code releases can be found on the releases page.
...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 76 more matches
GlobalEventHandlers - Web APIs
globaleventhandlers.onabort is an eventhandler representing the code to be called when the abort event is raised.
... 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.
...And 75 more matches
Index
MozillaTechXPCOMIndex
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.
...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.
... 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.
...And 71 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
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".
... 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.
...And 61 more matches
HTTP Index - HTTP
WebHTTPIndex
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.
... 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.
...it lets the client know how to decode in order to obtain the media-type referenced by the content-type header.
...And 61 more matches
Handling common JavaScript problems - Learn web development
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()).
... 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.
...And 60 more matches
Index
instead, the programmer will use lookup functions, and nss will provide an access handle that will be subsequently used by the application's code.
...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.
...And 56 more matches
Mozilla internal string guide
most 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).
...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.
...And 54 more matches
Introducing a complete toolchain - Learn web development
in this article we'll introduce the case study, set up our development environment, and set up our code transformation tools.
...many of today's code editors (such as vs code and atom) have integration support for a lot of tools via plugins.
... parcel to build and minify our code, and to write a bunch of configuration file content automatically for us.
...And 50 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.
... 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.
...And 48 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.
... 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.
...And 48 more matches
nsIVariant
inherits from: nsisupports last changed 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!
...And 46 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 .
...And 44 more matches
Mozilla
the articles below include content about downloading and building mozilla code.
... in addition, you'll find helpful articles about how the code works, how to build add-ons for mozilla applications and the like.
...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.
...And 44 more matches
What is JavaScript? - Learn web development
(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.
...e can add some javascript to implement dynamic behaviour: const para = document.queryselector('p'); para.addeventlistener('click', updatename); function updatename() { let name = prompt('enter a new name'); para.textcontent = 'player 1: ' + name; } try clicking on this last version of the text label to see what happens (note also that you can find this demo on github — see the source code, or run it live)!
... running code in response to certain events occurring on a web page.
...And 43 more matches
sslfnc.html
use pr_geterror to retrieve the error code.
...use pr_geterror to retrieve the error code.
...use pr_geterror to retrieve the error code.
...And 41 more matches
Digital audio concepts - Web media technologies
representing audio in digital form involves a number of steps and processes, with multiple formats available both for the raw audio and the encoded or compressed audio which is actually used on the web.
... this guide is an overview examining how audio is represented digitally, and how codecs are used to encode and decode audio for use on the web.
...the audio bandwidth is also affected by the codec, if it chooses to discard any frequency bands while encoding the sound.
...And 40 more matches
JSAPI User Guide
these programs can execute javascript code from c++ using the spidermonkey api.
...it also makes it easy for each application to expose some of its own objects and functions to javascript code.
... c++ code accesses spidermonkey via the jsapi, by including the header "jsapi.h".
...And 39 more matches
nsIPluginHost
inherits from: nsisupports 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!
...And 39 more matches
WebIDL bindings
the webidl bindings are generated at build time based on two things: the actual webidl file and a configuration file that lists some metadata about how the webidl should be reflected into gecko-internal code.
... all the generated code is placed in the mozilla::dom namespace.
...mpl_cycle_collecting_release(myclass) ns_interface_map_begin_cycle_collection(myclass) ns_wrappercache_interface_map_entry ns_interface_map_entry(nsisupports) ns_interface_map_end if your class doesn't inherit from a class that implements getparentobject, then add a function of that name that, for a given instance of your class, returns the same object every time (unless you write explicit code that handles your parent object changing by reparenting js wrappers, as nodes do).
...And 38 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.
...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.
...And 38 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
an open-source software license is a statement that anyone is free to use your source code in whatever way they want.
...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.
...the user is free to use (duplicate, distribute, and modify) the source code, following certain conditions.
...And 37 more matches
Graceful asynchronous programming with Promises - Learn web development
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.
...and of course, it's nice that it doesn't block the rest of the code execution.
... the code that the video chat application would use might look something like this: function handlecallbutton(evt) { setstatusmessage("calling..."); navigator.mediadevices.getusermedia({video: true, audio: true}) .then(chatstream => { selfviewelem.srcobject = chatstream; chatstream.gettracks().foreach(track => mypeerconnection.addtrack(track, chatstream)); setstatusmessage("conne...
...And 37 more matches
TypeScript support in Svelte - Learn web development
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/07-typescript-support or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/07-typescript-support remember to run npm install && npm run dev to start your app ...
...one of the big benefits is enabling ides to provide a richer environment for spotting common errors as you type the code.
... best of all, javascript code is valid typescript code; typescript is a superset of javascript.
...And 37 more matches
imgIContainer
as a service: var imgicontainer = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.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!
...And 37 more matches
A first splash into JavaScript - Learn web development
you won't be expected to understand all of the code in detail immediately — we just want to introduce you to the high-level concepts for now, and give you an idea of how javascript (and other programming languages) work.
... note: many of the code features you'll see in javascript are the same as in other programming languages — functions, loops, etc.
... the code syntax looks different, but the concepts are still largely the same.
...And 36 more matches
Client-side tooling overview - Learn web development
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.
... 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.
...And 36 more matches
Signing an XPI - Archive of obsolete content
introduction this article describes how to sign your own firefox extensions with a code-signing certificate on a windows platform.
... 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.
... c:\projects\codesigning\> certutil -n -d .
...And 34 more matches
Making asynchronous programming easier with async and await - Learn web development
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.
... prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals, an understanding of async code in general and promises.
...And 34 more matches
Debugger.Object - Firefox Developer Tools
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.
...And 33 more matches
Mozilla Crypto FAQ - Archive of obsolete content
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.
...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.
...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.
...And 32 more matches
Python binding for NSS
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.
... error codes are never returned from methods/functions.
...the exact error code, error description, and often contextual error information will be present in the exception object.
...And 32 more matches
NSS functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions nss_getclientauthdata mxr 3.2 and later nss_setdomesticpolicy mxr 3.2 and later nss_setexportpolicy mxr 3.2 and later nss_setfrancepolicy mxr 3.2 and later nssssl_versioncheck mxr 3.2.1 and later ssl_authcertificate mxr 3.2 and later ssl_authcertificatehook mxr 3.2 and later ssl_badcerthook mxr 3.2 and later ssl_certdbhandleset mxr 3.2 and later ssl_canbypass mxr 3.11.7 and later ssl_cipherpolicyget mxr 3.2 and later ssl_cipherpolicyset mxr 3.2 and later ssl_cip...
...the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
...And 32 more matches
Tracing JIT
the nanojit component is language agnostic, and contains no knowledge about spidermonkey or any other part of the mozilla codebase.
...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 monitor then calls into the native code stored in the fragment.
...And 32 more matches
Shell global objects
evaluate(code[, options]) evaluate code as though it were the contents of a file.
...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 columnnumber starting column number for error messages and debug info global global in which to execute the code newcontext if true, create and use a new cx (default: false) catchtermination if true, catch termination (failure without 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.
... elementattributename if present and not undefined, the name of property of element that holds this code.
...And 32 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.
... 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.
...And 32 more matches
Drawing graphics - Learn web development
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.
... add the following code into it, just below the opening <body> tag: <canvas class="mycanvas"> <p>add suitable fallback here.</p> </canvas> we have added a class to the <canvas> element so it will be easier to select if we have multiple canvases on the page, but we have removed the width and height attributes for now (you could add them back in if you wanted, but we will set them using javascript in a below secti...
... 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).
...And 31 more matches
nsIJSON
dom/interfaces/json/nsijson.idlscriptable this interface provides a convenient way to encode and decode json strings from javascript code.
... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) note: this interface may only be used from javascript code, with the exception of the legacydecodetojsval() method.
... jsobject decode(in astring str); obsolete since gecko 7.0 jsval decodetojsval(in astring str, in jscontext cx); native code only!
...And 30 more matches
Debugger.Frame - Firefox Developer Tools
debugger code can add its own properties to a frame object and expect to find them later, use == to decide whether two expressions refer to the same frame, and so on.
... (if more than one debugger instance is debugging the same code, each debugger gets a separate debugger.frame instance for a given frame.
... this allows the code using each debugger instance to place whatever properties it likes on its debugger.frame instances, without worrying about interfering with other debuggers.) when the debuggee pops a stack frame (say, because a function call has returned or an exception has been thrown from it), the debugger.frame instance referring to that frame becomes inactive: its live property becomes false, and accessing its other properties or calling its methods throws an exception.
...And 30 more matches
Strict mode - JavaScript
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.
...And 30 more matches
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
« 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.
... introduction javascript lacks functions for opening files and character-code conversion, among other things.
... 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.
...And 29 more matches
SpiderMonkey Internals
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.
... 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.
...And 29 more matches
mozIStorageBindingParams
method 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!
...And 29 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.
... 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.
...And 29 more matches
DOMException - Web APIs
properties domexception.code read only returns a short that contains one of the error code constants, or 0 if none match.
... 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.
...(legacy code value: 1 and legacy constant name: index_size_err) hierarchyrequesterror the node tree hierarchy is not correct.
...And 29 more matches
LiveConnect Overview - Archive of obsolete content
this chapter describes using liveconnect technology to let java and javascript code communicate with each other.
... table 9.1 the liveconnect objects object description javaarray a wrapped java array, accessed from within javascript code.
... javaobject a wrapped java object, accessed from within javascript code.
...And 28 more matches
Index - Learn web development
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!
...And 28 more matches
nsITextInputProcessor
you can create an instance of this interface with the following code: var tip = components.classes["@mozilla.org/text-input-processor;1"].
... code: "enter", // optional.
... keycode: keyboardevent.dom_vk_return, // required if printable key, but optional if non-printable key.
...And 28 more matches
Deploying our app - Learn web development
we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process.
... 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.
...And 27 more matches
Signaling and video calling - Web APIs
note: if you try out the example on glitch, please note that any changes made to the code will immediately reset any connections.
... to allow the server to support signaling and ice negotiation, we need to update the code.
...this involves a change near the end of the "connection" message handler: if (sendtoclients) { var msgstring = json.stringify(msg); var i; if (msg.target && msg.target !== undefined && msg.target.length !== 0) { sendtooneuser(msg.target, msgstring); } else { for (i=0; i<connectionarray.length; i++) { connectionarray[i].send(msgstring); } } } this code now looks at the pending message to see if it has a target property.
...And 27 more matches
sslerr.html
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.
...And 26 more matches
XPIDL
string only chars in range \u0000-\u00ff permitted most of the time you don't want 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.
... nsqiresult void* void** object should only be used with methods that act like queryinterface autf8string const nsacstring& nsacstring& string full unicode set permitted (translated to utf-8) acstring const nsacstring& nsacstring& string only chars in range \u0000-\u00ff permitted astring const nsastring& nsastring& string full unicode set permitted jsval const jsval& jsval* anything jsid jsid jsid* not allowed promise mozilla::dom::promise* mozilla:...
...the only constants supported are those which become integer types when compiled to source code; string constants and floating point constants, though parseable, cannot be made into a header or xpt file.
...And 26 more matches
Debugger - Firefox Developer Tools
this property gives debugger code a single point of control for disentangling itself from the debuggee, regardless of what sort of events or handlers or “points” we add to the interface.
... allowunobservedasmjs a boolean value indicating whether asm.js code running inside this debugger instance’s debuggee globals is invisible to debugger api handlers and breakpoints.
... setting this to false inhibits the ahead-of-time asm.js compiler and forces asm.js code to run as normal javascript.
...And 26 more matches
Lexical grammar - JavaScript
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+feff byte order mark <bom> used at the start of the script to mark it as unicode and the text's byte order (wikipedia).
...these characters are usually unnecessary for the functionality of the code.
...And 26 more matches
Getting started with HTML - Learn web development
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.
...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...
...tion; 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', updatecode); window.addeventlistener('load', updatecode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keycode === 9) { e.preventdefault(); insertatcaret('\t'); } if (e.keycode === 27) { textarea.blur(); } }; function insertatcaret(text...
...And 25 more matches
Client-Server Overview - Learn web development
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.
... 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!
...And 25 more matches
Server-side web frameworks - Learn web development
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.
...And 25 more matches
Migrating from webkitAudioContext - Web APIs
it was first implemented in webkit, and some of its older parts were not immediately removed as they were replaced in the specification, leading to many sites using non-compatible code.
... in this article, we cover the differences in web audio api since it was first implemented in webkit and how to update your code to use the modern web audio api.
... 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.
...And 25 more matches
Client-side storage - Learn web development
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.
...we need to create this and write our javascript code into it.
...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.
...And 24 more matches
Debugging on Mac OS X
this document explains how to debug mozilla-derived applications such as firefox, thunderbird, and seamonkey on macos using xcode.
...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.
...And 24 more matches
Hacking Tips
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 ---- ---- ----- ------ -------- ------ 0: 1 0 [ 0] newline 1: 2 0 [ 0] colspan 2 3: 2 2 [ 2] colspan 9 getting the bytecode of a function (from gdb) in jsopcode.cpp, a function named js::disassembleatpc can print the bytecode of a script.
...And 24 more matches
nsIFile
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.
...And 24 more matches
Debugger.Object - Firefox Developer Tools
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.
...And 24 more matches
Introduction to events - Learn web development
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.
... 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.
...And 23 more matches
Creating localizable web applications
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.
...And 23 more matches
JS::CompileOptions
const char *filename() const returns filename of the source code.
... methods of js::owningcompileoptions method description jsobject *element() const returns the dom element to which this source code belongs, if any, or null if it belongs to no dom element.
... utf8 bool true if the character set of the source code is utf-8.
...And 23 more matches
Index - Firefox Developer Tools
8 dom inspector internals code, tools, internals, organisation, source there are three main facets to dom inspector.
... 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.
... 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.
...And 23 more matches
Tabbed browser - Archive of obsolete content
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.
... each snippet normally includes some code to run at initialization, these are best run using a load listener.
...And 22 more matches
Handling common HTML and CSS problems - Learn web development
previous overview: cross browser testing next 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, handling css prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
... 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.
...And 22 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.
...And 22 more matches
WebAssembly Concepts - 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.
... 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.
...And 22 more matches
JavaScript Object Management - Archive of obsolete content
« previousnext » chrome javascript in this section we'll look into how to handle javascript data effectively, beginning with chrome code, in ways which will prevent pollution of shared namespaces and conflicts with other add-ons resulting from such global namespace pollution.
... the first step to good javascript object management is having a namespace, or a javascript object that contains our code and data, that you know will not conflict with firefox code or other extensions.
... you usually need only one js file to control a xul window, since the code required is normally not that much.
...And 21 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
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.
...// 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.
...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 21 more matches
HTML text fundamentals - Learn web development
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.
...</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...
...tion; 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 cardboard and i am married to a fish.</p>'; var solutionentry = htmlsolution; textarea.addeventlistener('input', updatecode); window.addeventlistener('load', updatecode); // stop tab key tabbing out of textarea and // make it write a tab at the caret position instead textarea.onkeydown = function(e){ if (e.keycode === 9) { e.preventdefault()...
...And 21 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 test, you use the get() method of the driver instance you created earlier, for example: driver.get('http://www.google.com'); note: see the webdriver class reference for details of the 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.
...And 21 more matches
nsIWindowMediator
components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); method overview void addlistener(in nsiwindowmediatorlistener alistener); boolean calculatezposition(in nsixulwindow inwindow, in unsigned long inposition, in nsiwidget inbelow, out unsigned long outposition, out nsiwidget outbelow); native code only!
... nsisimpleenumerator getenumerator(in wstring awindowtype); nsidomwindow getmostrecentwindow(in wstring awindowtype); nsidomwindow getouterwindowwithid(in unsigned long long aouterwindowid); nsisimpleenumerator getxulwindowenumerator(in wstring awindowtype); pruint32 getzlevel(in nsixulwindow awindow); native code only!
... nsisimpleenumerator getzorderdomwindowenumerator(in wstring awindowtype, in boolean afronttoback); nsisimpleenumerator getzorderxulwindowenumerator(in wstring awindowtype, in boolean afronttoback); void registerwindow(in nsixulwindow awindow); native code only!
...And 21 more matches
Introduction to XPCOM for the DOM
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.
... target audience: people who would like a quick introduction to the use of c++ and xpcom in the dom code.
...And 20 more matches
nsIPrincipal
method overview short canenablecapability(in string capability); native code only!
... void checkmayload(in nsiuri uri, in boolean report); void disablecapability(in string capability, inout voidptr annotation); native code only!
... void enablecapability(in string capability, inout voidptr annotation); native code only!
...And 20 more matches
Writing WebSocket servers - Web APIs
this means that you don't have to bloat your server code with cookie and authentication handlers (for example).
... 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).
...And 20 more matches
eval() - JavaScript
it is far too easy for a bad actor to run arbitrary code when you use eval().
... the eval() function evaluates javascript code represented as a string.
... return value the completion value of evaluating the given code.
...And 20 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
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.
...the code in listing 1 is a sample javascript script which incorporates java classes to handle the database query.
... * from employee" ); // get the metadata from the resultset var meta = rs.getmetadata(); // loop over the records, dump out column names and values while( rs.next() ) { for( var i = 1; i <= meta.getcolumncount(); i++ ) { print( meta.getcolumnname( i ) + ": " + rs.getobject( i ) + "\n" ); } print( "----------\n" ); } // cleanup rs.close(); stmt.close(); conn.close(); this code starts off by using a rhino function named importpackage which is just like using the import statement in java.
...And 19 more matches
JavaScript basics - Learn web development
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.
... 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.
... 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.
...And 19 more matches
Advanced text formatting - Learn web development
here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.
... 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.
...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 19 more matches
Useful string methods - Learn web development
such code could be used to filter strings.
...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.
...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.
...And 19 more matches
Introduction to the server side - Learn web development
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.
... perhaps the most significant benefit of server-side code is that it allows you to tailor website content for individual users.
... 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.
...And 19 more matches
Eclipse CDT Manual Setup
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.
...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.
... important background to help you make sense of the instructions that follow (and so that you can modify them to meet your own needs if necessary), this section provides some background on what ides need in order to provide advanced code assistance, and what eclipse cdt needs in particular.
...And 19 more matches
Using XPCOM Utilities to Make Things Easier
« previousnext » this chapter goes back over the code you've already created in the first part of the tutorial (see weblock1.cpp in the previous chapter) and uses xpcom tools that make coding a lot easier and more efficient.
... to begin with, the first section describesc++ macros that can replace a lot of the code in weblock1.cpp.
... much of the code created to get the software recognized and registered as a component can be reduced to a small data structure and a single macro.
...And 19 more matches
Index
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.
...the functionality of the component is described on the activity manager page, and the activity manager examples page has code snippets.
...And 19 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
for plugin vendors who have already written a native code (e.g.
...unlike native code installers (for example, files called setup.exe), the programming language for install operations in xpi is javascript.
... currently, all mozilla browsers released by mozilla.org support xpinstall, and a family of browsers based on mozilla code support xpinstall.
...And 18 more matches
Video and audio content - Learn web development
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.
...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.
... 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.
...And 18 more matches
Introduction to client-side frameworks - Learn web development
vue, like angularjs, extends html with some of its own code.
... the verbosity of dom changes building html elements and rendering them in the browser at the appropriate time takes a surprising amount of code.
...odoitemel(id, name) { const item = document.createelement('li'); const span = document.createelement('span'); const textcontent = document.createtextnode(name); span.appendchild(textcontent) item.id = id; item.appendchild(span); item.appendchild(builddeletebuttonel(id)); return item; } here, we use the document.createelement() method to make our <li>, and several more lines of code to create the properties and children it needs.
...And 18 more matches
An Overview of XPCOM
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.
... 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.
... 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.
...And 18 more matches
nsILocalFileMac
inherits from: nsilocalfile last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview cfurlref getcfurl(); native code only!
... fsref getfsref(); native code only!
... fsspec getfsspec(); native code only!
...And 18 more matches
nsIWebBrowserPersist
persist_flags_autodetect_apply_conversion 16384 let the webbrowserpersist decide whether the incoming data is encoded and whether it needs to go through a content converter, for example to decompress it.
... encode_flags_selection_only 1 output only the current selection as opposed to the whole document.
... encode_flags_formatted 2 for plain text output.
...And 18 more matches
nsIXPConnect
inherits 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!
...t(in nsisupports acomobj, in short depth); [noscript,notxpcom] prbool definedomquickstubs(in jscontextptr cx, in jsobjectptr proto, in pruint32 flags, in pruint32 interfacecount, [array, size_is(interfacecount)] in nsiidptr interfacearray); jsval evalinsandboxobject(in astring source, in jscontextptr cx, in nsixpconnectjsobjectholder sandbox, in prbool returnstringonly); native code only!
...And 18 more matches
Plug-in Basics - Plugins
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.
... 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.
...when the last instance of a plug-in is deleted, the plug-in code is unloaded from memory.
...And 18 more matches
Background Tasks API - Web APIs
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.
...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.
...And 18 more matches
Appendix D: Loading Scripts - Archive of obsolete content
most add-ons and xul runner applications provide their primary functionality by loading and executing javascript code.
... 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.
...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.
...And 17 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
here's an example of this kind of usage for ie: <!-- ie only code --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> </object> in the above example, the classid attri...
...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.
...And 17 more matches
Building up a basic demo with the PlayCanvas engine - Game development
<html> <head> <meta charset="utf-8"> <title>mdn games: playcanvas demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="playcanvas-latest.js"></script> <canvas id="application-canvas"></canvas> <script> var canvas = document.getelementbyid("application-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.
... before reading on, copy this code to a new text file and save it in your working directory as index.html.
...And 17 more matches
Inheritance in JavaScript - Learn web development
i\'m ' + this.name.first + '.'); }; note: in the source code, you'll also see bio() and farewell() methods defined.
... 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.
...it also takes more lines of code.
...And 17 more matches
Getting started with Svelte - Learn web development
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.
...less code means less kb to download, parse, execute, and keep hanging around in memory.
... 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 17 more matches
Command line crash course - Learn web development
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.
... src, located inside a directory called project, located on the desktop, you could type these three commands to get there from your home folder: cd desktop cd project cd src but this a waste of time — instead, you can type one command, with the different items in the path separated by forward slashes, just like you do when specifying paths to images or other assets in css, html, or javascript code: cd desktop/project/src note that including a leading slash on your path makes the path absolute, for example /users/your-user-name/desktop.
...And 17 more matches
NSS_3.12_release_notes.html
nss 3.12 libraries have 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_findcrlnumber...
....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 ...
..._camellia_flag new oids (see secoidt.h) new ec signature oids sec_oid_ansix962_ecdsa_signature_recommended_digest sec_oid_ansix962_ecdsa_signature_specified_digest sec_oid_ansix962_ecdsa_sha224_signature sec_oid_ansix962_ecdsa_sha256_signature sec_oid_ansix962_ecdsa_sha384_signature sec_oid_ansix962_ecdsa_sha512_signature more id-ce and id-pe oids from rfc 3280 sec_oid_x509_hold_instruction_code sec_oid_x509_delta_crl_indicator sec_oid_x509_issuing_distribution_point sec_oid_x509_cert_issuer sec_oid_x509_freshest_crl sec_oid_x509_inhibit_any_policy sec_oid_x509_subject_info_access camellia oids (rfc3657) sec_oid_camellia_128_cbc sec_oid_camellia_192_cbc sec_oid_camellia_256_cbc pkcs 5 v2 oids sec_oid_pkcs5_pbkdf2 sec_oid_pkcs5_pbes2 sec_oid_pkcs5_pbmac1 sec_oid_hmac_sha1 sec_oid_hmac...
...And 17 more matches
Xptcall Porting Status
feel free to email me with questions or to volunteer to contribute xptcall code for any platform.
...font> possible contributors notes <font color="white">done</font> win32 x86 john bandhauer <jband@netscape.com> win32 <font color="white">done</font> linux x86 john bandhauer <jband@netscape.com> ulrich drepper <drepper@cygnus.com> unix <font color="white">done</font> freebsd and netbsd x86 christoph toshok <toshok@hungry.com>, john bandhauer <jband@netscape.com> unix (same as linux 86 code) <font color="white">done</font> bsd/os x86 bert driehuis <bert_driehuis@nl.compuware.com> unix (same as linux 86 code) bert contributed patches that *should* do the right thing for all the unixish-x86 versions of this code for gcc 2.7 or 2.8 vs.
...he is hoping that others will help test the changes using these two compilers on the various platforms where this same code is used.
...And 17 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
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.
...a vast number of the most popular applications are based at least in part on javascript code.
...to understand where queuemicrotask() comes into play here, it's helpful to understand how the javascript runtime operates when scheduling and running code.
...And 17 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.
...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.
...And 17 more matches
SubtleCrypto.verify() - Web APIs
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.
...And 17 more matches
The Essentials of an Extension - Archive of obsolete content
now we'll look into its files and code, starting with the install.rdf file.
...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).
...most of the code for an extension resides in the chrome folder, just like in the hello world example.
...And 16 more matches
Package management basics - Learn web development
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?
... 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.
...And 16 more matches
Mozilla Development Strategies
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.
...the only thing worse than not understanding someone else's code is not understanding your own.
...And 16 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.
...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.
...And 16 more matches
Starting WebLock
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.
...you will see the code which does this in the next section.
...this callback allows the component to execute any one-time registration code it may need.
...And 16 more matches
Using Objective-C from js-ctypes
this guide explains how to convert objective-c code into js-ctypes code.
... converting objective-c code to c code to convert objective-c code to js-ctypes, we need to convert it to c code first.
... we can then convert it straight to js-ctypes code.
...And 16 more matches
EventTarget.addEventListener() - Web APIs
available only in code running in xbl or in the chrome of the firefox browser.
...this parameter is useful for code found in add-ons, as well as the browser itself.
... 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.
...And 16 more matches
Using Web Workers - Web APIs
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).
...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.
... you can run whatever code you like inside the worker thread, with some exceptions.
...And 16 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later.
... 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: .
...And 15 more matches
Building accessible custom components in XUL - Archive of obsolete content
<code> <grid class="spreadsheet" id="accjaxspreadsheet" flex="1"> <rows flex="1"></rows> <columns flex="1"> <column> <description value="entry #"/> <description value="1"/> <description value="2"/> <description value="3"/> <description value="4"/> <description value="5"/> <description value="6"/> <description value="7"/> </column> <column ...
... <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; background-color: white; margin: 0px; padding: 2px; border-left: thin solid; border-bottom: thin solid; font-family: monospace; font-size: 12pt; text-align: center; font-weight: bold; } </code> you can see the results by installing stage-1.xpi, restarting firefox, and selecting accjax from the tools menu.
...And 15 more matches
Scratchpad - Archive of obsolete content
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.
...And 15 more matches
Introducing asynchronous JavaScript - Learn web development
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.
...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?
...And 15 more matches
Arrays - Learn web development
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.
...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.
...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.
...And 15 more matches
Eclipse CDT
introduction eclipse cdt (c/c++ development tools) is an open-source ide for c and c++ development with advanced code assistance (inheritance/call graph explorer, jump to definition, refactoring, autocomplete, syntax highlighting, and so on).
... system requirements eclipse will use a lot of memory to fully index the mozilla source tree to provide code assistance features (easily 4 gb of ram, although this will drop to just over 1 gb if you restart after indexing is complete).
...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".
...And 15 more matches
Internationalized Domain Names (IDN) Support in Mozilla Browsers
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.
... how mozilla browsers handle non-ascii domain names unicode and nameprep when mozilla receives idn input from the user via the location bar or a request to process non-ascii host name links, it first turns them into unicode, then normalizes the input string to make it conform to general uri requirement.
...And 15 more matches
mozIStorageStatement
only available to javascript code.
...available only to javascript code.
...this will be one less than the number used in the sql (<code>?1</code> maps to <code>0</code>, and so on).
...And 15 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
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.
... 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.
... the event loop driving your code handles these tasks one after another, in the order in which they were enqueued.
...And 15 more matches
Transcoding assets for Media Source Extensions - Web APIs
this article takes you through the requirements and shows you a toolchain you can use to encode your assets appropriately.
... getting started the first and most important step is to ensure that your files are comprised of a container and codec that users' browsers support.
... depending on the codec, you might need to fragment the file to comply with the iso bmff spec.
...And 15 more matches
Closures - JavaScript
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().
... 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.
...the word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available.
...And 15 more matches
Functions - JavaScript
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.
... 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.
... 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)); /* ...
...And 15 more matches
String.prototype.normalize() - JavaScript
the normalize() method returns the unicode normalization form of the string.
... syntax str.normalize([form]) parameters form optional one of "nfc", "nfd", "nfkc", or "nfkd", specifying the unicode normalization form.
... return value a string containing the unicode normalization form of the given string.
...And 15 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
« previousnext » this document was authored by hiroshi shimoda of clear code inc.
... for each element that i explain in this chapter, i will illustrate it with a source code example.
...you can download a file with all the source code examples from: fixme: attache the translated tarball - paul task !.
...And 14 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
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).
... 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.
... 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.
...And 14 more matches
JXON - Archive of obsolete content
which do not contain other element nodes, text nodes, cdatasection nodes or attr nodes) have the default value true (see the code considerations).
...the generated javascript object tree is not stringifyable (see the code considerations).
...try: alert((new xmlserializer()).serializetostring(newdoc)); note: with this code the date instances, if they exist, are converted into strings through the togmtstring() method.
...And 14 more matches
Build your own function - Learn web development
prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code.
...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.
... finally, add the following code inside the curly braces: const html = document.queryselector('html'); const panel = document.createelement('div'); panel.setattribute('class', 'msgbox'); html.appendchild(panel); const msg = document.createelement('p'); msg.textcontent = 'this is a message box'; panel.appendchild(msg); const closebtn = document.createelement('button'); closebtn.textcontent = 'x'; panel.appendchild(closebtn); closebtn.onclick = function() { panel.parentnode.removechild(panel); } this is quite a lot of code to go through, so we'll walk you through it bit by bit.
...And 14 more matches
Android-specific test suites
there are several android-specific test suites that run on the firefox for android codebase: android-test ensures that the code passes unit tests.
... android-findbugs ensures that the code avoids common java coding errors.
... android-lint ensures that the code avoids common android coding errors.
...And 14 more matches
Gecko Keypress Event
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.
...And 14 more matches
Script security
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.
... 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.
...And 14 more matches
Introduction to the JavaScript shell
this article explains how to use the shell to experiment with javascript code and run javascript programs.
...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.
...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.
...And 14 more matches
nsIDocShell
lace); void beginrestore(in nsicontentviewer viewer, 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!
...void historypurged(in long numentries); void internalload(in nsiuri auri, in nsiuri areferrer, in nsisupports aowner, in pruint32 aflags, in wstring awindowtarget, in string atypehint, in nsiinputstream apostdatastream, in nsiinputstream aheadersstream, in unsigned long aloadflags, in nsishentry ashentry, in boolean firstparty, out nsidocshell adocshell, out nsirequest arequest); native code only!
...And 14 more matches
Debugger.Memory - Firefox Developer Tools
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.
... 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.
...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.
...And 14 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
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 code looks like this: const xrotationdegreespersecond = 25; const yrotationdegreespersecond = 15; const zrotationdegreespersecond = 35; const enablerotation = true; const allowmouserotation = true; const allowkeyboardmotion = true; const enableforcepolyfill = false; //const session_type = "immersive-vr"; const session_type = "inline"; const mouse_speed = 0.003; xrotationdegreespersecond the numb...
...refer to that if you're interested in the glsl source code for the basic shaders used here.
...And 14 more matches
Rendering and the WebXR frame animation callback - Web APIs
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().
...as long as your code is written properly, everything will be fine.
...And 14 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
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.
...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...
...errorcode="+hkcu_status); return hkcu_status; } } return 0; } /** * function for preinstallation of plugin (firstinstall).
...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.
...And 13 more matches
Archived Mozilla and build documentation - Archive of obsolete content
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").
...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).
...And 13 more matches
Examples - Archive of obsolete content
this page contains the source code of the examples related to the "properly using css and javascript in xhtml documents" article.
... important notes if you plan to test these examples by yourself, you must use the right filename extension (it is written at the beginning of the code).
..." /> <style type="text/css"> <!-- body {background-color: blue; color: yellow; } --> </style> <script type="text/javascript"> <!-- var i = 0; var sum = 0; for (i = 0; i < 10; ++i) { sum += i; } alert('sum = ' + sum); // --> </script> </head> <body> <h1>problem 2 - comments in xhtml</h1> <p> this document is valid xhtml 1.0 strict served as <code>application/xhtml+xml</code>.
...And 13 more matches
Windows Media in Netscape - Archive of obsolete content
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).
... below, some of the salient points are illustrated in a code snippet: if (window.activexobject && navigator.useragent.indexof('windows') != -1) { // ie for windows object instantiation -- use of activexobject } else if(window.geckoactivexobject) { // netscape 7.1 object instantiation --use of geckoactivexobject } else if(navigator.mimetypes) { // plugin architecture, such as in netscape 4x - 7.02 and opera browsers } since ie for mac also exposes window.activexobject it is wise to determine if the browser in question is on windows.
...here is a code snippet that shows this: var player; try { if (window.activexobject) { player = new activexobject("mediaplayer.mediaplayer.1"); } else if (window.geckoactivexobject) { player = new geckoactivexobject("mediaplayer.mediaplayer.1"); } else { // plugin code using navigator.mimetypes player = navigator.mimetypes["application/x-mplayer2"].enabledplugin; } } catch(e) { // han...
...And 13 more matches
Building up a basic demo with Babylon.js - Game development
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.
...doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: babylon.js demo</title> <style> html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <script src="babylon.js"></script> <canvas id="render-canvas"></canvas> <script> var canvas = document.getelementbyid("render-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 (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.
...And 13 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?
... 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.
... 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.
...And 13 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?
... objective: to gain familiarity with apis, what they can do, and how you can use them in your code.
...they abstract more complex code away from you, providing some easier syntax to use in its place.
...And 13 more matches
Working with Svelte stores - Learn web development
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.
... 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 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!".
...And 13 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.
...And 13 more matches
How to embed the JavaScript engine
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.
...And 13 more matches
Animated PNG graphics
MozillaTechAPNG
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 contents of the canvas are not necessarily available to the decoder.
...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.
...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.
...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.
...And 13 more matches
Using Service Workers - Web APIs
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.
... you’ll also need to serve your code via https — service workers are restricted to running across https for security reasons.
... 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.
...And 13 more matches
WindowEventHandlers - Web APIs
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.
...And 13 more matches
MIME types (IANA media types) - HTTP
for example, for the mime type text, the subtype might be plain (plain text), html (html source code), or calendar (for icalendar/.ics) files.
...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.
...And 13 more matches
Grammar and types - JavaScript
javascript is case-sensitive and uses the unicode character set.
...this practice reduces the chances of bugs getting into the code.
... you can use most of iso 8859-1 or unicode letters such as å and ü in identifiers.
...And 13 more matches
Text formatting - JavaScript
it is a set of "elements" of 16-bit unsigned integer values (utf-16 code units).
... '\xa9' // "©" unicode escape sequences the unicode escape sequences require at least four hexadecimal digits following \u.
... '\u00a9' // "©" unicode code point escapes new in ecmascript 2015.
...And 13 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.
...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.
... creating html and javascript this is the simplest case we'll look at, whereby you get emscripten to generate everything you need to run your code, as webassembly, in the browser.
...And 13 more matches
Understanding WebAssembly text format - WebAssembly
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 textual formats, the fundamental unit of code in webassembly is a module.
...And 13 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.
... 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.
...And 12 more matches
When To Use ifdefs - Archive of obsolete content
the mozilla codebase is used for many different projects and products, including firefox, thunderbird, xulrunner, and many others.
... sometimes the same basic code is used for multiple projects, but there are small differences needed.
... "ifdefs", or conditional instructions, are used to build different code what are ifdefs ifdefs are conditional directives to a text preprocessor which mark that certain blocks of code are used only in certain conditions.
...And 12 more matches
Gecko Compatibility Handbook - Archive of obsolete content
this compatibility test will be most beneficial to sites using simple code or that have updated to support standards.
...correct any errors and replace proprietary code wherever possible.
... 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.
...And 12 more matches
GLSL Shaders - Game development
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.
...this allows the cpu to focus its processing power on other tasks, like executing code.
...And 12 more matches
How CSS is structured - Learn web development
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.
...<head> <meta charset="utf-8"> <title>my css experiments</title> <link rel="stylesheet" href="styles.css"> </head> <body> <p>create your test html here</p> </body> </html> styles.css: /* create your test css here */ p { color: red; } when you find css that you want to experiment with, replace the html <body> contents with some html to style, and then add your test css code to your css file.
...And 12 more matches
How to build custom form controls - Learn web development
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.
...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.
... .select:after { content : "▼"; /* we use the unicode character u+25bc; make sure to set a charset meta tag */ position: absolute; z-index : 1; /* this will be important to keep the arrow from overlapping the list of options */ top : 0; right : 0; box-sizing : border-box; height : 100%; width : 2em; padding-top : .1em; border-left : .2em solid #000; border-radius: 0 .1em .1em 0; background-color : #000; color : ...
...And 12 more matches
Choosing the right approach - Learn web development
single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes (recursive callbacks) yes (nested callbacks) no code example an example that loads a resource via the xmlhttprequest api (run it live, and see the source): function loadasset(url, type, callback) { let xhr = new xmlhttprequest(); xhr.open('get', url); xhr.responsetype = type; xhr.onload = function() { callback(xhr.response); }; xhr.send(); } function displayimage(blob) { let objecturl = url.createobjecturl(blob); let image...
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations yes yes (recursive timeouts) yes (nested timeouts) no code example here the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr.
... universe!'); }, 2000) pitfalls you can use recursive settimeout() calls to run a function repeatedly in a similar fashion to setinterval(), using code like this: let i = 1; settimeout(function run() { console.log(i); i++; settimeout(run, 100); }, 100); there is a difference between recursive settimeout() and setinterval(): recursive settimeout() guarantees at least the specified amount of time (100ms in this example) will elapse between the executions; the code will run and then wait 100 milliseconds before it runs again.
...And 12 more matches
Getting started with React - Learn web development
it does this through the use of components — self-contained, logical pieces of code that describe a portion of the user interface.
... use cases unlike the other frameworks covered in this module, react does not enforce strict rules around code conventions or file organization.
...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.
...And 12 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
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/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...
... 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.
...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.
...And 12 more matches
Limitations of chrome scripts
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.
...for example: // chrome code gbrowser.contentwindow; // null gbrowser.contentdocument; // null gbrowser.selectedbrowser.contentwindow; // null window.content; // null content; // null as a special note, docshells live in the content process, so they are also inaccessible: gbrowser.docshell; // n...
... 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.
...And 12 more matches
Localization content best practices
this document provides best practices for developers to create localizable code, and describes how to avoid some localizability (l12y) common mistakes.
... note: if you're a localizer and you want to contribute to the localization of mozilla products, you might want to read our localization quick start guide for information on localizing mozilla code.
...for example, use the single unicode …, and not three dots.
...And 12 more matches
Web Replay
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.
... 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.
...And 12 more matches
nsIMimeConverter
method overview string encodemimepartiistr(in string header, in boolean structured, in string mailcharset, in long fieldnamelen, in long encodedwordsize); string encodemimepartiistr_utf8(in autf8string header, in boolean structured, in string mailcharset, in long fieldnamelen, in long encodedwordsize); string decodemimeheadertocharptr(in string header, in string default_charset, in boolean override_charset, in boolean eatcontinuations); astring decodemimeheader(in string header, in string default_charset, in boolean override_charset, in boolean eatcontinuations); mime...
...encoderdata *b64encoderinit(in mimeconverteroutputcallback output_fn, in void *closure); mimeencoderdata *qpencoderinit(in mimeconverteroutputcallback output_fn, in void *closure); void encoderdestroy(in mimeencoderdata *data, in boolean abort_p); long encoderwrite(in mimeencoderdata *data, in string buffer, in long size); methods encodemimepartiistr() an variant of encodemimepartiistr_utf8() which treats the header as written in the given charset.
... this should only be used by native code, as xpconnect translation causes it to not work properly.
...And 12 more matches
Setting HTTP request headers
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.
...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.
...And 12 more matches
Console messages - Firefox Developer Tools
filename and line number for javascript, css and console api messages, the message can be traced to a specific line of code.
... summary the http version, response code, and time taken to complete.
... clicking the response code takes you to the reference page for that code.
...And 12 more matches
HTMLBodyElement - Web APIs
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.
...And 12 more matches
WebGL model view projection - Web APIs
you may encouter that term from time to time while researching and wokring with webgl code.
...the code below will create 2 triangles that will draw a square on the screen.
... note: the code for each webglbox example is available in this github repo and is organized by section.
...And 12 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
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.
... 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.
...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.
...And 12 more matches
Setting up adaptive streaming media sources - Developer guides
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.
... 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.
...And 12 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
"one-time-code" a one-time code used for verifying user identity.
...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.
... "country" a country code.
...And 12 more matches
Browser detection using the user agent - HTTP
so, you might have thought to do this: // this code snippet splits a string in a special notation if (navigator.useragent.indexof("chrome") !== -1){ // yes!
...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.
... var camelcaseexpression = new regexp("(?<=[a-z])"); var splitupstring = function(str) { return (""+str).split(camelcaseexpression); }; } else { /*this fallback code is much less performant, but works*/ var splitupstring = function(str){ return str.replace(/[a-z]/g,"z$1").split(/z(?=[a-z])/g); }; } console.log(splitupstring("foobare")); // ["foob", "are"] console.log(splitupstring("jqwhy")); // ["jq", "w", "hy"] the above code would have made several incorrect assumptions: it assumed that all user agent strings that include the substring "chrome" are chrome.
...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.
... note: you can find the sample code in our webassembly-examples github repo.
...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.
...And 12 more matches
panel - Archive of obsolete content
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.
... scripting panel content you can't directly access your panel's content from your main add-on code.
...so implementing a complete solution usually means you have to send messages between the content script and the main add-on code.
...And 11 more matches
Connecting to Remote Content - Archive of obsolete content
we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code.
... 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.
...And 11 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
instead of forcing the reader to follow links to new pages, the javascript code can act as the mediator for information access.
...the code includes the dhtml element.
...in addition to these components, you will also find the piece of code that is responsible for the dhtml ticker.
...And 11 more matches
MMgc - Archive of obsolete content
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.
...kfinalize and krcobject are used internally by the gc; you should not need to set them in your user code.
...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.
...And 11 more matches
Tamarin build documentation - Archive of obsolete content
tamarin source versions the following instructions are for obtaining and building the tamarin central source code.
... the tamarin codebase contains a cross-platform build system for mozilla developers.
... the tamarin codebase has the ability to build additional code which supports debugging hooks.
...And 11 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
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.
...if your language uses only plain latin (ascii) characters, set your text editor to use any encoding except unicode.
...And 11 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
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.
...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.
...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.
...And 11 more matches
Desktop mouse and keyboard controls - Game development
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.
...inside them we can get the code of the key that was pressed from the keycode property of the event object, see which key it is, and then set the proper variable.
... there are no helpers so you have to remember what the given codes are (or look them up); 37 is the left arrow: function keydownhandler(event) { if(event.keycode == 39) { rightpressed = true; } else if(event.keycode == 37) { leftpressed = true; } if(event.keycode == 40) { downpressed = true; } else if(event.keycode == 38) { uppressed = true; } } the keyuphandler looks almost exactly the same as the keydownhandler above, but instead of setting the pressed variables to true, we would set them to false.
...And 11 more matches
Images in HTML - Learn web development
our above code would give us the following result: note: elements like <img> and <video> are sometimes referred to as replaced elements.
... 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.
...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.
...And 11 more matches
Fetching data from the server - Learn web development
just inside the <script> element, add the following code.
...first of all, put the following beneath your previous code block — this is the empty shell of the function.
...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.
...And 11 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
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/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...
... 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.
...they make little to no attempt to understand what our javascript code is doing.
...And 11 more matches
IPDL Tutorial
ipdl, short for "inter-process-communication protocol definition language", is a mozilla-specific language allowing c++ code to pass messages between processes or threads in an organized and secure way.
...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.
...And 11 more matches
sample2
/* this source code form is subject to the terms of the mozilla public * license, v.
...s_sig_trailer "-----end signature-----" #define ns_cert_header "-----begin certificate-----" #define ns_cert_trailer "-----end certificate-----" /* missing publically 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".
...And 11 more matches
Tutorial: Embedding Rhino
in this document, javascript code will be in green, java code will be in green, and shell logs will be in purple.
... entering a context the code context cx = context.enter(); creates and enters a context.
... 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.
...And 11 more matches
64-bit Compatibility
this article focuses on hacking tracemonkey code generation (jstracer.cpp, jsregex.cpp) in ways that will work on both 32-bit and 64-bit jit backends.
...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.
...lir safety it is not immediately clear from reading lir which opcodes should be used for 64-bit safety.
...And 11 more matches
Self-hosted builtins in SpiderMonkey
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.
...in contrast to function.prototype.call, this syntax makes it impossible for other code to interfere and gets compiled to bytecode that doesn't have any overhead compared to a normal function invocation.
...And 11 more matches
SpiderMonkey 1.8.5
you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (md5 checksum: a4574365938222adca0a6bd33329cb32).
...spidermonkey 1.8.5 includes a just-in-time compiler (jit) (several, actually) that compiles javascript to machine code, for a significant speed increase.
...on other platforms, the jit is simply disabled; javascript code runs in an interpreter, as in previous versions.
...And 11 more matches
nsIDOMWindowUtils
float abottomsize, in float aleftsize, in boolean aignorerootscrollframe, in boolean aflushlayout); void processupdates(); obsolete since gecko 13.0 void purgepccounts(); unsigned long redraw([optional] in unsigned long acount); void renderdocument(in nsconstrect arect, in pruint32 aflags, in nscolor abackgroundcolor, in gfxcontext athebescontext); native code only!
... 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 11 more matches
nsIFocusManager
fox 5.0 / thunderbird 5.0 / seamonkey 2.2) implemented by: @mozilla.org/focus-manager;1 as a service: 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!
...And 11 more matches
nsISelectionPrivate
method overview void addselectionlistener(in nsiselectionlistener newlistener); void endbatchchanges(); void getcachedframeoffset(in nsiframe aframe, in print32 inoffset, in nspointref apoint); native code only!
... nsienumerator getenumerator(); nsframeselection getframeselection(); native code only!
...erval(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results); void getrangesforintervalarray(in nsinode beginnode, in print32 beginoffset, in nsinode endnode, in print32 endoffset, in boolean allowadjacent, in rangearray results); native code only!
...And 11 more matches
Using the clipboard
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.
...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.
...And 11 more matches
Add to iPhoto
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.
... note: in a few cases, this code takes the easy way out by using ctypes.voidptr_t instead of a typed pointer.
...And 11 more matches
HTMLFrameSetElement - Web APIs
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.
...And 11 more matches
Using IndexedDB - Web APIs
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.
...therefore, it is not recommended to use it in production code.
...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!
...And 11 more matches
SubtleCrypto.sign() - Web APIs
WebAPISubtleCryptosign
hmac the hmac algorithm calculates and verifies hash-based message authentication codes according to the fips 198-1 standard.
... 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.
...And 11 more matches
Getting Started - Developer guides
// old compatibility code, no longer needed.
... 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.
...form data should be sent in a format that the server can parse, like a query string: "name=value&anothername="+encodeuricomponent(myvar)+"&so=on" or other formats, like multipart/form-data, json, xml, and so on.
...And 11 more matches
Regular expression syntax cheatsheet - JavaScript
\s matches a single white space character, including space, tab, form feed, line feed, and other unicode spaces.
... \cx matches a control character using caret notation, where "x" is a letter from a–z (corresponding to codepoints u+0001–u+001f).
... \xhh matches the character with the code hh (two hexadecimal digits).
...And 11 more matches
String - JavaScript
primitives 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.
... console.log(eval(s2.valueof())) // returns the number 4 escape notation special characters can be encoded using escape notation: code output \xxx (where xxx is 1–3 octal digits; range of 0–377) iso-8859-1 character / unicode code point between u+0000 and u+00ff \' single quote \" double quote \\ backslash \n new line \r carriage return \v vertical tab \t tab \b backspace \f form feed \uxxxx (where xxxx is 4 hex digits; range of 0x0000–0xffff) utf-16 code unit / unicode code point between u+0000 and u+ffff \u{x} ...
...And 11 more matches
Compiling from Rust to WebAssembly - WebAssembly
if you have some rust code, you can compile it into webassembly (wasm).
...this package will contain only webassembly and javascript code, and so the users of the package won't need rust installed.
...this helps compile the code to webassembly, as well as produce the right packaging for npm.
...And 11 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
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.
... 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.
...And 10 more matches
Custom XUL Elements with XBL - Archive of obsolete content
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.
...bindings tend to require many lines of code, and having more than one ends up making gigantic, unbrowsable files.
...And 10 more matches
XPCOM Objects - Archive of obsolete content
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.
...a modified version of the last code snippet produces an even longer list of available interfaces.
... 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.
...And 10 more matches
Nanojit - Archive of obsolete content
overview nanojit is a small, cross-platform c++ library that emits machine code.
...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.
... once the instructions are in the lirbuffer, the application calls nanojit::compile() to produce machine code, which is stored in a nanojit::fragment.
...And 10 more matches
Using Breakpoints in Venkman - Archive of obsolete content
breakpoints are places in code where execution is suspended.
...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.
...a hard breakpoint represents an actual trap instruction included in the pseudocode of a compiled function.
...And 10 more matches
Elements - Archive of obsolete content
in addition, data: urls are only supported from chrome code (in other words, from the application or an extension).
... constructor the code inside the constructor is called when a binding has just been attached to an element.
... destructor the code inside the destructor is called when a binding is being removed from an element.
...And 10 more matches
textbox - Archive of obsolete content
the old name is retained for compatibility, but you should update your code.
...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.
...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.
...And 10 more matches
Client-side form validation - Learn web development
javascript validation is coded using javascript.
...find the source code on github at fruit-start.html and a live example below.
...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.
...And 10 more matches
Third-party APIs - Learn web development
note: you might want to just get all our code examples at once, in which case you can then just search the repo for the example files you need in each section.
... 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.
...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.
...And 10 more matches
Storing the information you need — Variables - Learn web development
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).
...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.
...And 10 more matches
JavaScript-DOM Prototypes in Mozilla
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.
...And 10 more matches
Mozilla projects on GitHub
there are a number of tools and services whose code is hosted on github.
... this article offers a quick guide for getting started with mozilla code on github.
... it also lists some interesting github repositories containing mozilla project code.
...And 10 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
nss sample code 6: encryption/decryption and mac and output public as a pkcs 11 csr.
... generates encryption/mac keys and outputs public key as pkcs11 certificate signing request /* this source code form is subject to the terms of the mozilla public * license, v.
... 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 10 more matches
JIT Optimization Strategies
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.
...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] ...
...And 10 more matches
Language bindings
aught than simply throwing an nsresult's value will.components.idcomponents.id is a constructor that creates native objects that conform to the nsijsid interface.components.interfacescomponents.interfaces is a read-only object whose properties are interfaces indexed by their names.components.interfacesbyidcomponents.interfacesbyid is a read-only array of classes indexed by iid.components.issuccesscodedetermines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.components.lastresultcomponents.managercomponents.manager is a convenience reflection of the global native 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.
...it returns a reference to the clone:components.utils.createobjectincomponents.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.components.utils.evalinsandboxthe evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.components.utils.evalinwindowthis function enables code running in a more-privileged javascript context to evaluate a string in a less-privileged javascript context.
...And 10 more matches
nsIMsgDBHdr
this property does not change the state of any thread objects, so only internal database code should set this attribute.
...setting this property will probably result in an inconsistent database representation, so only internal database code should set this attribute.
...the value here will effectively be the unparsed header content, so it will contain full mime-encoded syntax.
...And 10 more matches
Using the Payment Request API - Web APIs
note: the code snippets from this section are from our feature detect support demo.
...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...
...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.
...And 10 more matches
Using XMLHttpRequest - Web APIs
however, this method is a "last resort" since if the xml code changes slightly, the method will likely fail.
...however, this method is a "last resort" since if the html code changes slightly, the method will likely fail.
... 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).
...And 10 more matches
Using CSS animations - CSS: Cascading Style Sheets
<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.
...that’s as simple as adding this keyframe: 75% { font-size: 300%; margin-left: 25%; width: 150%; } the full code now looks like this: p { animation-duration: 3s; animation-name: slidein; } @keyframes slidein { from { margin-left: 100%; width: 300%; } 75% { font-size: 300%; margin-left: 25%; width: 150%; } to { margin-left: 0%; width: 100%; } } <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 ...
... note: reload page to see the animation, or click the codepen button to see the animation in the codepen environment.
...And 10 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
strings strings in javascript are sequences of unicode characters.
...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.
...And 10 more matches
Inheritance and the prototype chain - JavaScript
code link setting a property to an object creates an own property.
...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.
...And 10 more matches
Optimizing startup performance - Web Performance
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.
... 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.
...And 10 more matches
Compiling an Existing C Module to WebAssembly - WebAssembly
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.
... $ 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.
...And 10 more matches
Content Scripts - Archive of obsolete content
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.
...there are 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.
...And 9 more matches
Preferences - Archive of obsolete content
nsisupportsstring used to handle unicode strings in preferences.
... nsisupportsstring as noted above, this is used to handle unicode strings in preferences.
... example: // prefs is an nsiprefbranch // example 1: getting unicode value var value = prefs.getcomplexvalue("preference.with.non.ascii.value", components.interfaces.nsisupportsstring).data; // example 2: setting unicode value var str = components.classes["@mozilla.org/supports-string;1"] .createinstance(components.interfaces.nsisupportsstring); str.data = "some non-ascii text"; prefs.setcomplexvalue("preference.with.non.ascii.value", components.interfaces.nsisupportsstring, str); nsipreflocalizedstring another complex type supported by mozilla is nsipreflocalizedstring.
...And 9 more matches
JavaScript Daemons Management - Archive of obsolete content
here are some code snippets that simplify and abstract the management of daemons.
... 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...
... for a fast overview on the code proposed here you can git clone https://github.com/madmurphy/daemon.js.git.
...And 9 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
in your extension's browser.xul overlay, write code which listens for a custom dom event.
... the data from the web page (unprivileged code) will be the values of attribute1 and attribute2.
... to trigger the alert() in the listener and pass the data from the web page, write code such as this in the web page: var element = document.createelement("myextensiondataelement"); element.setattribute("attribute1", "foobar"); element.setattribute("attribute2", "hello world"); 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.
...And 9 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
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.
...And 9 more matches
nsIContentPolicy - Archive of obsolete content
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.
... important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code.
... important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code.
...And 9 more matches
Building up a basic demo with Three.js - Game development
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.
... before reading further, copy this code to a new text file, and save it in your working directory as index.html.
...And 9 more matches
HTML: A good basis for accessibility - Learn web development
better on mobile — semantic html is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive.
...whatever the case, you should replace such bad code.
...additionally, their source code requires more markup, which makes them less flexible and more difficult to maintain.
...And 9 more matches
HTML: A good basis for accessibility - Learn web development
better on mobile — semantic html is arguably lighter in file size than non-semantic spaghetti code, and easier to make responsive.
...whatever the case, you should replace such bad code.
...additionally, their source code requires more markup, which makes them less flexible and more difficult to maintain.
...And 9 more matches
Positioning - Learn web development
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.
... note: you can see the example at this point live at 1_static-positioning.html (see source code).
...go ahead and update the position declaration in your code: position: relative; if you save and refresh at this stage, you won't see a change in the result at all.
...And 9 more matches
How do I use GitHub Pages? - Learn web development
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!
...And 9 more matches
Adding vector graphics to the Web - Learn web development
more advanced svg features include <fecolormatrix> (transform colors using a transformation matrix,) <animate> (animate parts of your vector graphic,) and <mask> (apply a mask over the top of your image.) as a simple example, the following code creates a circle and a rectangle: <svg version="1.1" baseprofile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="black" /> <circle cx="150" cy="100" r="90" fill="blue" /> </svg> this creates the following output: from the example above, you may get the impression that svg is easy to handcode.
... yes, you can handcode simple svg in a text editor, but for a complex image this quickly starts to get very difficult.
... if you want to control the svg content with css, you must include inline css styles in your svg code.
...And 9 more matches
From object to iframe — other embedding technologies - Learn web development
select the embed button and you'll be given some <iframe> code — copy this.
... select the embed map option, which will give you some <iframe> code — copy this.
... playable code <h2>live output</h2> <div class="output" style="min-height: 250px;"> </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="width: 95%;min-height: 100px;"> </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-...
...And 9 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.
... 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).
...And 9 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.
... 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).
...And 9 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
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.
... logic errors: these are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results.
...And 9 more matches
Obsolete Build Caveats and Tips
purpose of this page the mozilla build process and code base have evolved considerably over the past few years.
... this has resulted in many caveats and tips being added to the mdn documentation for building older versions of the code base or dealing with older build tools.
...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.
...And 9 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.
... message managers are designed to enable chrome-privileged javascript code in one process to communicate with chrome-privileged javascript 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.
...And 9 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.
... 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.
...And 9 more matches
Mozilla DOM Hacking Guide
mozilla's dom is coded almost entirely in c++.
...however, since the dom is coded in c++, we expect to receive an argument of the correct type for our function.
...indeed, it will forward the call history[1] to history.item(1), which is defined in the idl and easily coded.
...And 9 more matches
Performance
the articles linked to from here will help you improve performance, whether you're developing core mozilla code or an add-on.
... best practices for front-end engineers tips for reducing impacts on browser performance in front-end code.
... about:memory about:memory is the easiest-to-use tool for measuring memory usage in mozilla code, and is the best place to start.
...And 9 more matches
JSAutoByteString
str jsstring * a pointer to jsstring to get initial content by calling js_encodestring(cx, str).
... 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.
...And 9 more matches
Avoiding leaks in JavaScript XPCOM components
despite this, it's easy to write javascript code that leaks.
... it's easy to write leaky code in any garbage-collected language.
... programmers writing and reviewing javascript code in mozilla should understand how code using xpcom in javascript can leak so that they can avoid leaks.
...And 9 more matches
Component Internals
the illustration below shows the basic relationship between the shared library containing the component implementation code you write and the xpcom framework itself.
...the largest and possibly most complex part of a component is the code specific to the component itself.
...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.
...And 9 more matches
Components.utils.Sandbox
principal the security principal defined for a sandbox determines what code running in that sandbox will be allowed to do.
... system principal to specify the system principal, you can create it using code like: cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsiprincipal); content principal you can specify a content principal for a particular origin in one of three ways: as an nsiprincipal, for example by using the nodeprincipal property of a dom node as an nsidomwindow, such as that returned by the dom window property as a string uri like "http://www.example.com/" (discouraged) when possible, specify a window or an nsiprincipal object instead of using a string uri.
...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.
...And 9 more matches
imgIRequest
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.
... decoderobserver imgidecoderobserver read only.
... status_load_complete 0x4 the data has been fully loaded to memory, but not necessarily fully decoded.
...And 9 more matches
nsIEditorIMESupport
inherits from: nsisupports last changed in gecko 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!
...And 9 more matches
nsILocalFile
to create an instance, use: var localfile = components.classes["@mozilla.org/file/local;1"] .createinstance(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!
...And 9 more matches
xptcall FAQ
it is implemented using platform specific c/c++ and assembly language code.
...porting this code is required in order to make mozilla run on any given platform.
... the xptcall approach was chosen over an approach that would have required generating stub code for calling and implementing all interfaces.
...And 9 more matches
Writing a WebSocket server in C# - Web APIs
this sample code can detect a get from the client.
...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.
... 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=0001 fin bit: this bit indicates whether the full message has been sent from the client.
...And 9 more matches
Inputs and input sources - Web APIs
let primaryinputsource = xrsession.inputsources[0]; for (let i=0; i < xrsession.inputsources.length; i++) { if (xrsession.inputsources[i].handedness === user.handedness) { primaryinputsource = inputsources[i]; break; } } this snippet of code starts by assuming that the first input source is the primary, but then looks for one whose handedness matches the one specified in the user object.
...the code below starts by assuming the first input source is the primary, then establishes a handler for the select event that records the event's source as the primary input source.
... 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.
...And 9 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.
... 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.
... code an optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds.
...And 9 more matches
Audio and video manipulation - Developer guides
ideo player and <canvas> element like this: <video id="my-video" controls="true" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> javascript this code handles altering the frames.
... 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.
... note: you can find the source code of this demo on github (see it live also).
...And 9 more matches
Expressions and operators - JavaScript
strings are compared based on standard lexicographical ordering, using unicode values.
...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.
... the following code shows examples of the && (logical and) operator.
...And 9 more matches
Intl - JavaScript
intl.locale() constructor for objects that represents a unicode locale identifier.
... a single locale may be specified by either an intl.locale object or a string 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.
...And 9 more matches
Creating annotations - Archive of obsolete content
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.
...the click handler sends a message called show back to the main add-on code.
...And 8 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.
...And 8 more matches
Appendix A: Add-on Performance - Archive of obsolete content
luckily, minimizing your startup time is easy, if you follow these guidelines: do not load or run code before it’s needed.
... javascript code modules.
...keep as much of your code in jsm, make it as modular as you can, and only load modules as you require them.
...And 8 more matches
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.
...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.
...And 8 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 ...
...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.which==3)||(a.button==2);var l=null;if(j.match(/over|out/)){switch(j){case"mouseover":l=a.relatedtarget||a.fromelement; break;case"mouseout":l=a.relatedtarget||a.toelement;}if(!(function(){while(l&&l.nodetype==3){l=l.parentnode;}return true;}).create({attempt:browser.engine.gecko})()){l=false; }}}}return ...
...And 8 more matches
Venkman Introduction - Archive of obsolete content
the interactive console also allows for execution of arbitrary javascript code.
...the source code view is empty until you select a script, and the interactive session view starts up with basic startup information.
...file names are displayed after a color coded, single letter icon representing the file extension.
...And 8 more matches
Custom toolbar button - Archive of obsolete content
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.
... if your language uses only plain latin (ascii) characters, set your text editor to use any encoding except unicode.
...And 8 more matches
XPCOM Interfaces - Archive of obsolete content
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.
...so, in most cases, you don't need to write native code for yourself.
...And 8 more matches
Common causes of memory leaks in extensions - Extensions
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.
... 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.
... strict mode also excludes several other error-prone code patterns.
...And 8 more matches
Anatomy of a video game - Game development
it is an excellent idea to attach your code to the moments that are appropriate for them.
... some code needs to be run frame-by-frame so why attach that function to anything other than the browser's redraw schedule?
... the above chunk of code has two statements.
...And 8 more matches
Web fonts - Learn web development
objective: to learn how to apply web fonts to a web page, using either a third party service, or by writing your own code.
...we'll show you below how to generate the required code.
...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).
...And 8 more matches
What are browser developer tools? - Learn web development
(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.
... 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.
... source code set breakpoints where you want to pause execution.
...And 8 more matches
Sending form data - Learn web development
o do you want to say it to?</label> <input name="to" id="to" value="mom"> </div> <div> <button>send my greetings</button> </div> </form> when the form is submitted using the post method, you get no data appended to the url, and the http request looks like so, with the data included in the request body instead: post / http/2.0 host: foo.com content-type: application/x-www-form-urlencoded content-length: 13 say=hi&to=mom the content-length header indicates the size of the body, and the content-type header indicates the type of resource sent to the server.
...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.
...And 8 more matches
UI pseudo-classes - Learn web development
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).
... 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).
...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.
...And 8 more matches
Working with JSON - Learn web development
note: we've made the json seen above available inside a variable in our jsontest.html example (see the source code).
... unlike in javascript code in which object properties may be unquoted, in json only quoted strings may be used as properties.
...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.
...And 8 more matches
Aprender y obtener ayuda - Learn web development
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.
...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.
... many mdn web docs reference pages provide interactive examples too, where you can alter the code and see how the live result changes.
...And 8 more matches
Framework main features - Learn web development
objective: to understand the main code features of frameworks.
...handlebars code resembles html, but it has the option of pulling data in from elsewhere.
... given this handlebars template: <header> <h1>hello, {{subject}}!</h1> </header> and this data: { subject: "world" } handlebars will build html like this: <header> <h1>hello, world!</h1> </header> typescript typescript is a superset of javascript, meaning it extends javascript — all javascript code is valid typescript, but not the other way around.
...And 8 more matches
Mozilla accessibility architecture
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.
...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.
...And 8 more matches
CustomizableUI.jsm
the customizableui.jsm javascript code module allows you to interact with customizable buttons and items in firefox's main window ui.
...this can be useful if other parts of the code need to react to changes in the customization of the user interface.
... 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.
...And 8 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.
... pseudocode this section provides some pseudocode that demonstrates how to put together a javascript class based on the steps listed above.
...And 8 more matches
Profiling with the Firefox Profiler
there are lighter grey names to the right of tree elements that indicate where the code comes from.
... clicking the "javascript only" option will only show javascript code in the call tree.
...if you're unfamiliar with gecko's internals, you can click the javascript only button to see where your javascript code is slow.
...And 8 more matches
Introduction to NSPR
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.
...And 8 more matches
Creating JavaScript jstest reftests
comparison functions and shared test functionality the jstest runner loads the code in js/src/tests/shell.js for every test.
... 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.
... it is easy to make a test silently pass; anyone who has written js code for the web has written this kind of if-statement: if (typeof gc === 'function') { var arr = []; arr[10000] = 'item'; gc(); asserteq(arr[10000], 'item', 'gc must not wipe out sparse array elements'); } else { print('test skipped: no gc function'); } reportcompare(0, 0, 'ok'); handling abnormal test terminations some tests can terminate abnormally even though the test has t...
...And 8 more matches
SpiderMonkey 1.8.7
you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz (md5 checksum: a4574365938222adca0a6bd33329cb32).
...on other platforms, the jit is simply disabled; javascript code runs in an interpreter, as in previous versions.
... spidermonkey 1.8.7 is not binary-compatible with previous releases, nor is it source-code compatible.
...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.
...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...
...ss is a type of code injection attack typically occurs in web applications injection of arbitrary data into an html document from another site victim’s browser executes those html instructions could be used to steal user credentials think: webmail, online auction, cms, online banking...
...And 8 more matches
nsICryptoHash
acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string.
...this can be either binary data or a base-64 encoded string.
...the following example shows how to compute the sha256 hash of a file: // hardcoded here for convenience var path = "c:\\windows\\notepad.exe"; var f = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); f.initwithpath(path); var istream = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream); // open for reading istream.i...
...And 8 more matches
Cache - Web APIs
WebAPICache
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.
...And 8 more matches
A basic 2D WebGL animation example - Web APIs
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.
...then we set the global gl_fragcolor to the value of the uniform uglobalcolor, which is set by the javascript code to the color being used to draw the square.
...And 8 more matches
Starting up and shutting down a WebXR session - Web APIs
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.
... 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.
...And 8 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.
...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.
...with the processor registered, you can create a new audioworkletnode which passes the audio through the processor's code when the node is linked into the chain of audio nodes along with any other audio nodes.
...And 8 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.
...And 8 more matches
filter - CSS: Cascading Style Sheets
WebCSSfilter
<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
Audio and Video Delivery - Developer guides
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.
...rs that don't support mp4 --> <source src="videofile.webm" type="video/webm"> <!-- specifying subtitle files --> <track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="english"> <track src="subtitles_no.vtt" kind="subtitles" srclang="no" label="norwegian"> <!-- fallback for browsers that don't support video tag --> <a href="videofile.mp4">download video</a> </video> the code above creates a video player of dimensions 640x480 pixels, displaying a poster image until the video is played.
... 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.
...And 8 more matches
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
it controls how your html source code is turned into web pages and, as such, changes to it are rare.
... changed parser behaviors some changes to the way that the gecko 2 parser behaves, as compared to earlier versions of gecko, may affect web developers, depending on how you've written your code in the past and what browsers you've tested it on.
...if you previously tested your code in ie and opera, then you probably don't have any tags like this.
...And 8 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
see encodeuri() for one way to do this.
... note: the above code snippet is taken from all world timezones in an html select element.
...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).
...And 8 more matches
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
maxlength the maximum number of characters (as utf-16 code units) the user can enter into the telephone number field.
... 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.
...And 8 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
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.
...it's a great way to modularize your code that's been available since firefox 3.
...And 7 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
extension code using internal linkage will need to migrate to use frozen linkage because internal linkage will not be available in firefox 3.
... this document is a guide to common code patterns that may need to change to work with frozen linkage.
...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.
...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 ...
...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 miscellaneous modules on page load page loading post data to window preferences 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 deploying a plugin as an extension developing add-ons displaying web content in an extension without security issues downloading json a...
...And 7 more matches
Developing New Mozilla Features - Archive of obsolete content
learn the codebase and coding practices before you start your feature include learning time in your schedule.
... mozilla is a complex codebase.
...become familiar with our code review processes.
...And 7 more matches
XUL Questions and Answers - Archive of obsolete content
he said the code will be open-source, but it is not released yet (as of oct 2006).
...the following is the code they wrote: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="test-window" title="check list test" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> <listbox rows="4"> <listhead> <listheader label="multi-column"/> </listhead> <listcols> <listcol flex="1"/> </listcols> <lis...
...(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?
...And 7 more matches
The Implementation of the Application Object Model - Archive of obsolete content
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.
...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.
...And 7 more matches
RDF in Mozilla FAQ - Archive of obsolete content
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>.
...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.
...the following code illustrates its usage: // this is the object that will observe the rdf/xml load's progress var observer = { onbeginload: function(asink) {}, oninterrupt: function(asink) {}, onresume: function(asink) {}, onendload: function(asink) { asink.removexmlsinkobserver(this); alert("done!"); }, onerror: function(asink, astatus, aerrormsg) { alert("error!
...And 7 more matches
The Business Benefits of Web Standards - Archive of obsolete content
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.
... increase website traffic maintain contact with your user on multiple platforms standards-based code and cross-platform go hand in hand.
...customers, developers, digital media creators, can be freed from the tyranny of graphics led development, code generators, and incomprehensible markup.
...And 7 more matches
Paddle and keyboard controls - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson4.html.
...add the following variables near the top of your code, beside your other variables: var paddleheight = 10; var paddlewidth = 75; var paddlex = (canvas.width-paddlewidth) / 2; here we're defining the height and width of the paddle and its starting point on the x axis for use in calculations further on down the code.
...we want to run some code to handle the paddle movement when the buttons are pressed.
...And 7 more matches
Test your skills: Links - Learn web development
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.
...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.
...And 7 more matches
Introduction to cross browser testing - Learn web development
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.
...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?
...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.
...And 7 more matches
Strategies for carrying out testing - Learn web development
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.
... 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.
...And 7 more matches
Git and GitHub - Learn web development
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.
... 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.
... 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.
...And 7 more matches
Developer guide
working with mozilla source code a code overview, how to get the code, and the coding style guide.
... code snippets useful code samples for a wide variety of things you might need to figure out how to do.
... debugging find helpful tips and guides for debugging mozilla code.
...And 7 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.
...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.
...knowing the path they will take through the various layers of the browser engine will help you optimize your code to avoid pitfalls.
...And 7 more matches
OS.File for the main thread
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.
... 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.
...it uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (typically because the computer is turned off, the battery runs out, or the application is stopped.) let encoder = new textencoder(); // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp"}); // buffer "file.txt.tm...
...And 7 more matches
Gecko Profiler FAQ
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.
... for native code, the profiler captures the necessary information but doesn’t have a way to display it.
...And 7 more matches
JSAPI Cookbook
/* * add this to your jscontext setup code.
...the jsapi code also has to return false to signal failure to the caller.
... // javascript throw exc; /* jsapi */ js_setpendingexception(cx, exc); return false; when js_reporterror creates a new error object, it sets the filename and linenumber properties to the line of javascript code currently at the top of the stack.
...And 7 more matches
XPCOM array guide
MozillaTechXPCOMGuideArrays
nsistringenumerator / nsiutf8stringenumerator - enumerators for strings obsolete arrays / enumerators there are some deprecated classes which should not be used by new code.
... 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.
...And 7 more matches
nsIContentViewer
= components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsicontentviewer); method overview void clearhistoryentry(); 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!
...dstart(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 resetclosewindow(); void setbounds([const] in nsintrectref abounds); native code only!
...And 7 more matches
nsIMsgDatabase
hdrforkey(in nsmsgkey key); nsimsgdbhdr getmsghdrformessageid(in string messageid); boolean containskey(in nsmsgkey key); nsimsgdbhdr createnewhdr(in nsmsgkey key); void addnewhdrtodb(in nsimsgdbhdr newhdr, in boolean notify); nsimsgdbhdr copyhdrfromexistinghdr(in nsmsgkey key, in nsimsgdbhdr existinghdr, in boolean addhdrtodb); void listallkeys(in nsmsgkeyarrayref outputkeys); native code only!
...in nsmsgkey key, in boolean breplied, in nsidbchangelistener instigator); void markforwarded(in nsmsgkey key, in boolean bforwarded, in nsidbchangelistener instigator); void markhasattachments(in nsmsgkey key, in boolean bhasattachments, in nsidbchangelistener instigator); void markthreadread(in nsimsgthread thread, in nsidbchangelistener instigator, in nsmsgkeyarrayptr thosemarked); native code only!
...read, 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); boolean isignored(in nsmsgkey key); boolean ismarked(in nsmsgkey key); boolean hasattachments(in nsmsgkey key); void markallread(in nsmsgkeyarrayptr thosemarked); native code only!
...And 7 more matches
Xptcall Porting Guide
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 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.
...And 7 more matches
Using COM from 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.
... 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.
...And 7 more matches
Browser Console - Firefox Developer Tools
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.
... 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.
...And 7 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.
... 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.
...And 7 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.
...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.
... it is for use by javascript code.
...And 7 more matches
Using Fetch - Web APIs
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.
... mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'content-type': 'application/json' // 'content-type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrerpolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: json.stringify(data) // body data type must match "content-type" header }); return response.json(); // parses json response into native jav...
...ascript objects } postdata('https://example.com/answer', { answer: 42 }) .then(data => { console.log(data); // json data parsed by `data.json()` call }); note that mode: "no-cors" only allows a limited set of headers in the request: accept accept-language content-language content-type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain sending a request with credentials included to cause browsers to send a request with credentials included, even for a cross-origin call, add credentials: 'include' to the init object you pass to the fetch() method.
...And 7 more matches
Using the Media Capabilities API - Web APIs
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.
... 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.
...And 7 more matches
SVGTransformList - Web APIs
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.
... 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.
... 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.
...And 7 more matches
SubtleCrypto.encrypt() - Web APIs
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.
... function getmessageencoding() { const messagebox = document.queryselector(".rsa-oaep #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(publickey) { let encoded = getmessageencoding(); return window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode.
...And 7 more matches
Adding 2D content to a WebGL context - Web APIs
a simple thing we can do is draw a simple square untextured plane, so let's start there, by building code to draw a square plane.
... the complete source code for this project is available on github.
...you write these in glsl and pass the text of the code into webgl to be compiled for execution on the gpu.
...And 7 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.
...And 7 more matches
Overview of events and handlers - Developer guides
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.
...(the talk is available from several sources, including this one.) currently, all execution environments for javascript code use events and event handling.
...this pattern can easily be followed using completely custom code, as explained in the article on custom events.
...And 7 more matches
Writing forward-compatible websites - Developer guides
this is especially important for intranets and other non-public websites; if we can't see your code, we can't see that it broke.
...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.
...And 7 more matches
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
maxlength the maximum number of characters (as utf-16 code units) the user can enter into the search field.
... 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
this - JavaScript
// 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.
... 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.
...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.
...And 7 more matches
Transitioning to strict mode - JavaScript
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.
...it is possible to change each file individually and even to transition code to strict mode down to the function granularity.
...they occur before the code is running.
...And 7 more matches
Media type and format guide: image, audio, and video content - Web media technologies
WebMediaFormats
this guide provides an overview of the media file types, codecs, and algorithms that may comprise media used on the web.
... media file types and codecs media containers (file types) a guide to the file types that contain media data.
... web audio codec guide a guide to the audio codecs allowed for by the common media containers, as well as by the major browsers.
...And 7 more matches
Performance fundamentals - Web Performance
all other things being equal, code optimized for some target besides user-perceived performance (hereafter upp) loses when competing against code optimized for upp.
...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 html/css layout and graphics code in gecko reduces invalidation and repainting for common cases like scrolling; developers get this support "for free".
...And 7 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.
... 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.
...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 7 more matches
page-mod - Archive of obsolete content
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.
...this makes your code easier to maintain, secure, debug and review.
...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.
...And 6 more matches
widget - Archive of obsolete content
so implementing a complete solution usually means you have to send messages between the content script and the main add-on code.
...this makes your code easier to maintain, secure, debug and review.
...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.
...And 6 more matches
loader/sandbox - Archive of obsolete content
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(sandbox, code, uri, line, version) evaluate code in sandbox, and return the result.
... code : string the code to execute.
...And 6 more matches
Creating Event Targets - Archive of obsolete content
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.
... using the places api first, let's write some code using places api that logs the uris of bookmarks the user adds.
...then open "index.js" and add the following code: var {cc, ci} = require("chrome"); var { xpcomutils } = require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { onitemadded: function(aitemid, afolder, aindex) { console.log("added ", bookmarkservice.getbookmarkuri(aitemid).spec); }, onitemvisited: function(aitemid, avisitid, time) { console.log("visited ", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; exports.main = function() { bookmarkser...
...And 6 more matches
Creating Reusable Modules - Archive of obsolete content
you can split your code into separate modules with clearly defined interfaces between them.
...we can adapt it like this: var {cc, ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } function md5file(path) { var f = cc["@mozilla.org/file/local;1"] .createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 04...
... var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } putting it together the complete add-on adds a button to firefox: when the user clicks the button, we ask them to select a file, compute the hash, and log the hash to the console: var {cc, ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } function md5...
...And 6 more matches
File I/O - Archive of obsolete content
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().
... 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.
...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.
...And 6 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
most of these methods are specific to a particular site or codebase.
...these requests can be tracked from chrome code using a variety of methods, including web progress listeners, http observers, and content policies.
... 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.
...And 6 more matches
Setting Up a Development Environment - Archive of obsolete content
« previousnext » getting the right tools there are 3 tools that we think are essential for effective add-on development (or any kind of development, really): a source code editor, a source control system, and a build system.
... in regards to code editing, there's no official mozilla ide.
...it can be installed on mac os x as part of the xcode tools package, and on windows with cygwin.
...And 6 more matches
Writing textual data - Archive of obsolete content
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.
... os.close(); you can also write character arrays using the write function, although using writestring is simpler from javascript code.
...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.
...And 6 more matches
Complete - Archive of obsolete content
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.
...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.
...And 6 more matches
Updating Commands - Archive of obsolete content
for other commands, you will need to use a couple of additional lines of code.
...fortunately, the extra code is fairly simple.
...a simple way of doing this is the following: var controller = document.commanddispatcher.getcontrollerforcommand("cmd_paste"); if (controller && controller.iscommandenabled("cmd_paste")){ controller.docommand(command); } the code above first retrieves the controller for the 'cmd_paste' command from the command dispatcher.
...And 6 more matches
Mozilla release FAQ - Archive of obsolete content
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 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.
...what are all of the codenames given to various netscape/mozilla projects?
...And 6 more matches
Developing cross-browser and cross-platform pages - Archive of obsolete content
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.
...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.
... // bad sample if (navigator.appversion.charat(0) == "8") { if (navigator.appname == "netscape") { isns8 = true; alert("netscape 8"); }; } else if (navigator.appversion.indexof("msie") != -1) { isie = true; alert("internet explorer"); }; while this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when internet explorer 8 is released or when an opera 8.x user visits the page or even when an user with any non-netscape browser starting with a "8" character in the appversion string visits that page.
...And 6 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
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.
...And 6 more matches
asm.js - Game development
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.
...And 6 more matches
Create the Canvas and draw on it - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson1.html.
...using your favourite text editor, create a new html document, save it 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 defi...
...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.
...And 6 more matches
Move the ball - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson2.html.
...the draw() function will be executed within setinterval every 10 miliseconds: 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.
...And 6 more matches
Debugging CSS - Learn web development
view source in comparison, is simply the html source code as stored on the server.
...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.
...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.
...And 6 more matches
Test your skills: Selectors - Learn web development
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.
... 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.
... 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.
...And 6 more matches
Legacy layout methods - Learn web development
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.
...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.
...And 6 more matches
Publishing your website - Learn web development
previous overview: getting started with the web next once you finish writing the code and organizing the files that make up your website, you need to put it all online so people can find it.
... this article explains how to get your simple sample code online with little effort.
...it allows you to upload code repositories for storage in the git version control system.
...And 6 more matches
General asynchronous programming concepts - Learn web development
normally, a given program's code runs straight along, with only one thing happening at once.
... 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.
...And 6 more matches
Test your skills: Events - Learn web development
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.
... 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.
...And 6 more matches
Test your skills: Math - Learn web development
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.
... 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).
... so, try updating the live code below to recreate the finished example, following these steps: create four variables that contain numbers.
...And 6 more matches
Test your skills: Strings - Learn web development
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.
... 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).
... 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.
...And 6 more matches
Test your skills: variables - Learn web development
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.
... 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).
... 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.
...And 6 more matches
JavaScript object basics - Learn web development
this contains very little — a <script> element for us to write our source code into.
...try entering the following line below the javascript code that's already in your file, then saving and refreshing: const person = {}; now open your browser's javascript console, enter person into it, and press enter/return.
... note: if you are having trouble getting this to work, try comparing your code against our version — see oojs-finished.html (also see it running live).
...And 6 more matches
Object building practice - Learn web development
let's start by adding the following constructor to the bottom of our code.
... save the code so far, and load the html file in a browser.
...add the following code at the bottom of your javascript file, to add an update() method to the ball()'s prototype: ball.prototype.update = function() { if ((this.x + this.size) >= width) { this.velx = -(this.velx); } if ((this.x - this.size) <= 0) { this.velx = -(this.velx); } if ((this.y + this.size) >= height) { this.vely = -(this.vely); } if ((this.y - this.size) <= 0) { this.vely =...
...And 6 more matches
Test your skills: Object basics - Learn web development
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.
... 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).
... 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.
...And 6 more matches
Componentizing our Svelte app - Learn web development
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/04-componentizing-our-app or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app remember to run npm install && npm run dev to start y...
... 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.
...And 6 more matches
Configuring Build Options
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 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.
...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.
...And 6 more matches
Simple Instantbird build
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").
... 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).
... get the latest source code from mozilla's comm-central mercurial code repository: hg clone http://hg.mozilla.org/comm-central then, get all the repositories it depends on.
...And 6 more matches
Simple Thunderbird build
18/10/2010 16:11 7,334 mapiaux.h 02/06/2009 17:02 7,938 mapicode.h 02/06/2009 17:02 22,960 mapidbg.h 02/06/2009 17:02 84,644 mapidefs.h 02/06/2009 17:02 27,840 mapiform.h 02/06/2009 17:02 11,880 mapiguid.h 02/06/2009 17:02 2,648 mapihook.h 02/06/2009 17:02 5,359 mapinls.h 02/06/2009 17:02 2,743 mapioid.h 02/06/2009 17:02 32,978 mapispi.h 02/06/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").
... 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).
...And 6 more matches
Following the Android Toasts Tutorial from a JNI Perspective
this article teaches developers how to port java code to jni by reading the java and android documentation.
... java code let's start with the following java code, which invokes a toast and says "hello, firefox!".
... context context = getapplicationcontext(); charsequence text = "hello, firefox!"; int duration = toast.length_short; toast toast = toast.maketext(context, text, duration); toast.show(); nativewindow code as mentioned earlier, toasts are a very popular feature, so mozilla developers chose to bring it to the privileged javascript scope via the nativewindow object.
...And 6 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.
...the callback receives a single parameter: the nsresult status code for the copy operation.
...And 6 more matches
Application Translation with Mercurial
check what is available for translation find out on which branch localization is done for your locale: read your localization team's page by clicking on the team with your language code (e.g.
... 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.
...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.
...And 6 more matches
Enc Dec MAC Output Public Key as CSR
nss sample code 5: encryption/decryption and mac and output public as a csr.
... generates encryption/mac keys and outputs public key as certificate signing request /* this source code form is subject to the terms of the mozilla public * license, v.
...\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
Invariants
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.
...but this is true only so long as we are actually in the interpreter or jit code.
...so code must check js_validcontextpointer(ownercx) before dereferencing it.
...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...
...lete since jsapi 36 js_evaluatescriptforprincipals obsolete since jsapi 30 js_evaluateucscriptforprincipals obsolete since jsapi 30 js_evaluatescriptforprincipalsversion obsolete since jsapi 30 js_evaluateucscriptforprincipalsversion obsolete since jsapi 30 you can instead compile javascript code into a jsscript which you can then execute multiple times.
...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
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.
... compiling it requires a c++ compiler, and the jsapi can only be used from c++ code.
... spidermonkey 24 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase.
...And 6 more matches
Preface
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.
...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.
...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++.
...And 6 more matches
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
in mozilla code, a stream is an object which represents access to a sequence of characters.
...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.
... a note about unicode strings versus nsiinputstream nsiinputstream and nsioutputstream work with 8-bit characters.
...And 6 more matches
nsIIDNService
interfaces.nsiidnservice); method overview autf8string convertacetoutf8(in acstring input); autf8string 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.
...And 6 more matches
nsIPushService
nsipushservice supports the push api implementation in firefox, and can be used directly from privileged code to create system subscriptions.
...privileged code should pass the system principal.
...interfaces: ci, utils: cu } = components; const scriptsecuritymanager = cc["@mozilla.org/scriptsecuritymanager;1"] .getservice(ci.nsiscriptsecuritymanager); const pushservice = cc["@mozilla.org/push/service;1"] .getservice(ci.nsipushservice); pushservice.subscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("error creating subscription: " + code); return; } // `subscription` implements `nsipushsubscription`.
...And 6 more matches
nsISocketTransport
to create an instance, call nsisockettransportservice.createtransport() method overview prnetaddr getpeeraddr(); native code only!
... prnetaddr getselfaddr(); native code only!
... nsitransporteventsink status codes note: although these constants look like xpcom error codes and are passed in an nsresult variable, they are not error codes.
...And 6 more matches
CloseEvent - Web APIs
closeevent.code read only returns an unsigned short containing the close code sent by the server.
... the following values are permitted status codes.
...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).
...And 6 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
here's the html markup generated by the javascript code: ...
... 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 to keep in mind the tree model for the structures you are planning to create; this will make it easier to write the necessary code.
...And 6 more matches
HTMLElement - Web APIs
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).
...And 6 more matches
Using the Resource Timing API - Web APIs
a live version of the examples is available on github, as is the source code.
...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.
...And 6 more matches
SVGLengthList - Web APIs
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.
... 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.
... 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.
...And 6 more matches
SVGNumberList - Web APIs
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.
... 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.
... 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.
...And 6 more matches
SVGPathSegList - Web APIs
exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified.
... exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified.
... exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified.
...And 6 more matches
SVGPointList - Web APIs
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.
... 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.
... 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.
...And 6 more matches
SVGStringList - Web APIs
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.
... 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.
... 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.
...And 6 more matches
SubtleCrypto.exportKey() - Web APIs
see the complete code on github.
...the exported key is then pem-encoded.
... see the complete code on github.
...And 6 more matches
SubtleCrypto.wrapKey() - Web APIs
see the complete code on github.
...*/ 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.
...see the complete code on github.
...And 6 more matches
Using textures in WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
... loading textures the first thing to do is add code to load the textures.
... the code that loads the texture looks like this: // // initialize a texture and load an image.
...And 6 more matches
Writing a WebSocket server in Java - Web APIs
although other server-side languages can be used to create a websocket server, this example uses oracle java to simplify the example code.
... 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.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.
...And 6 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
note: you can find the source code on github as step-sequencer; see the step-sequencer running live also.
...re: name of voice technique associated web audio api feature "sweep" oscillator, periodic wave oscillatornode, periodicwave "pulse" multiple oscillators oscillatornode "noise" random noise buffer, biquad filter audiobuffer, audiobuffersourcenode, biquadfilternode "dial up" loading a sound sample to play audiocontext.decodeaudiodata(), audiobuffersourcenode note: this instrument was not created to sound good, it was created to provide demonstration code and represents a very simplified version of such an instrument.
...noise is just random numbers when it comes to audio data, so is, therefore, a relatively straightforward thing to create with code.
...And 6 more matches
Web Audio API - Web APIs
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.
... 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.
...And 6 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
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 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.
...And 6 more matches
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
lar expression the value must match in order to be valid placeholder an example value to display in the field when the field is empty readonly a boolean attribute which, if present, indicates that the field's contents should not be editable size the number of characters wide the input field should be maxlength the maximum number of characters (as utf-16 code units) the user can enter into the password field.
... 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.
...And 6 more matches
Localization - Archive of obsolete content
the sdk supports localization of strings appearing in: your main add-on's javascript code html files packaged with your add-on the title, description and homepage fields of your add-on's metadata the title and description fields of your add-on's preferences.
... like: hello_id.accesskey= h the following attributes are supported: accesskey alt label title placeholder further the localization of the aria attributes aria-label, aria-valuetext and aria-moz-hint are supported with the same aliases as on firefox os: arialabel ariavaluetext ariamozhint using localized strings in javascript to reference localized strings from your main add-on code, you do this: var _ = require("sdk/l10n").get; console.log(_("hello_id")); assigning to "_" in particular is not required, but is a convention from the gettext tools and will make it possible to work with existing tools that expect "_" to indicate localizable strings.
...ngular form for "one", and a plural form for "everything else, including zero": one tomato no tomatoes two tomatoes but russian has different forms for numbers ending in 1 (except 11), numbers ending in 2-4 (except 12-14) and other numbers: один помидор // one tomato два помидора // two tomatoes пять помидоров // five tomatoes the sdk uses the unicode cldr data to describe the different plural forms used by different languages.
...And 5 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.
... simple dialog code the following xul code defines a simple dialog with two buttons, ok and cancel (buttons="accept,cancel" attribute on dialog).
...And 5 more matches
Windows - Archive of obsolete content
this article offers code snippets demonstrating common tasks you may wish to perform.
... 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.
...the following code does not care which element is clicked on, simply responding to all mousedown events equally.
...And 5 more matches
Downloading JSON and JavaScript in extensions - Archive of obsolete content
once the content has been downloaded, the extension authors proceed to use eval() to decode the string content into javascript objects.
... the practice is dangerous because the decoded javascript has full chrome privileges and could perform some nasty actions.
...json is about state and does not allow functions to be decoded.
...And 5 more matches
Intercepting Page Loads - Archive of obsolete content
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.
... 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.
...And 5 more matches
Localizing an extension - Archive of obsolete content
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.
...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.
...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.
...And 5 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
a flavor object has a name, which is a formatted like a mime type, such as 'text/unicode'.
...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.
...in this case above, the html flavour (text/html) comes first and then the text flavour (text/unicode).
...And 5 more matches
Documentation for BiDi Mozilla - Archive of obsolete content
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.
...And 5 more matches
JavaScript Client API - Archive of obsolete content
the best, and most up-to-date, reference to sync's internal apis is the source code.
...therefore, developers outside of the sync core should know that their code could require significant refactoring in future releases.
...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.
...And 5 more matches
LIR - Archive of obsolete content
in nanojit, lir is the source language for compilation to machine code.
...the lir instruction set is best learnt by reading nanojit/liropcode.tbl.
... code for manipulating lir is in nanojit/lir.h.
...And 5 more matches
Reading textual data - Archive of obsolete content
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"].
... 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 5 more matches
A XUL Bestiary - Archive of obsolete content
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 mozilla xparchitecture section below describes xpcom, xpidl, and xpconnect, three somewhat related technologies for getting access to application code from the interface.
...And 5 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
168 keycode xul attributes, xul reference 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.
...both types of builder share much of the same code except for how they generate output to be displayed.
...And 5 more matches
Introduction to XUL - Archive of obsolete content
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.
...our current code tends not to be strict about enforcing this, especially for tags and attributes in the html namespace.
..."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 ...
...And 5 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
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.
... title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> 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.
...And 5 more matches
Using the Editor from XUL - Archive of obsolete content
before each window is closed, javascript code in globaloverlay.js tries to call a trytoclose method on each window.
... nstexteditortextlistener the nsidomtextlistener interface that this implements is used by the ime code.
... nshtmleditor::editorkeypress() gets the character code from the key event, puts that into a string, and calls nshtmleditor::typedtext(), which simply calls nshtmleditor::inserttext().
...And 5 more matches
Building up a basic demo with PlayCanvas editor - Game development
this can be a more pleasant working environment if you are not someone who likes to code.
...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.
... if you double click on it, you'll be moved to a code editor.
...And 5 more matches
Bounce off the walls - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson3.html.
...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.
... the code above would deal with the ball bouncing off the top edge, so now let's think about the bottom edge: if(y + dy > canvas.height) { dy = -dy; } if the ball's y position is greater than the height of the canvas (remember that we count the y values from the top left, so the top edge starts at 0 and the bottom edge is at 320 pixels, the canvas' height), then bounce it off the bottom edge by rever...
...And 5 more matches
Initialize the framework - Game development
after completing this tutorial you can find the source code for this section at gamedev-phaser-content-kit/demos/lesson01.html.
...using your favourite text editor, create a new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev phaser workshop - lesson 01: initialize the framework</title> <style>* { padding: 0; margin: 0; }</style> <script src="js/phaser.min.js"></script> </head> <body> <script> var game = new phaser.game(480, 320, phaser.canvas, null, { preload: preload, create: create, update: update }); fun...
...ction preload() {} function create() {} function update() {} </script> </body> </html> downloading the phaser code next, we need to go through the process of downloading the phaser source code and applying it to our html document.
...And 5 more matches
Test your skills: CSS and JavaScript accessibility - Learn web development
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.
... 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.
...test the code to make sure the problem is now fixed.
...And 5 more matches
Test your skills: HTML accessibility - Learn web development
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.
... 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.
... 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.
...And 5 more matches
Organizing your CSS - Learn web development
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 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 ||.
...you will be able to recognise code that uses bem due to the extensive use of dashes and underscores in the css classes.
...And 5 more matches
Test your skills: values and units - Learn web development
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.
... task one in this task, the first list item has been given a background color using hex color codes.
... 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.
...And 5 more matches
Test your skills: Flexbox - Learn web development
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.
... 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.
... 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?
...And 5 more matches
Test your skills: Grid Layout - Learn web development
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.
... 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.
... 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?
...And 5 more matches
Practical positioning examples - Learn web development
our simple example will look like this once we are finished: note: you can see the finished example running live at info-box.html (source code).
... 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.
...put the following block of code, exactly as written in between your opening and closing <script> tags (you'll find these below the html content): var tabs = document.queryselectorall('.info-box li a'); var panels = document.queryselectorall('.info-box article'); for(i = 0; i < tabs.length; i++) { var tab = tabs[i]; settabhandler(tab, i); } function settabhandler(tab, tabpos) { tab.onclick = function() { for(i = 0; ...
...And 5 more matches
Sending forms through JavaScript - Learn web development
form data (application/x-www-form-urlencoded) is made of url-encoded lists of key/value pairs.
...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.
...And 5 more matches
CSS basics - Learn web development
previous overview: getting started with the web next css (cascading style sheets) is the code that styles web content.
... to make the code work, we still need to apply this css (above) to your html document.
... 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.
...And 5 more matches
Dealing with files - Learn web development
previous overview: getting started with the web next a website consists of many files: text content, code, stylesheets, media content, and so on.
...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.
... styles folder: this folder will contain the css code used to style your content (for example, setting text and background colors).
...And 5 more matches
Installing basic software - Learn web development
a text editor, to write code in.
...visual studio code, notepad++, sublime text, atom, gnu emacs, or vim), or a hybrid editor (e.g.
... web browsers, to test code in.
...And 5 more matches
Getting started with the Web - Learn web development
you'll set up the tools you need to construct a simple webpage and publish your own simple code.
...if you're just starting out, you might be confused by the array of code editors, frameworks, and testing tools out there.
... before you start writing the code for your website, you should plan it first.
...And 5 more matches
What’s in the head? Metadata in HTML - Learn web development
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).
... you should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser.
...And 5 more matches
Test your skills: Arrays - Learn web development
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.
... 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).
... 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.
...And 5 more matches
Object-oriented JavaScript for beginners - Learn web development
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.
...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.
... 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 5 more matches
Test your skills: JSON - Learn web development
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).
...this has something to do with async code.
... try updating the live code below to recreate the finished example: warning: to answer this question, you'll need to write your code into the live code window above.
...And 5 more matches
Test your skills: Object-oriented JavaScript - Learn web development
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.
... 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).
... 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.
...And 5 more matches
Website security - Learn web development
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.
...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.
... 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.
...And 5 more matches
Ember interactivity: Events, classes and state - Learn web development
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.
...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.
...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.
...And 5 more matches
Starting our Svelte Todo list app - Learn web development
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/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 you...
... 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.
...the intention is to encourage developers to write more accessible code "by default".
...And 5 more matches
Handling common accessibility problems - Learn web development
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.
... 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.
...take for example our fake-div-buttons.html example (see source code).
...And 5 more matches
Adding a new CSS property
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.
... 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.
... when writing the custom parsing code for a shorthand, you'll need to ensure that any successful parse sets all of the subproperties of the shorthand (since that's the way shorthands work in css).
...And 5 more matches
How Mozilla's build system works
if we need to write code for the build system, we do it in python 2 instead of editing a makefile.
...this is where we take all the code in the tree and produce the firefox binary program file or the application you are creating.
... all the code for reading moz.build files lives under /python/mozbuild/mozbuild/frontend/.
...And 5 more matches
Old Thunderbird build
windows build prerequisites gnu/linux build prerequisites mac os x build prerequisites 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").
... 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).
... get the latest source code from mozilla's comm-central mercurial code repository: hg clone https://hg.mozilla.org/comm-central then, get all the repositories it depends on.
...And 5 more matches
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.
...And 5 more matches
WebRequest.jsm
the webrequest api is modeled on chrome's webrequest extension api, which makes it easier to write cross-browser add-on code.
... usage to import webrequest, use code like: let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); the webrequest object has the following properties, each of which corresponds to a specific stage in executing a web request: onbeforerequest onbeforesendheaders onsendheaders onheadersreceived onresponsestarted oncompleted each of these objects defines two functions: addlistener(callback, filter, opt_extrainfospec) removelistener(callback) adding listeners use addlistener to add a listener to a particular event.
... statuscode number http response code.
...And 5 more matches
source-editor.jsm
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.
... 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.
...And 5 more matches
Index
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.
... 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.
... 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).
...And 5 more matches
Fonts for Mozilla 2.0's MathML engine
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.
...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.
...And 5 more matches
nss tech note4
pulling certificate extension information out of ssl certificates nss technical note: 4 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.
...name *name); char *cert_getcountryname(certname *name); char *cert_getlocalityname(certname *name); char *cert_getstatename(certname *name); char *cert_getorgname(certname *name); char *cert_getorgunitname(certname *name); char *cert_getdomaincomponentname(certname *name); char *cert_getcertuid(certname *name); example code to illustrate access to the info is given below.
... }; static const secitem myoiditem = { (secitemtype) 0, (unsigned char *)myoid, sizeof(myoid) }; secitem myextvalue; mycertextdata data; secstatus rv = cert_findcertextensionbyoid(cert, &myoiditem, &myextvalue); if (rv == secsuccess) { sec_asn1decodercontext * context = sec_asn1decoderstart(null, &data, mycertexttemplate); rv = sec_asn1decoderupdate( context, (const char *)(myextvalue.data), myextvalue.len); if (rv == secsuccess) { /* now you can extract info from secitem fields of your extension data structure */ /* see "misc helper functions" below */ .......
...And 5 more matches
Utility functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions atob_asciitodata mxr deprecated 3.2 use nssbase64_decodebuffer atob_convertasciitoitem mxr deprecated 3.2 use nssbase64_decodebuffer btoa_convertitemtoascii mxr deprecated 3.2 use nssbase64_encodeitem btoa_datatoascii mxr deprecated 3.2 use nssbase64_encodeitem der_asciitotime mxr 3.5 and later der_decodetimechoice mxr 3.9 and later der_encode mxr 3.4 and later der_encodetimechoice mxr 3.9 and later der...
... mxr 3.11.7 and later der_timetogeneralizedtime mxr 3.11.7 and later der_timetogeneralizedtimearena mxr 3.11.7 and later der_utcdaytoascii mxr 3.2 and later der_utctimetoascii mxr 3.2 and later der_utctimetotime mxr 3.2 and later dsau_decodedersig mxr 3.2 and later dsau_decodedersigtolen mxr 3.9 and later dsau_encodedersig mxr 3.2 and later dsau_encodedersigwithlen mxr 3.9 and later hash_begin mxr 3.4 and later hash_clone mxr 3.10 and later hash_create mxr ...
...And 5 more matches
GCIntegration - SpiderMonkey Redirect 1
this page is intended to explain the changes that are happening, with a focus on how they will affect gecko code that uses jsapi.
... 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.
...in between these slices, non-gc code is allowed to run.
...And 5 more matches
Property cache
when executing certain property-accessing bytecode instructions, the interpreter populates the cache to speed future execution of the same instruction.
... 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.
...And 5 more matches
JSErrorReport
uclinebuf const char16_t * unicode line buffer.
...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_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.
...And 5 more matches
JS_SetNativeStackQuota
syntax void js_setnativestackquota(jsruntime *cx, size_t systemcodestacksize, size_t trustedscriptstacksize = 0, size_t untrustedscriptstacksize = 0); name type description rt jsruntime * the runtime.
... systemcodestacksize size_t the desired stack quota setting, in bytes.
...if omitted, it uses the value of systemcodestacksize.
...And 5 more matches
SpiderMonkey 1.8.8
you can download full source code here: insert-actual-link-when-the-release-happens (md5 checksum: insert-actual-hash-here).
...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.
...spidermonkey 1.8.8 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase.
...And 5 more matches
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).
...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.
...spidermonkey 17 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase.
...And 5 more matches
Setting up CDT to work on SpiderMonkey
eclipse's cdt has some pretty decent features that make it an attractive environment to work in when you are interested in getting code hints, autocompletion, function, and field usage information and general ide goodness for c/c++.
... there is a guide for setting up cdt to work with the mozilla codebase, but it does not cover setting things up for just spidermonkey instead of the whole mozilla codebase.
... step 1 - preparing a spidermonkey build for cdt to index all code, spidermonkey has to be built with debug information.
...And 5 more matches
Using XPCOM Components
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.
...in fact, a search of the mozilla source code reveals that this cookiemanager component is called only from javascript.
... mozilla also has some tools that can find and display information about the interfaces available in gecko such as the xpcom component viewer, described below, and mxr, which is a web-based source code viewing tool.
...And 5 more matches
Components.lastResult
components.lastresult returns the numeric nsresult code that was the result code of the last xpcom method called via xpconnect.
... introduction generally, components.lastresult is only useful for testing the result of xpcom methods that can return interesting 'success' codes.
... this is because failure result codes get converted by xpconnect into exceptions that are thrown into the calling javascript method.
...And 5 more matches
Components.utils.import
components.utils.import was introduced in firefox 3 and is used for sharing code between different scopes easily.
... see using javascript code modules for more details.
... note: prior to gecko 2.0, javascript code modules could only be loaded using file: or resource: urls.
...And 5 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 ...
... 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.
...And 5 more matches
nsIDBFolderInfo
pertyname, in boolean defaultvalue); void getcharacterset(out acstring charset, out boolean 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!
...ertyvalue); void setcharacterset(in string charset); void setcharactersetoverride(in boolean charactersetoverride); obsolete since gecko 1.8 void setcharptrproperty(in string apropertyname, in string apropertyvalue); void sethighwater(in nsmsgkey highwater, in boolean force); void setlocale(in nsstring locale); native code only!
...And 5 more matches
nsIMsgHeaderParser
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.
... 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.
... 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).
...And 5 more matches
nsINavBookmarksService
9 obsolete since gecko 13.0 long long createfolder(in long long aparentfolder, in autf8string name, in long index); void endupdatebatch(); obsolete since gecko 1.9 void exportbookmarkshtml(in nsifile file); obsolete since gecko 1.9 nsiuri getbookmarkedurifor(in nsiuri auri); void 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!
...from c++ code inside the places component, use nsbookmarksupdatebatcher defined in nsnavbookmarks.h to scope batches.
...And 5 more matches
nsIUTF8ConverterService
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.
... aallowsubstitution when true, allow the decoder to substitute invalid input sequences by replacement characters.
...And 5 more matches
Reference Manual
which leads them to type in code that looks like this: nscomptr<nsifoo> foo( do_queryinterface(createbar()) ); // oops!
...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.
...And 5 more matches
CData
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.
... 8-bit strings are assumed to be encoded as utf-8.
...And 5 more matches
Set a logpoint - Firefox Developer Tools
sometimes you want to view a value in your code but you don't want to pause execution.
... rather than sprinkle console.log() statements throughout your code, you can use a special type of breakpoint, the logpoint.
... logpoints print a message to the console panel instead of pausing code execution.
...And 5 more matches
AddressErrors - Web APIs
postalcode a domstring which, if present, indicates that the postalcode property of the paymentaddress could not be validated.
... regioncode a domstring which, if present, indicates that the regioncode property of the paymentaddress could not be validated.
... sortingcode a domstring which, if present, indicates that the sortingcode property of the paymentaddress could not be validated.
...And 5 more matches
KeyboardEvent - Web APIs
the numlock key does not fall into this group and is always encoded with the location dom_key_location_standard.
... keyboardevent.code read only returns a domstring with the code value of the physical key represented by the event.
...if the key corresponds to a printable character, this value is a non-empty unicode string containing that character.
...And 5 more matches
Using server-sent events - Web APIs
you'll need a bit of code on the server to stream events to the front-end, but the client side code works almost identically to websockets in part of handling incoming events.
...s: true } ); once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtsource.onmessage = function(event) { const newelement = document.createelement("li"); const eventlist = document.getelementbyid("list"); newelement.innerhtml = "message: " + event.data; eventlist.appendchild(newelement); } this code listens for incoming messages (that is, notices from the server that 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.
...And 5 more matches
SubtleCrypto.decrypt() - Web APIs
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.
...And 5 more matches
SubtleCrypto.generateKey() - Web APIs
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.
...And 5 more matches
Controlling multiple parameters with ConstantSourceNode - Web APIs
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.
...ns-serif; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } .left { width: 50%; position: absolute; left: 0; display: table-cell; vertical-align: middle; } .left span, .left input { vertical-align: middle; } javascript now let's take a look at the javascript code, a piece at a time.
...let's look at the code.
...And 5 more matches
Window.open() - Web APIs
WebAPIWindowopen
*/ }; } </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.
...some code snippets are available.
...And 5 more matches
Window - Web APIs
WebAPIWindow
a global variable, window, representing the window in which the script is running, is exposed to javascript code.
... 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.
... 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.
...And 5 more matches
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.
...And 5 more matches
Using CSS transforms - CSS: Cascading Style Sheets
<table> <tbody> <tr> <th><code>perspective: 250px;</code> </th> <th><code>perspective: 350px;</code> </th> </tr> <tr> <td> <div class="container"> <div class="cube pers250"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top...
... <div class="container"> <div class="cube pers350"> <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> </td> </tr> <tr> <th><code>perspective: 500px;</code> </th> <th><code>perspective: 650px;</code> </th> </tr> <tr> <td> <div class="container"> <div class="cube pers500"> <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...
... html <section> <figure> <caption><code>perspective-origin: top left;</code></caption> <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> </figure> <figure> <caption><code>perspective-origin: top...
...And 5 more matches
text-transform - CSS: Cascading Style Sheets
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.
...the keyword target the first letter, that is the first unicode character part of the letter or number general category.
...the keyword target the first letter, that is the first unicode character part of the letter or number general category.
...And 5 more matches
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
maxlength the maximum number of characters (as utf-16 code units) the user can enter into the email input.
... 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.
... minlength the minimum number of characters (as utf-16 code units) the user can enter into the email input.
...And 5 more matches
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
maxlength the maximum number of characters (as utf-16 code units) the user can enter into the text input.
... 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.
... minlength the minimum number of characters (as utf-16 code units) the user can enter into the text input.
...And 5 more matches
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
maxlength the maximum number of characters (as utf-16 code units) the user can enter into the url input.
... 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.
... minlength the minimum number of characters (as utf-16 code units) the user can enter into the url input.
...And 5 more matches
HTTP authentication - HTTP
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 given resource, the server should respond with the 403 forbidden status code.
...And 5 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
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.
...another article for server developers discussing cross-origin sharing from a server perspective (with php code snippets) is supplementary reading.
...all the code knows is that an error occurred.
...And 5 more matches
Control flow and error handling - JavaScript
the semicolon (;) character is used to separate statements in javascript code.
...(in c or java, the equivalent code would have outputted 1.) since ecmascript2015, the let and const variable declarations are block-scoped.
...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
JSON.stringify() - JavaScript
// '{"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.
...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.
...And 5 more matches
async function - JavaScript
use of async / await enables the use of ordinary try / catch blocks around asynchronous code.
...top-level code, up to and including the first await expression (if there is one), is run synchronously.
... for example: async function foo() { await 1 } ...is equivalent to: function foo() { return promise.resolve(1).then(() => undefined) } code after each await expression can be thought of as existing in a .then callback.
...And 5 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
in this article, we look at how it is used in our js13kpwa example (see the source code also).
... they run on a separate thread from the main javascript code of our page, and don't have any access to the dom structure.
...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.
...And 5 more matches
Mobile first - Progressive web apps (PWAs)
you can see my mobile first example running live, or grab the code to play with it on github.
...the app's code files are inside the www folder.
... volo build: builds a minified code version of your app, ready for production deployment, in a www-built folder.
...And 5 more matches
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
it also may affect the direction in which characters are positioned if the unicode-bidi property's value is either embed or bidi-override.
... 226 u1 deprecated, svg, svg attribute 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.
... 227 u2 deprecated, svg, svg attribute 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.
...And 5 more matches
Tutorials
you'll set up the tools you need to construct a simple webpage and publish your own simple code.
...also includes a step-by-step guide to creating a basic web page with code examples.
... css tutorials introductory level css basics css (cascading style sheets) is the code you use to style your webpage.
...And 5 more matches
Content Processes - Archive of obsolete content
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.
...content scripts communicate with add-on code using something called event emitters.
...And 4 more matches
XUL Migration Guide - Archive of obsolete content
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 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.
...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.
...And 4 more matches
/loader - Archive of obsolete content
usage the code is intentionally authored so that it can be loaded in several ways.
... it can be loaded as a javascript code module: let { loader, require, unload } = components.utils.import('resource://gre/modules/commonjs/toolkit/loader.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 ?
... provide an environment for loading commonjs style modules, which makes it possible to consume lots of interesting code that has already been developed.
...And 4 more matches
Chrome Authority - Archive of obsolete content
from this you can access less-frequently-used properties like components.stack and components.issuccesscode.
...the sdk tools will emit a warning if it sees module code which references components directly.
...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.
...And 4 more matches
Unit Testing - Archive of obsolete content
if you're migrating test code from cfx to jpm, see the guide to migrating from cfx, in particular the section on loading modules from test code.
... the sdk provides a framework to help create and run unit tests for your code.
...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.
...And 4 more matches
Finding window handles - Archive of obsolete content
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.
...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.
...And 4 more matches
Miscellaneous - Archive of obsolete content
this page contains small, self-explanatory code snippets.
...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.
...-on-modify-request' observer topic: observerservice.addobserver(observer, 'http-on-modify-request', false); where "observer" is an object that has a method "observe": function observe(subject, topic, data) { subject.queryinterface(components.interfaces.nsiuploadchannel); postdata = subject.uploadstream; } here again, postdata is not a string, but an nsiinputstream, so you can use the last code snippet of the previous section to get the data as a string.
...And 4 more matches
Rosetta - Archive of obsolete content
the following code is nothing but the base for an extensible collection of compilers.
... 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.
...|*| |*| 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.
...And 4 more matches
Adding sidebars - Archive of obsolete content
the code required to add a sidebar is very simple, as explained in creating a firefox sidebar.
...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.
...And 4 more matches
Adding windows and dialogs - Archive of obsolete content
// 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.
... 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.
...there are some equivalent, simpler functions that are available in the window object, but those are meant for unprivileged html javascript code.
...And 4 more matches
Signing an extension - Archive of obsolete content
this article describes how to digitally sign your extension for firefox and thunderbird, with a code signing certificate for object signing.
...codesign.p12.
... nss-pk12util -i codesign.p12 -d .
...And 4 more matches
List of Mozilla-Based Applications - Archive of obsolete content
abstract accounting tool adobe acrobat and adobe reader portable document format (pdf) software uses mozilla spidermonkey adobe flash player popular browser plug-in uses nss in linux version adwatch content management system uses xul and xpcom aicpcu/iia exam app exam delivery software aliwal geocoder geocoding & data on a map amarok xul remote remote control for amarok music player ample sdk javascript gui-framework aol instant messenger im client uses nss apache web server doesn't use nss by default, but can be configured to use nss with mod_nss ssl module apicawatch site performance monitoring tool uses fir...
...efox 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 users ...
... eudora mail and news application the upcoming version 8 will be based on thunderbird evergreen library automation system evolution email client uses nss exe elearning xhtml editor seems to be using xul for some of their webui facebook open platform facebook open platform the fbml parser used in the platform is based on mozilla code fennec browser for mobiles as mark notes: fennec is not firefox, it’s a completely different application findthatfont!
...And 4 more matches
generateCRMFRequest() - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
... 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.
...after the "escrowauthoritycert" parameter, the method takes some javascript code that is invoked when the crmf request is ready.
...And 4 more matches
Monitoring downloads - Archive of obsolete content
onload: function() { // initialization code this.initialized = true; this.strings = document.getelementbyid("downloadlogger-strings"); this.dlmgr = components.classes["@mozilla.org/download-manager;1"] .getservice(components.interfaces.nsidownloadmanager); this.dlmgr.addlistener(downloadlogger); // open the database, placing its file in the profile directory this.dbfile = components.classes["...
... handling download state changes once the code above is run, our ondownloadstatechange() method is called whenever a download's state changes.
... 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.
...And 4 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
this is very powerful since you could make improvements to the underlying application logic without having to rewrite the higher level code.
...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.
...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.
...And 4 more matches
XPJS Components Proposal - Archive of obsolete content
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.
... 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 registration function that the js code calls (e.g.
...And 4 more matches
The Joy of XUL - Archive of obsolete content
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.
... 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.
... 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.
...And 4 more matches
Adding Event Handlers - Archive of obsolete content
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.
... responding to events the script will contain code which responds to various events triggered by the user or other situations.
...this is useful if there are several elements you would like to handle using the same or similar code.
...And 4 more matches
Document Object Model - Archive of obsolete content
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.
...for example, the following code will display the text 'message' in an alert twice.
...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.
...And 4 more matches
Keyboard Shortcuts - Archive of obsolete content
here are some additional examples: <keyset> <key id="copy-key" modifiers="control" key="c"/> <key id="explore-key" modifiers="control alt" key="e"/> <key id="paste-key" modifiers="accel" key="v"/> </keyset> keycode attribute the key attribute is used to specify the key that must be pressed.
...another attribute, keycode can be used for non-printable characters.
... the keycode attribute should be set to a special code which represents the key you want.
...And 4 more matches
XUL accessibility guidelines - Archive of obsolete content
by default, the tab order is determined by the order of the elements in the underlying code.
...do not specifically code them to open on a click of the right mouse button.
...view the code examples below.
...And 4 more matches
key - Archive of obsolete content
ArchiveMozillaXULkey
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.
... 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.
... 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.
...And 4 more matches
calICalendarView - Archive of obsolete content
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.
... interface code [scriptable, uuid(3e567ccb-2ecf-4f59-b7ca-bf42b0fbf24a)] interface calicalendarview : nsisupports { attribute calicalendar displaycalender; attribute calicalendarviewcontroller controller; void showdate(in calidatetime adate); void setdaterange(in calidatetime astartdate, in calidatetime aenddate); readonly attribute calidatetime startdate; readonly attribute calidatetime enddate; ...
... 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.
...And 4 more matches
Extentsions FAQ - Archive of obsolete content
write an xpcom component in c++ - it will talk to the com component and will be accessible to js code via xpconnect.
... use wm_copydata how to creating an extension that can replace html code on a specific page that does not use greasemonkey?
... 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?
...And 4 more matches
Adobe Flash - Archive of obsolete content
<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.
...a complete code listing which expands on the above approach can be found in the flashversion.js file used in the samples.
...the illustrative code snippet below shows this idea: <object id="myflash" .....
...And 4 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
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.
... the "objects" signed with object signing technology can be applets or other java code, javascript scripts, plug-ins, or any kind of file.
...used to identify signers of java code, javascript scripts, or other signed files.
...And 4 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.
...the tamarin codebase contains a cross-platform build system for mozilla developers.
...the tamarin codebase has the ability to build additional code which supports debugging hooks.
...And 4 more matches
Audio for Web games - Game development
if possible, you should try your code on several devices and platforms to see how it works.
... 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.
... const trackels = document.queryselectorall('li'); we want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audioctx.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we ...
...And 4 more matches
Implementing controls using the Gamepad API - Game development
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.
...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.
... demo the full version of the hungry fridge game was built first, and then to showcase the gamepad api in action and show the javascript source code, a simple demo was created.
...And 4 more matches
Build the brick field - Game development
you can find the source code as it would look after completing this lesson at gamedev-canvas-workshop/lesson6.html.
... 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.
...add the following lines to your code below the variables which you have previously declared in your program.
...And 4 more matches
Collision detection - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson7.html.
...for better readability of the code we will define the b variable for storing the brick object in every loop of the collision detection: function collisiondetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { var b = bricks[c][r]; // calculations } } } if the center of the ball is inside the coordinates of one of our bricks, we'll change the dire...
... 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.
...And 4 more matches
Build the brick field - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson09.html.
... 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 the initbricks() function at the end of our games code, just before the closing </script> tag, as shown below.
...And 4 more matches
Extra lives - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson13.html.
... 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.
...to make it easier for us to maintain in the future we can create a separate variable that will hold our styling, let's call it textstyle and place it before the text definitions: textstyle = { font: '18px arial', fill: '#0095dd' }; we can now use this variable when stlying our text labels — update your code so that the multiple instances of the text styling are replaced with the variable: scoretext = game.add.text(5, 5, 'points: 0', textstyle); 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); lifel...
...And 4 more matches
2D maze game with device orientation - Game development
starting with the project you can see cyber orb source code on github.
... src: the javascript files with all the source code of the game defined inside.
...after that some functionality will require further code to control — we will write our own functions to handle more complicated tasks.
...And 4 more matches
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... 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").
...And 4 more matches
Accessible multimedia - Learn web development
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.
...add it to your code, at the bottom: playpausebtn.onclick = function() { if(player.paused) { player.play(); playpausebtn.textcontent = 'pause'; } else { player.pause(); playpausebtn.textcontent = 'play'; } }; next, add this code to the bottom, which controls the stop button: stopbtn.onclick = function() { player.pause(); player.currenttime = 0; playpausebtn.textcontent = 'play'; }; the...
... next, our rewind and fast forward buttons — add the following blocks to the bottom of your code: rwdbtn.onclick = function() { player.currenttime -= 3; }; fwdbtn.onclick = function() { player.currenttime += 3; if(player.currenttime >= player.duration || player.paused) { player.pause(); player.currenttime = 0; playpausebtn.textcontent = 'play'; } }; these are very simple, just adding or subtracting 3 seconds to the currenttime each time they are clicked.
...And 4 more matches
WAI-ARIA basics - Learn web development
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.
... 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.
...And 4 more matches
Test your skills: The Box Model - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Test your skills: sizing - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Test your skills: Writing Modes and Logical Properties - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Test your skills: floats - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Test your skills: Multicol - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Responsive design - Learn web development
note: see this simple liquid layout: example, source code.
... note: see this simple fixed-width layout: example, source code.
...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.
...And 4 more matches
Test your skills: Basic controls - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Test your skills: Other controls - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Your first form - Learn web development
designing your form before starting to code, it's always better to step back and take the time to think about your form.
... in terms of html code we need something like the following to implement these form widgets: <form action="/my-handling-form-page" method="post"> <ul> <li> <label for="name">name:</label> <input type="text" id="name" name="user_name"> </li> <li> <label for="mail">e-mail:</label> <input type="email" id="mail" name="user_email"> </li> <li> <label for="msg">message:</label> <textarea id...
...="msg" name="user_message"></textarea> </li> </ul> </form> update your form code to look like the above.
...And 4 more matches
The web and web standards - Learn web development
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.
...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.
...examples include: the developer tools inside modern browsers that can be used to debug your code.
...And 4 more matches
Test your skills: HTML text basics - Learn web development
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.
...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.
... 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.
...And 4 more matches
Test your skills: HTML images - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Test your skills: Multimedia and embedding - Learn web development
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.
... 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.
... 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.
...And 4 more matches
Function return values - Learn web development
it's important to understand what their values are, how to use them in your code, and how to make functions return useful values.
... prerequisites: basic computer literacy, a basic understanding of html and css, javascript first steps, functions — reusable blocks of code.
...in the code above, the result of this return value is saved in the variable newstring.
...And 4 more matches
JavaScript building blocks - Learn web development
in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.
... 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.
...And 4 more matches
Manipulating documents - Learn web development
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.
...the html source code looks like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>simple dom example</title> </head> <body> <section> <img src="dinosaur.png" alt="a red tyrannosaurus rex: a two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."> <p>here we will add a link to the <a href="https://www.mozilla.o...
... 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.
...And 4 more matches
Basic math in JavaScript — numbers and operators - Learn web development
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 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.
... 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.
...And 4 more matches
Object prototypes - Learn web development
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.
...for example, try person1.__proto__ and person1.__proto__.__proto__ to see what the chain looks like in code!
... go back to our oojs-class-further-exercises.html example and make a local copy of the source code.
...And 4 more matches
Implementing feature detection - Learn web development
previous overview: cross browser testing next feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't), so that the browser can always provide a working experience rather than crashing/erroring in some browsers.
... 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.
...And 4 more matches
Gecko info for Windows accessibility vendors
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.
...inside the gecko process, code has full access to dom apis.
...And 4 more matches
Debugging on Windows
then use xpcom_debug_break=warn changing running code you normally shouldn't need to do this (just quit the application, set the environment variable described above, and run it again).
... it is possible to change the interrupt code in memory (which causes you to break into debugger) to be a nop (no operation).
...you should see some assembly code.
...And 4 more matches
ESLint
in order to help people write standard-compliant code from the start and avoid wasting time during code reviews, a set of eslint configuration files have been added to the code base so that javascript can be analyzed automatically.
... this automatic linting can happen either while coding, in a code editor, or when using the command line.
... running eslint eslint comprises of a set of rules that are used to analyse the code for correctness and style consistency.
...And 4 more matches
mach
mach (german for to make) is a program via the "command-line interface" to help developers perform installation tasks such as installing firefox from its c++ source code.
...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!
... most mach bugs are bugs in individual commands, not bugs in the core mach code.
...And 4 more matches
How to implement a custom autocomplete search component
there are actually two autocomplete mechanisms: an older mechanism that is part of the "xpfe" codebase and is used in older applications such as thunderbird and seamonkey.
...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.
...= 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
Emscripten
it takes llvm bytecode (e.g.
... 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)!
...And 4 more matches
Midas
introduction midas is the code name for gecko's built-in rich text editor.
... supported commands command value description backcolor a color code.
...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.
...And 4 more matches
An overview of NSS Internals
instead, the programmer will use lookup functions, and nss will provide an access handle that will be subsequently used by the application's code.
...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.
...And 4 more matches
Certificate functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions cert_addcerttolisttail mxr 3.2 and later cert_addextension mxr 3.5 and later cert_addocspacceptableresponses mxr 3.6 and later cert_addokdomainname mxr 3.4 and later cert_addrdn mxr 3.2.1 and later cert_asciitoname mxr 3.2 and later cert_cachecrl mxr 3.10 and later cert_clearocspcache mxr 3.11.7 and later cert_certchainfromcert mxr 3.2 and later cert_certlistfromcert mxr 3.2 and later cert_certtimesvalid mxr 3.2 and later cert_changecerttrust mxr 3.2 and later cert...
..._checkcertvalidtimes mxr 3.2 and later cert_checknamespace mxr 3.12 and later cert_checkcertusage 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.1 and later cert_createocspcertid mxr 3.6 and later cert_createocsprequest mxr 3...
...And 4 more matches
Getting Started With NSS
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.
...when you're satisfied with it, you'll need code review.
...And 4 more matches
NSS tools : certutil
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.
... in each category position, use none, any, or all of the attribute codes: + p - valid peer + p - trusted peer (implies p) + c - valid ca + t - trusted ca to issue client certificates (implies c) + c - trusted ca to issue server certificates (ssl only) (implies c) + u - certificate can be used for authentication or signing + w - send warning (use with ...
...And 4 more matches
Rhino overview
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).
...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.
...And 4 more matches
JS::DeflateStringToUTF8Buffer
this article covers features introduced in spidermonkey 38 encode the given string as utf8 into given buffer.
... numcharsp size_t* the pointer to receive the number of unicode characters written to the buffer.
... description js::deflatestringtoutf8buffer encodes src as utf8.
...And 4 more matches
WebReplayRoadmap
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.
... 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.
... 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.
...And 4 more matches
Mork
MozillaTechMork
mork is a database file format invented by david mccusker for the mozilla code since the original netscape database information was proprietary and could not be released open source.
...the information on this page was constructed by reading the source code of the mork database in mozilla and attempting to codify what it parses as faithfully as possible.
... in a few cases, constructs that the parser supported but were never used in mozilla's code are left unspecified.
...And 4 more matches
XPCOM changes in Gecko 2.0
this article details those changes, and provides suggestions for how to update your code.
...chrome.manifest: # the {classid} here must match the classid in mycomponent.js 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.
...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!
...And 4 more matches
Finishing the Component
all of the mozilla source code is publicly available, and interfaces can be used easily enough.
...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.
...when this method call is made, the code execution treats the isprime method as testa.
...And 4 more matches
Components object
warning: this object is only intended for code running with chrome privileges.
... exposing the object to regular web code was a mistake.
...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 ...
...And 4 more matches
mozIRegistry
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.
...currently, nsiservicemanager requires a clsid to access a service which hardcodes the implementation of that service.
...And 4 more matches
nsIAccessibleText
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.
...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.
...And 4 more matches
nsISHEntry
(in nsidocshelltreeitem shell); nsidocshelltreeitem childshellat(in long index); void clearchildshells(); nsishentry clone(); void create(in nsiuri uri, in astring title, in nsiinputstream inputstream, in nsilayouthistorystate layouthistorystate, in nsisupports 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!
...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 setuniquedocidentifier(); void seturi(in nsiuri auri); void setviewerbounds(in nsintrect bounds); native code only!
...And 4 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.
...And 4 more matches
nsIWebProgressListener
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.
... astatus error status code associated with the state change.
...the status code indicates success or failure of the request associated with the state change.
...And 4 more matches
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.
... loadgroup nsiloadgroup the load group of the websockets code.
... status codes the following values are permitted status codes.
...And 4 more matches
Getting Started Guide
with nscomptr, you can write code that is shorter, cleaner, clearer, and safer, than you can with raw xpcom interface pointers.
...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.
...And 4 more matches
XPIDL Syntax
MozillaTechXPIDLSyntax
status of this document this is a partial reverse-engineering of the libidl source code's parser, limited mostly to the subset of functionality that is supported by the mozilla xpidl binary.
...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 `%}'.
...And 4 more matches
Examine, modify, and watch variables - Firefox Developer Tools
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.
...in the screenshot below the variable upvar has been optimized away: modify variables when the code has stopped at a breakpoint, you can modify variables in the variables pane of the debugger.
...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.
...And 4 more matches
Set a breakpoint - Firefox Developer Tools
breakpoints in brief breakpoints are very useful when debugging javascript — you basically set a point in your code where you would like execution of the code to pause.
... continue to here: when stepping through code, this option tells the debugging to continue execution through to this point.
... unconditional breakpoints an unconditional breakpoint is one where the code will always pause execution when it is reached.
...And 4 more matches
Using the Debugger map scopes feature - Firefox Developer Tools
this feature is useful when debugging source-mapped code.
... 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.
...And 4 more matches
Deprecated tools - Firefox Developer Tools
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.
...once we have decided to remove the panel, we will provide a warning message, and finally, we will remove the panel from the codebase.
... description scratchpad provided an environment for experimenting with javascript code.
...And 4 more matches
Basic animations - Web APIs
if you don't want any user interaction you can use the setinterval() function which repeatedly executes the supplied code.
...note that the width and height specified here must match the values of the canvasxzsize and canvasysize variables in the javascript code.
...ion touch(t) { t.classlist.toggle("off"), document.getelementsbyclassname("keypress")[0].classlist.toggle("hide") } var t = new date + "", d = void 0, cc = document.getelementsbytagname("canvas")[0], c = cc.getcontext("2d"); key = {}, key.keydown = function (t) { var e = document.createevent("keyboardevent"); object.defineproperty(e, "keycode", { get: function () { return this.keycodeval } }), object.defineproperty(e, "key", { get: function () { return 37 == this.keycodeval ?
...And 4 more matches
Binary strings - Web APIs
WebAPIDOMStringBinary
javascript strings are utf-16 encoded strings.
... this means that each code unit requires two bytes of memory and is able to represent 65535 different code points.
... a subset of these strings is represented by utf-16 strings containing only ascii characters (i.e., characters whose code point does not exceed 127).
...And 4 more matches
Using files from web applications - Web APIs
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.
...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...
...And 4 more matches
Recommended Drag Types - Web APIs
the html drag and drop api supports dragging various types of data, including plain text, urls, html code, files, etc.
... note: in older code, you may find text/unicode or the text types.
...the data for this type should be serialized html source code.
...And 4 more matches
IDBObjectStoreSync - Web APIs
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.
... 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.
... 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.
...And 4 more matches
LockManager.request() - Web APIs
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.
... request a "shared" lock when multiple instances of the code can share access to a resource.
...And 4 more matches
Media Session API - Web APIs
ummyimage.com/192x192', sizes: '192x192', type: 'image/png' }, { src: 'https://dummyimage.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.
...And 4 more matches
RTCOutboundRtpStreamStats - Web APIs
framesencoded the number of frames that have been successfully encoded so far for sending on this rtp stream.
... 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.
...And 4 more matches
RTCPeerConnection.createAnswer() - Web APIs
the answer contains information about any media already attached to the session, codecs and options supported by the browser, and any ice candidates already gathered.
... deprecated parameters in older code and documentation, you may see a callback-based version of this function.
...you should update any existing code to use the promise-based version of createanswer() instead.
...And 4 more matches
RTCPeerConnection.createOffer() - Web APIs
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.
... 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.
... deprecated parameters in older code and documentation, you may see a callback-based version of this function.
...And 4 more matches
RTCPeerConnection - Web APIs
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.
...this happens when the ice gathering state—that is, whether or not the ice agent is actively gathering candidates—changes.onidentityresult the rtcpeerconnection.onidentityresult 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
RTCRtpCapabilities - Web APIs
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.
...And 4 more matches
RTCRtpStreamStats - Web APIs
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.
...this value will match that of the media type indicated by rtccodecstats.codec, as well as the track's kind property.
... 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.
...And 4 more matches
Using writable streams - Web APIs
inside this method, you should include code that sets up the stream functionality, e.g.
... the constructor call in our example looks like this: const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { str...
...eam: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); the write() method contains a promise including code that decodes each written chunk into a format that can be written to the ui.
...And 4 more matches
Lighting in WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
...we'll see how to do that when we look at the code for the shader.
... 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.
...And 4 more matches
Taking still photos with WebRTC - Web APIs
you can also jump straight to the code on github if you like.
... <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.
... the javascript code now let's take a look at the javascript code.
...And 4 more matches
Using bounded reference spaces - Web APIs
since not all hardware supports bounded reference spaces, you should made sure to support bounded reference spaces as an option rather than as a required feature unless you have special knowledge of the environment in which your code will run.
... you can create a session that supports a bounded-floor reference space if available by using code such as the following: async function onactivatexrbutton(event) { if (!xrsession) { navgator.xr.requestsession("immersive-vr"), { requiredfeatures: ["local-floor"], optionalfeatures: ["bounded-floor"] }).then((session) => { xrsession = session; startsessionanimation(); }); } } this function, called when the user clicks on a button to start the xr experience, works as usual, exiting at once if a session is already in place, then requesting a new session using immersive-vr mode.
...that means you need to change the code that calls requestreferencespace() to ask for a bounded reference space, then if that fails fall back to your backup choice, like this: let xrsession = null; let xrreferencespace = null; let spacetype = null; function onsessionstarted(session) { xrsession = session; spacetype = "bounded-floor"; xrsession.requestreferencespace(spacetype) .then(onrefspacecreated) .catch(() => { spa...
...And 4 more matches
Geometry and reference spaces in WebXR - Web APIs
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.
...And 4 more matches
Using the Web Audio API - Web APIs
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.
... check out the final demo here on codepen, or see the source code on github.
... 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).
...And 4 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
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.
... 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.
...And 4 more matches
overflow-wrap - CSS: Cascading Style Sheets
(<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.
... (<code>overflow-wrap: anywhere</code>)</p> <p>they say the fishing is excellent at lake <em class="ow-break-word">chargoggagoggmanchauggagoggchaubunagungamaugg</em>, though i've never been there myself.
... (<code>overflow-wrap: break-word</code>)</p> <p>they say the fishing is excellent at lake <em class="word-break">chargoggagoggmanchauggagoggchaubunagungamaugg</em>, though i've never been there myself.
...And 4 more matches
Creating a cross-browser video player - Developer guides
note: you can see the example running live, or check out the source code on github.
... the code above would allow playback of the video in most browsers, using the browser's default control set.
...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.
...And 4 more matches
Constraint validation - Developer guides
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.
... 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.
... constraint combining several fields: postal code validation the postal code format varies from one country to another.
...And 4 more matches
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
its value can, however, still be changed from javascript code that directly sets the value of the htmlinputelement.value property.
...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).
... the <select> for choosing the month is hardcoded with the names of the months, as they don't change (leaving localization out of things).
...And 4 more matches
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
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.
... 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.
...And 4 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
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.
... 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 valid for text, search, url, tel, email, and password, it defines the minimum number of characters (as utf-16 code units) the user can enter into the entry field.
...And 4 more matches
Data URLs - HTTP
otherwise, you can specify base64 to embed base64-encoded binary data.
... 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.
...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.
...And 4 more matches
Index - HTTP
WebHTTPHeadersIndex
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".
... 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.
...it lets the client know how to decode in order to obtain the media-type referenced by the content-type header.
...And 4 more matches
Indexed collections - JavaScript
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.
... 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.
...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.
...And 4 more matches
Character classes - JavaScript
\s matches a single white space character, including space, tab, form feed, line feed, and other unicode spaces.
... \cx matches a control character using caret notation, where "x" is a letter from a–z (corresponding to codepoints u+0001–u+001f).
... \xhh matches the character with the code hh (two hexadecimal digits).
...And 4 more matches
Regular expressions - JavaScript
unicode property escapes distinguish based on unicode character properties, for example, upper- and lower-case letters, math symbols, and punctuation.
... corresponding article \, ., \cx, \d, \d, \f, \n, \r, \s, \s, \t, \v, \w, \w, \0, \xhh, \uhhhh, \uhhhhh, [\b] character classes ^, $, x(?=y), x(?!y), (?<=y)x, (?<!y)x, \b, \b assertions (x), (?:x), (?<name>x), x|y, [xyz], [^xyz], \number groups and ranges *, +, ?, x{n}, x{n,}, x{n,m} quantifiers \p{unicodeproperty}, \p{unicodeproperty} unicode property escapes note: a larger cheatsheet is also available (only aggregating parts of those individual articles).
... regexp.prototype.dotall u "unicode"; treat a pattern as a sequence of unicode code points.
...And 4 more matches
Using Promises - JavaScript
here's some code that uses createaudiofileasync(): function successcallback(result) { console.log("audio file ready at url: " + result); } function failurecallback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, successcallback, failurecallback); modern functions return a promise that you can attach your callbacks to instead: if createaudiofileasync...
...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 re...
... one case of special usefulness: when writing code for node.js, it's common that modules you include in your project may have unhandled rejected promises.
...And 4 more matches
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.
... 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 ( “ ).
...And 4 more matches
Promise - JavaScript
for the following code, the transiton of promisea into a "settled" state will cause both instances of .then() to be invoked.
... // in this example, we use settimeout(...) to simulate async code.
...to understand this, start by scrolling to the bottom of the code block, and examine the promise chain.
...And 4 more matches
Authoring MathML - MathML
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.
...in thunderbird, you can use the "insert html" command to paste your html+mathml code.
... 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.
...And 4 more matches
Image file type and format guide - Web media technologies
svg files are text files containing source code that, when interpreted, draws the desired image.
... webp image webp supports lossy compression via predictive coding based on the vp8 video codec, and lossless compression that uses substitutions for repeating data.
... compression lossless (huffman, lz77, or color cache codes) or lossy (vp8).
...And 4 more matches
port - Archive of obsolete content
this article documents the port object, which is used to communicate between a content script and the main add-on code.
... the port object provides message sending and receiving api enabling conversations between a content script and the main add-on code.
... each end of the conversation has access to a port: the content script via the global self property, and the main add-on code via a worker object associated with the sdk module you've used to attach the content script, such as page-mod or page-worker.
...And 3 more matches
Communicating using "port" - Archive of obsolete content
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.
... 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.
... however, the worker is not exposed to add-on code in quite the same way in all modules.
...And 3 more matches
Modules - Archive of obsolete content
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.
...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.
...And 3 more matches
Module structure of the SDK - Archive of obsolete content
a commonjs module is a piece of reusable javascript: it exports certain objects which are thus made available to dependent code.
... 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 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.
...And 3 more matches
Two Types of Scripts - Archive of obsolete 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.
...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.
...And 3 more matches
page-worker - Archive of obsolete content
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.
... 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, this add-on loads a page from wikipedia, and runs a content script in it to send all the headers back to the main add-on code: var pageworkers = require("sdk/page-worker"); // this content script sends header titles from the page to the add-on: var script = "var elements = document.queryselectorall('h2 > span'); " + "for (var i = 0; i < elements.length; i++) { " + " postmessage(elements[i].textcontent) " + "}"; // create a page worker that loads wikipedia: pageworkers.page({ contentur...
...And 3 more matches
remote/parent - Archive of obsolete content
multiprocess firefox restricts the things that code running in child processes is allowed to do.
...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.
... process a process provides a way to communicate with code running in one of the application's processes.
...And 3 more matches
ui/frame - Archive of obsolete content
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().
...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.
... // 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.
...And 3 more matches
Display a Popup - Archive of obsolete content
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.
...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.
...And 3 more matches
HTML to DOM - Archive of obsolete content
the code snippets on this page will let your site work until these new features are more widely available.
...om into which we'll insert our newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textcontent = "this is inside the body!"; using a hidden iframe element to parse html to a window's dom sample code may need more work.
... as an example, i will show a browser overlay .xul file, and some javascript code to access it.
...And 3 more matches
JavaScript timers - Archive of obsolete content
a block of javascript code is generally executed synchronously.
... 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.
...And 3 more matches
Handling Preferences - Archive of obsolete content
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.
...each source is a js file that contains some special functions not available in regular code.
...And 3 more matches
Local Storage - Archive of obsolete content
the logger is called log4moz and it is implemented as a javascript code module, so it only works on firefox 3 and above.
...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?
...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.
...And 3 more matches
Mozilla Documentation Roadmap - Archive of obsolete content
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".
...in these cases you should dive into mozilla's source code and try to locate the code you need.
...it would be much better to be able to search and navigate through the huge code base with some ease.
...And 3 more matches
Observer Notifications - Archive of obsolete content
« previousnext » sometimes you need your code to send a message to other parts of your code.
... this example code shows you what an implementation of the nsiobserver interface looks like: let testobserver = { observe : function(asubject, atopic, adata) { if (atopic == "xulschoolhello-test-topic") { window.alert("data received: " + adata); } } } in order for this observer to work, you need to use the observer service that provides methods for you to add, remove, notify and enumerate ob...
...by non-chrome we mean javascript code modules or xpcom.
...And 3 more matches
Extensions support in SeaMonkey 2 - Archive of obsolete content
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.
...some important menu ids are listed below, menu ids are based on firefox 3 source code: menu id in firefox menu id in seamonkey 1.x and 2.0 seamonkey 2.1 overlays menu_filepopup menu_filepopup menu_filepopup file menu popup menu_editpopup menu_edit_popup menu_editpopup edit menu popup menu_viewpopup menu_view_popup menu_view_popup view menu popup ...
...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
Using Dependent Libraries In Extension Components - Archive of obsolete content
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.
...veleafname(ns_literal_cstring(krealcomponent)); prlibrary *lib; rv = library->load(&lib); if (ns_failed(rv)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_error_failure; return getmoduleproc(acompmgr, alocation, aresult); } extensions/stub/bdsstubloader.cpp (for mac os x) the code as written above won't work for mac os x.
.../* * 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.
...And 3 more matches
Adding preferences to an extension - Archive of obsolete content
get the code here: download the sample update the manifests the install manifest and chrome manifest need to be updated.
... 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.
... the javascript code in order to monitor changes to our preferences, we need to install an observer using the nsiprefbranch2 interface.
...And 3 more matches
Drag and Drop Example - Archive of obsolete content
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.
...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.
...var boardobserver = { getsupportedflavours : function () { var flavours = new flavourset(); flavours.appendflavour("text/unicode"); return flavours; }, ondragover: function (event, flavour, session) {}, ondrop: function (event, dropdata, session) { if (dropdata.data != "") { var elem = document.createelement(dropdata.data); event.target.appendchild(elem); elem.setattribute("left", "" + event.pagex); elem.setattribute("top", "" + event.pagey); elem.setattribute("label", dropdata...
...And 3 more matches
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.
...javascript code is sometimes designed to throw exceptions to report a result condition back to the c++ caller.
...And 3 more matches
Java in Firefox Extensions - Archive of obsolete content
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.").
... the following technique only works in javascript code linked from or contained in xul files.
...And 3 more matches
Example Sticky Notes - Archive of obsolete content
oke-width="1px"> <svg:circle cx="25px" cy="12px" r="12" fill="#ff0000" transform="translate(0,0)"/> <svg:circle cx="25px" cy="12px" r="12" fill="#00ff00" transform="translate(7,12)"/> <svg:circle cx="25px" cy="12px" r="12" fill="#0000ff" transform="translate(-7,12)"/> </svg:g> </svg:svg> <children/> </content> <implementation> <!-- here and futher cdata wrappers around javascript code are not mandatory but recommended.
...--> <constructor><![cdata[ /** * the code below will be called one time only after * the binding is successfully prepared and bound.
... */ // your code goes here ]]></constructor> <destructor><![cdata[ /** * the code below will be called one time only before * binding is unbound.
...And 3 more matches
XML in Mozilla - Archive of obsolete content
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/.
...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.
...And 3 more matches
cancelInstall - Archive of obsolete content
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.
...And 3 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
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.
...ow" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> oninput type: script code this event is sent when a user enters text in a textbox.
... onsearchbegin type: script code this event handler is called when the autocomplete search begins.
...And 3 more matches
Property Files - Archive of obsolete content
stringbundles you could write the code to read properties yourself, however xul provides the stringbundle element which does this for you.
...in addition, each occurrence of formatting code (e.g.
... you will notice the formatting codes %1$s and %2$s is used, and replaced different order in the array.
...And 3 more matches
XUL Structure - Archive of obsolete content
in fact, in mozilla, all document types, whether they are html or xul, or even svg, are all handled by the same underlying code.
...to the user, it may seem like the extension has modified the browser, but in reality, the code is all separate, and the extension may be easily uninstalled.
... 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.
...And 3 more matches
Using nsIXULAppInfo - Archive of obsolete content
starting with mozilla/xulrunner 1.8, there now is a way to find out which application, application version, and gecko version your code is running on.
...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.
...And 3 more matches
prefwindow - Archive of obsolete content
onbeforeaccept type: script code the code in this attribute is called when the ok button is pressed or the acceptdialog method is called.
... ondialogaccept type: script code the code in this attribute is called when the accept button is pressed, or when the acceptdialog method is called.
... ondialogcancel type: script code the code in this attribute is called when the "cancel" button is pressed or when the canceldialog method is called.
...And 3 more matches
Writing JavaScript for XHTML - Archive of obsolete content
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.
...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 3 more matches
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
ute ) atsc (advanced television systems committee ) ieee (institute of electrical and electronics engineers ) ietf (internet engineering task force ) irtf (internet research task force ) iso (international standards organization ) itu (international telecommunication union ) oasis (organization for the advancement of structured information standards ) oma (open mobile alliance ), uni (unicode consortium ) w3c (world wide web consortium ) 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.
...a fundamental mistake that many organizations make is to use proprietary methods, software, code, or standards.
...And 3 more matches
Index - Game development
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.
... 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).
...And 3 more matches
Game distribution - Game development
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.
... 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.
... instant updates you don't have to wait several days to have your game's code updated.
...And 3 more matches
Building up a basic demo with A-Frame - Game development
the <script> element includes the a-frame framework in the page; we will write our example code inside the <body> element.
...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.
...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.
...And 3 more matches
Unconventional controls - Game development
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.
...And 3 more matches
Efficient animation for web games - Game development
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.
...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.
...And 3 more matches
Collision detection - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson10.html.
... brick/ball collision detection the physics engine makes everything a lot easier — we just need to add two simple pieces of code.
...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!
...And 3 more matches
Load the assets and print them on screen - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson03.html.
...add the following line between the game initialization code (our var game...
... game.load.image('ball', 'img/ball.png'); } the first parameter we want to give the asset is the name that will be used across our game code — for example, in our ball variable name — so we need to make sure it is the same.
...And 3 more matches
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... 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.
... call stack list: - greeting execute all lines of code inside the greeting() function.
...And 3 more matches
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
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.
...And 3 more matches
Test your skills: WAI-ARIA - Learn web development
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.
... 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.
... 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.
...And 3 more matches
Test your skills: Overflow - Learn web development
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.
... 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.
... 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.
...And 3 more matches
Test your skills: backgrounds and borders - Learn web development
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.
... 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.
... 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.
...And 3 more matches
Test your skills: position - Learn web development
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.
... try updating the live code below to recreate the finished example: as an extra challenge, can you change the target to display underneath the text?
... 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.
...And 3 more matches
Getting started with CSS - Learn web development
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.
...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.
...And 3 more matches
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...
... windows, mac, linux forum official, unofficial yes textmate closed source $50 mac twitter, irc, mailing list, e-mail online manual, wiki yes textwrangler closed source free mac faq, forum pdf manual no vim specific open license free windows, mac, linux mailing list online manual yes visual studio code open source under mit licence/ specific licence for product free windows, mac, linux faq documentation yes active learning in this active learning section, we would like you to try using and/or installing a text editor of your choice.
... code completion.
...And 3 more matches
Test your skills: Advanced styling - Learn web development
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.
... 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.
... 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.
...And 3 more matches
Test your skills: HTML5 controls - Learn web development
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.
...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.
... 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.
...And 3 more matches
HTML Cheatsheet - Learn web development
that's the whole purpose of the cheatsheet, to give you some quick accurate ready to use code snippets for common usages.
... usage code snippet result a simple link <a href="https://realityripple.com/">a link to realityripple</a> a link to realityripple a simple image <img src="https://udn.realityripple.com/samples/6e/d6ed76c6c7.png" width="25" /> a generic inline container <p>p its used to <span style="color:blue">style and group</span> particular elements </p> p its used...
...it is used to suggest the browser to cut the text on this site if there is not enough space to display it on the same line date in readable form it is used to format the date legibly for the user, such as: <time datetime="2020-05-24" pubdate>published on 23-05-2020</time> it is used to format the date legibly for the user, such as: published on 23-05-2020 text displayed in code format <p>this text is in normal format.</p> <code>this text is in code format.</code> <pre>this text is in predefined format.</pre> this text is in normal format.
...And 3 more matches
Test your skills: Advanced HTML text - Learn web development
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.
... 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.
... 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.
...And 3 more matches
Responsive images - Learn web development
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.
...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.
...you can find an example of what this looks like in srcset-resolutions.html (see also the source code): <img srcset="elva-fairy-320w.jpg, elva-fairy-480w.jpg 1.5x, elva-fairy-640w.jpg 2x" src="elva-fairy-640w.jpg" alt="elva dressed as a fairy"> in this example, the following css is applied to the image so that it will have a width of 320 pixels on the screen (also called css pixels): img { width: 320px; } in this case, sizes is not needed — the browser...
...And 3 more matches
Image gallery - Learn web development
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.
... 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.
... you need to: put the section of code below the "looping through images" comment inside a loop that loops through all 5 images — you just need to loop through five numbers, one representing each image.
...And 3 more matches
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.
... 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.
...And 3 more matches
Silly story generator - Learn web development
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.
... initial variables and functions: in the raw text file, copy all of the code underneath the heading "1.
... copy the code found underneath the heading "3.
...And 3 more matches
Handling text — strings in JavaScript - Learn web development
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!
... 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.
...And 3 more matches
Adding features to our bouncing balls demo - Learn web development
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.
... at this point, try reloading the code — it should work just the same as it did before, with our redesigned objects.
...the following code block should be put inside the method definition: let _this = this; window.onkeydown = function(e) { if (e.key === 'a') { _this.x -= _this.velx; } else if (e.key === 'd') { _this.x += _this.velx; } else if (e.key === 'w') { _this.y -= _this.vely; } else if (e.key === 's') { _this.y += _this.vely; } } so when a key is pressed, the event object's keyc...
...And 3 more matches
Getting started with Ember - Learn web development
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.
... this language also enables lighter asset payloads due to compiling the templates into a "byte code" that can be parsed faster than javascript.
...later on in the tutorial, we'll focus on adding code to our application to fix some of todomvc's biggest faults.
...And 3 more matches
Accessibility in React - Learn web development
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.
...note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code.
...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.
...And 3 more matches
Componentizing our React app - Learn web development
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.
...open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that to todo.js too, as follows.
... in this code, we define the function and export it on the same line: export default function todo() { return ( ); } this is ok so far, but our component has to return something!
...And 3 more matches
Deployment and next steps - Learn web development
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/08-next-steps or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/08-next-steps remember to run npm install && npm run dev to start your app in development m...
...svelte analyzed our components and compiled the code to vanilla javascript.
...in which directory is your code located?
...And 3 more matches
Understanding client-side JavaScript frameworks - Learn web development
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.
... 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.
... 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.
...And 3 more matches
Introduction to automated testing - Learn web development
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.
... 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.
...And 3 more matches
Multiprocess on Windows
gecko and apartments most code that runs on gecko's main thread is not thread safe.
... enter the interceptor to achieve the best of both worlds, we wrote our own code to facilitate the safe handing off of an inbound rpc from the content process's mta to the content main thread's sta.
... this code lives in the mscom library, located in the tree at /ipc/mscom.
...And 3 more matches
Index
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.
...And 3 more matches
Creating a spell check dictionary add-on
a locale code to describe the language of the dictionary.
...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.
...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.
...And 3 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.
... browser console the browser console lets you see all javascript errors and logging in the browser, including from firefox code.
...And 3 more matches
Reviewer Checklist
submitting patches to mozilla source code needn't be complex.
... the patch does not add duplicates of existing code ('almost duplicates' could mean a refactor is needed).
... 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.
...And 3 more matches
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.
...this is an intentional design decision made to prevent content code from making chrome code unresponsive.
... content to chrome the frame script can choose to send synchronous or asynchronous messages to chrome code.
...And 3 more matches
Security best practices for Firefox front-end engineers
this article will help firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for firefox.
... existing security controls sanitizing all strings that enter the dom through apis such as innerhtml when running system-privileged chrome code, we sanitize all html fragments that are created for chrome-privileged documents.
...the canonical truth for the list of whitelisted elements is the source code.
...And 3 more matches
Embedding the editor
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.
...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.
...high-level ui and emebedding code should deal with this editing session interface, without knowledge of the underlying editors.
...And 3 more matches
PBackground
at build time the ipdl compiler automatically generates a large amount of c++ glue code from the ipdl files.
... writing code that works in both chrome and content processes a lot of code "just works" in the content process.
...this has lead to a rather awkward pattern seen in some parts of the gecko codebase, looking something like this (try searching for geckoprocesstype_default in dxr): if (xre_getprocesstype() == geckoprocesstype_default) { dothething(arguments); } else { mipdlprotocol->senddothething(arguments); } this can get unwieldy very quickly, so a better solution was needed.
...And 3 more matches
Examples
using a promise returned by a function (compact) the same code as the previous example is usually written with a more compact syntax: components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); os.file.exists(path).then(exists => { console.log(exists ?
... const {cu} = require("chrome"); const {textdecoder, textencoder, os} = cu.import("resource://gre/modules/osfile.jsm", {}); /* files: an array of file paths */ function readtextfiles(files) { let promises = [], decoder = new textdecoder(); for (let i = 0; i < files.length; i++) { let promise = os.file.read(files[i]) promise = promise.then(function onsuccess(array) { return decoder.decode(array); }); promises.push(...
...uncommet the var 2 lines above to see the promise succesfully return } catch(ex) { return promise.reject(ex); } } copy and paste this code and the rejection will take place.
...And 3 more matches
PromiseWorker.jsm
here is the test case from firefox codebase: mozilla dxr :: test_promise.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.
...finally, the template code should be added in.
...And 3 more matches
Localization and Plurals
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.
...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.
...And 3 more matches
Mozilla Web Developer FAQ
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?
... 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.
...And 3 more matches
NSS Certificate Download Specification
they are: der encoded certificate: this is a single binary der encoded certificate.
...this data must be base64 encoded as described by rfc 1113.
...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.
...And 3 more matches
JSS Provider Notes
it implements cryptographic operations in native code using the nss libraries.
... apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension.
...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 3 more matches
Mozilla-JSS JCA Provider notes
it implements cryptographic operations in native code using the nss libraries.
... apply for your own jce code-signing certificate following the procedure at how to implement a provider for the javatm cryptography extension.
... 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.
...And 3 more matches
NSS_3.12.1_release_notes.html
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.
... cert_encodesubjectkeyid (see cert.h) encode certificate skid (subject key id) extension.
... bug 311432: ecc's ecl_use_fp code (for linux x86) fails pairwise consistency test bug 330622: certutil's usage messages incorrectly document certain options bug 330628: coreconf/linux.mk should _not_ default to x86 but result in an error if host is not recognized bug 359302: remove the sslsample code from nss source tree bug 372241: need more versatile form of cert_nametoascii bug 390296: nss ignores subject cn even whe...
...And 3 more matches
NSS 3.12.4 release notes
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.
... 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.
...And 3 more matches
NSS sources building testing
getting the source code of network security services (nss), how to build it, and how to run its test suite.
... getting source code, and a quick overview the easiest way is to download archives of nss releases from mozilla's download server.
... (historical information: nspr and nss source code have recently been re-organized into a new directory structure.
...And 3 more matches
nss tech note3
certusageobjectsigner ........ used to verify signatures on files of executable code, e.g.
... the oid for this extension is { 2 5 29 19 }, encoded in hex as 0x55, 0x1d, 0x13.
...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.
...And 3 more matches
nss tech note8
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.
... the same cache/uncache api is used by both client and server code.
...And 3 more matches
NSS environment variables
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.
...note: the code must be built with pkix_object_leak_test defined to use this functionality.
... 3.11 ssldebug integer debug level note: the code must be built with debug defined to use this functionality.
...And 3 more matches
NSS tools : cmsutil
the options and arguments for the cmsutil command are defined as follows: -d decode a message.
...-c content use this detached content (decode only).
...-h num generate email headers with info about cms message (decode only).
...And 3 more matches
NSS_3.12.3_release_notes.html
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.
... bug 426413: audit messages need distinct types bug 438870: free freebl hashing code of dependencies on nspr and libutil bug 439115: db merge allows nickname conflicts in merged db bug 439199: sse2 instructions for bignum are not implemented on windows 32-bit bug 441321: tolerate incorrect encoding of dsa signatures in ssl 3.0 handshakes bug 444404: libpkix reports unknown issuer for nearly all certificate errors bug 452391: certutil -k incorrectly reports ec private ke...
...And 3 more matches
NSS tools : cmsutil
MozillaProjectsNSStoolscmsutil
the options and arguments for the cmsutil command are defined as follows: -d decode a message.
... -c content use this detached content (decode only).
... -h num generate email headers with info about cms message (decode only).
...And 3 more matches
JSPrincipals
codebase char * pointer to the codebase for the principal.
...a principals object is like a java codesource.
...these functions ensure that the given jsprincipals object is indelibly associated not only with the script being compiled or evaluated, but with all functions ever created by that script or code eval()-ed by it.
...And 3 more matches
JS_DecompileFunctionBody
generate the source code representing the body of a function, minus the function keyword, name, parameters, and braces.
... 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.
...And 3 more matches
SpiderMonkey 38
compiling it requires a c++ compiler, and the jsapi can only be used from c++ code.
... spidermonkey 38 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase.
... on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions.
...And 3 more matches
SpiderMonkey 45
you can download full source code from https://ftp.mozilla.org/pub/spidermonkey/releases/45.0.2/mozjs-45.0.2.tar.bz2 sha256: 570530b1e551bf4a459d7cae875f33f99d5ef0c29ccc7742a1b6f588e5eadbee md5: 2ca34f998d8b5ea79d8616dd26b5fbab spidermonkey 45 is the javascript engine that shipped in firefox 45.
... compiling it requires a c++ compiler, and the jsapi can only be used from c++ code.
... spidermonkey 45 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase.
...And 3 more matches
Split object
security privileges are granted to js code on the basis of the scope chain of the executing code.
......and yet, there is special code in jsobj.h with a comment about fixing some kind of interaction between with an split objects.
...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.
...And 3 more matches
SpiderMonkey: The Mozilla JavaScript runtime
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.
... gc rooting guide guide on how to write code compatible with the generational gc in spidermonkey.
...And 3 more matches
How to build an XPCOM component in JavaScript
this tutorial does not describe how and why xpcom works the way it does, or what every bit of the example code does.
...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.
... 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.
...And 3 more matches
Setting up the Gecko SDK
note that mozilla-config.h may be need to be included before other includes in your component's source code.
... 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.
... xpidl -m header ispecialthing.idl xpidl -m typelib ispecialthing.idl the code add the main code, the real work horse.
...And 3 more matches
Creating XPCOM components
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.
...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.
...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.utils.evalInSandbox
the evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.
...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.
...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.
...And 3 more matches
Observer Notifications
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.
... 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.
... content-document-global-created nsidomwindow origin sent immediately after a web content document window has been set up, but before any script code has been executed.
...And 3 more matches
nsIErrorService
xpcom/base/nsierrorservice.idlscriptable this is a service that allows nsresult codes to be mapped to string bundles that can be used to look up error messages.
...error modules are obtained from nsresult code with ns_error_get_module.
...geterrorstringbundlekey() retrieves a key in a string bundle for an nsresult error code.
...And 3 more matches
nsIMemoryReporterManager
from: nsisupports 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.
...void registermultireporter( in nsimemorymultireporter reporter ); parameters reporter an object implementing the nsimemorymultireporter interface which provides memory usage information for a given code area.
...And 3 more matches
nsISelectionController
inherits from: nsiselectiondisplay last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void characterextendforbackspace(); native code only!
... void characterextendfordelete(); native code only!
... void setcaretenabled(in boolean enabled); void setcaretreadonly(in boolean readonly); void setcaretvisibilityduringselection(in boolean visibility); void setcaretwidth(in short pixels); obsolete since gecko 1.8 void setdisplayselection(in short toggle); void wordextendfordelete(in boolean forward); native code only!
...And 3 more matches
XPCOM
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.
... some errors.language bindingsan xpcom language binding is a bridge between a particular language and xpcom to provide access to 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.
...often, compiled xpcom components are called 'binary' or 'native'.xpcom category image-sniffing-servicesin versions of firefox prior to firefox 3, extensions could add decoders for new image types.
...And 3 more matches
Address Book examples
the code stores uris in various places (e.g.
... 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.
...the best example of a binary implementation of an address book is the os x address book source code.
...And 3 more matches
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.
...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.
...And 3 more matches
Network request list - Firefox Developer Tools
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.
... keyword meaning examples status-code shows resources that have the specific http status code.
...And 3 more matches
Blob - Web APIs
WebAPIBlob
for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data.
... 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.
... 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.
...And 3 more matches
Manipulating video using canvas - Web APIs
this tutorial demonstrates how to perform chroma-keying (also known as the "green screen effect") using javascript code.
... the javascript code is imported from a script named processor.js.
... the javascript code the javascript code in processor.js consists of three methods.
...And 3 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
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.
... </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.
...And 3 more matches
FileError - Web APIs
WebAPIFileError
it extends the fileerror interface described in file writer and adds several new error codes.
...the objects have a code that shows the type of error that occurred.
... attribute attribute type description code unsigned short the most appropriate error code for the condition.
...And 3 more matches
IDBIndexSync - Web APIs
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.
... 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.
... 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.
...And 3 more matches
Intersection Observer API - Web APIs
since all this code runs on the main thread, even one of these can cause performance problems.
...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.
...And 3 more matches
Keyboard API - Web APIs
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.
...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.
...And 3 more matches
MediaDevices.getUserMedia() - Web APIs
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().
... 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.
...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).
...And 3 more matches
MediaError.message - Web APIs
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.
...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.
...And 3 more matches
Web-based protocol handlers - Web APIs
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.
...head> <title>web protocol handler sample - register</title> <script type="text/javascript"> navigator.registerprotocolhandler("web+burger", "http://www.google.co.uk/?uri=%s", "burger handler"); </script> </head> <body> <h1>web protocol handler sample</h1> <p>this web page will install a web protocol handler for the <code>web+burger:</code> protocol.</p> </body> </html> activating now, anytime the user activates a link that uses the registered protocol, the browser will route the action to the url supplied when the web application registered.
...so, using the above examples, the browser would perform a get on this url: http://www.google.co.uk/?uri=web+burger:cheeseburger server side code can extract the query string parameters and perform the desired action.
...And 3 more matches
RTCInboundRtpStreamStats.qpSum - Web APIs
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.
... 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
RTCOutboundRtpStreamStats.qpSum - Web APIs
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.
... 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
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.
... 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
SVGAngle - Web APIs
WebAPISVGAngle
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.
... 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.
... exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <angle>.
...And 3 more matches
SVGLength - Web APIs
WebAPISVGLength
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.
... 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.
... exceptions on setting: a domexception with code syntax_err is raised if the assigned string cannot be parsed as a valid <length>.
...And 3 more matches
SVGTransform - Web APIs
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.
... 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.
... 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.
...And 3 more matches
Matrix math for the web - Web APIs
multiplying a matrix and a point in our example code we have defined a function to multiply a matrix and a point — multiplymatrixandpoint(): // point • matrix function multiplymatrixandpoint(matrix, point) { // give a simple variable name to each part of the matrix, a column and row number let c0r0 = matrix[ 0], c1r0 = matrix[ 1], c2r0 = matrix[ 2], c3r0 = matrix[ 3]; let c0r1 = matrix[ 4], c1r1 = matrix[ 5], c2r1 = matrix[ 6], c3r1 = ma...
...in real production code it would be best to use optimized functions.
... first, here's code that rotates a point around the origin without using matrices.
...And 3 more matches
Animating objects with WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
... to actually animate, we need to add code that changes the value of squarerotation over time.
... we can do that by creating a new variable to track the time at which we last animated (let's call it then), then adding the following code to the end of the main function var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; drawscene(gl, programinfo, buffers, deltatime); requestanimationframe(render); } requestanimationframe(render); this code uses requestanimationframe to ask the browser to call the function "render" on each frame.
...And 3 more matches
Animating textures in WebGL - Web APIs
you can use similar code to use any sort of data (such as a <canvas>) as the source for your textures.
...you'll need to include it if you create your own project based on this code.
...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 3 more matches
Using DTMF with WebRTC - Web APIs
webrtc doesn't send dtmf codes as audio data.
...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.
...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.
...And 3 more matches
Visualizations with Web Audio API - Web APIs
note: you can find working examples of all the code snippets in our voice-change-o-matic demo.
... creating a waveform/oscilloscope to create the oscilloscope visualisation (hat tip to soledad penadés for the original code in voice-change-o-matic), we first follow the standard pattern described in the previous section to set up the buffer: analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); next, we clear the canvas of what had been drawn on it before to get ready for the new visualization display: canvasctx.clearrect(0, 0, width, height); we now...
... height/2; if(i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x += slicewidth; } finally, we finish the line in the middle of the right hand side of the canvas, then draw the stroke we've defined: canvasctx.lineto(canvas.width, canvas.height/2); canvasctx.stroke(); }; at the end of this section of code, we invoke the draw() function to start off the whole process: draw(); this gives us a nice waveform display that updates several times a second: creating a frequency bar graph another nice little sound visualization to create is one of those winamp-style frequency bar graphs.
...And 3 more matches
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
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.
... 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.
...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).
...And 3 more matches
Synchronous and asynchronous requests - Web APIs
synchronous requests block the execution of code which causes "freezing" on the screen and an unresponsive user experience.
... example: using a timeout you can use a timeout to prevent your code from hanging while waiting for a read to finish.
... this is done by setting the value of the timeout property on the xmlhttprequest object, as shown in the code below: function loadfile(url, timeout, callback) { var args = array.prototype.slice.call(arguments, 3); var xhr = new xmlhttprequest(); xhr.ontimeout = function () { console.error("the request for " + url + " timed out."); }; xhr.onload = function() { if (xhr.readystate === 4) { if (xhr.status === 200) { callback.apply(xhr, args); } else { console.error(xhr.statustext); } } }; xhr.open("get", url, true); xhr.timeout = timeout; xhr.send(null); } notice the addition of code to handle the "timeout" event by setting the ontimeout handler.
...And 3 more matches
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
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.
...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.
...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.
...And 3 more matches
perspective-origin - CSS: Cascading Style Sheets
html <section> <figure> <figcaption><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>pers...
...pective-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-origin: top right;</code></figcaption> <div class="container"> <div class="cube potr"> <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: left;</code><...
.../figcaption> <div class="container"> <div class="cube poml"> <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: 50% 50%;</code></figcaption> <div class="container"> <div class="cube pomm"> <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: right;</code></figcaption> <div class="con...
...And 3 more matches
<string> - CSS: Cascading Style Sheets
WebCSSstring
syntax the <string> data type is composed of any number of unicode characters surrounded by either double (") or single (') quotes.
...all characters can also be represented with their respective unicode code points in hexadecimal, in which case they are preceded by a backslash (\).
...in your code, however, strings can span multiple lines, in which case each new line must be escaped with a \ as the last character of the line.
...And 3 more matches
Cross-browser audio basics - Developer guides
this article provides: a basic guide to creating a cross-browser html5 audio player with all the associated attributes, properties, and events explained a guide to custom controls created using the media api basic audio example the code below is an example of a basic audio implementation using 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.
...owsers goes here --> <a href="audiofile.mp3">download audio</a> <object width="320" height="30" type="application/x-shockwave-flash" data="mediaelement-flash-video.swf"> <param name="movie" value="mediaelement-flash-video.swf" /> <param name="flashvars" value="controls=true&isvideo=false&file=audiofile.mp3" /> </object> </audio> note: you should be aware that flash and silverlight code require that the user has the appropriate plugin installed, and that the browser cannot guarantee the security aspects of code running on those plugin platforms.
...And 3 more matches
Index - Developer guides
WebGuideIndex
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.
... 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.
... 31 localizations and character encodings character encodings, html, localization, needsmarkupwork browsers process text as unicode internally.
...And 3 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
after that come the hexadecimal digits of the color code.
...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...
...n, 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 the hue's unit, it's assumed to be in degrees (deg).
...And 3 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
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.
... 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 rem...
...And 3 more matches
Warning - HTTP
WebHTTPHeadersWarning
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.
... 1xx warn-codes describe the freshness or validation status of the response and will be deleted by a cache after deletion.
...And 3 more matches
HTTP Messages - HTTP
WebHTTPMessages
http messages are composed of textual information encoded in ascii, and span over multiple lines.
... a status code, indicating success or failure of the request.
... common status codes are 200, 404, or 302 a status text.
...And 3 more matches
Arrow function expressions - JavaScript
thus, in the following code, the this within the function that is passed to setinterval has the same value as the this in the lexically enclosing function: function person(){ this.age = 0; setinterval(() => { this.age++; // |this| properly refers to the person object }, 1000); } var p = new person(); relation with strict mode given that this comes from the surrounding lexical context, strict mode rules with r...
... this code sample using chrome 81 demonstrates that arrow functions allow the creation of global variables in such situations (both for a concise body and for a normal function body): > f1 = x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; } x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; } > y vm51587:1 uncaught referenceerror: y is not defined at <anonymous>:1:1 (anonymous) @ vm51587:1 > f1(3) vm51533:1 x: 3, y: 3 4 > y 3 > f2 = x ...
... 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.
...And 3 more matches
Array.prototype.sort() - JavaScript
the default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of utf-16 code units values.
...if omitted, the array elements are converted to strings, then sorted according to each character's unicode code point value.
... 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.
...And 3 more matches
Intl.Collator() constructor - JavaScript
the following unicode extension keys are allowed: co variant collations for certain locales.
...this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence.
...this option can be set through an options property or through a unicode extension key; if both are provided, the options property takes precedence.
...And 3 more matches
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.
... 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.
...And 3 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.
... return value a string representing the character (exactly one utf-16 code unit) at the specified index.
... 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...
...And 3 more matches
WebAssembly.instantiate() - JavaScript
the webassembly.instantiate() function allows you to compile and instantiate webassembly code.
... this function has two overloads: the primary overload takes the webassembly binary code, in the form of a typed array or arraybuffer, and performs both compilation and instantiation in one step.
...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.
...And 3 more matches
import - JavaScript
this runs the module's global code, but doesn't actually import any values.
...this will run the code in the package entry point file (and any files it imports) only.
... (async () => { if (somethingistrue) { const { default: mydefault, foo, bar } = await import('/modules/my-module.js'); } })(); dynamic imports the standard import syntax is static and will always result in all code in the imported module being evaluated at load time.
...And 3 more matches
throw - JavaScript
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.
...And 3 more matches
var - JavaScript
description var declarations, wherever they occur, are processed before any code is executed.
... '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.
... 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.
...And 3 more matches
Types of attacks - Web security
(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.
... the malicious content often includes javascript, but sometimes html, flash, or any other code the browser can execute.
...And 3 more matches
Using custom elements - Web Components
} } 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.
...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.
... for example, take a look at this code from our popup-info-box-external-stylesheet example (see the source code): // apply external styles to the shadow dom const linkelem = document.createelement('link'); linkelem.setattribute('rel', 'stylesheet'); linkelem.setattribute('href', 'style.css'); // attach the created element to the shadow dom shadow.appendchild(linkelem); note that <link> elements do not block paint of the shadow root, so there may be a flash of unstyled content (fouc) while the stylesheet loads.
...And 3 more matches
Introduction to using XPath in JavaScript - XPath
note that, if the xpathexpression contains a namespace prefix, this will result in a domexception being thrown with the code namespace_err.
...contextnode.documentelement : contextnode.ownerdocument.documentelement ); or alternatively by using the <code>creatensresolver</code> method of a <code>xpathevaluator</code> object.
...var paragraphcount = document.evaluate( 'count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.numbervalue + ' paragraph elements' ); although javascript allows us to convert the number to a string for display, the xpath interface will not automatically convert the numerical result if the stringvalue property is requested, so the following code will not work: var paragraphcount = document.evaluate('count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.stringvalue + ' paragraph elements' ); instead, it will return an exception with the code ns_dom_type_error.
...And 3 more matches
Classes and Inheritance - Archive of obsolete content
as it turns out, it is possible to emulate classical inheritance using prototypal inheritance, but not without writing a significant amount of boilerplate code.
...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.
... 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.
...And 2 more matches
Contributor's Guide - Archive of obsolete content
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.
...And 2 more matches
base64 - Archive of obsolete content
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).
...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.
...And 2 more matches
request - Archive of obsolete content
if content is a string, it should be url-encoded (use encodeuricomponent).
...nested objects & arrays should encode safely.
...the default value is application/x-www-form-urlencoded.
...And 2 more matches
ui/sidebar - Archive of obsolete content
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.
... 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.
...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.
...And 2 more matches
Bookmarks - Archive of obsolete content
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.
... you can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksmenufolder to another folder attribute.
... 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").
...And 2 more matches
On page load - Archive of obsolete content
this article is for xul/javascript developers who want to have custom code executed each time a new page is loaded in browser/mail.
... if you need finer control over custom code execution—for example, as documents are loading or when tabs are switched—see progress listeners.
... // you can use it to make your code executed on certain pages only.
...And 2 more matches
Sidebar - Archive of obsolete content
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).
...for example the code below calls a function defined in the sidebar's context: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; // verify that our sidebar is open at this moment: if (sidebarwindow.location.href == "chrome://yourextension/content/whatever.xul") { // call "yournotificationfunction" in the sidebar's context: sidebarwindow.yournotificationfunction(anyarguments); } testing which sidebar is open the sidebar content may contain different panels (bookmarks, history, webpanel,...
...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
Enhanced Extension Installation - Archive of obsolete content
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.
... 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.
... }; 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.
...And 2 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
ref = "http://www.google.com/"; var text = "google"; $("body").append( $("<div>", { class: "foo" }) .append($("<a>", { href: href, text: text }) .click(function (event) { alert(event.target.href) })) .append($("<span>").text("foo"))); innerhtml with html escaping this method is a last resort which should be used only as a temporary measure in established code bases.
... 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.
...under no circumstances should code resembling 'callback("' + str + '")' appear anywhere in your add-on.
...And 2 more matches
Firefox addons developer guide - Archive of obsolete content
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).
... filenames should use <code> styling.
... variable and function names use <code> styling.
...And 2 more matches
Search Extension Tutorial (Draft) - Archive of obsolete content
if (localized) value = "data:text/plain," + encodeuricomponent(name + "=" + value.replace(/ /g, "\\u0020")); // save the original and new values.
...note: example uninstall code is only provided for restartless extensions.
... a separate tutorial exists for running code at uninstall in non-restartless extensions.
...And 2 more matches
Add-ons - Archive of obsolete content
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.
...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).
...in your extension's browser.xul overlay, write code which listens for a custom dom event.
...And 2 more matches
Enabling the behavior - updating the status periodically - Archive of obsolete content
now that we have code to retrieve tinderbox status and update the icon, we need to run it periodically.
... 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.
...And 2 more matches
Making it into a static overlay - Archive of obsolete content
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.
...integrating extensions into the mozilla codebase is beyond the scope of this tutorial, but for more information see mozilla.org's hacking documentation.
...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.
...And 2 more matches
Tinderbox - Archive of obsolete content
tinderbox is a web tool for tracking the status of the mozilla source code.
...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.
...And 2 more matches
Creating a Mozilla Extension - Archive of obsolete content
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
In-Depth - Archive of obsolete content
what appears in a tree view below is the actual code for the interface.
...what this will do is find the code for the back button and display it in the dom inspector.
...now that we have the code that will change the toolbar, it needs to be accessed.
...And 2 more matches
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
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.
...And 2 more matches
Message Summary Database - Archive of obsolete content
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.
...there are a set of generic property methods so that core code and extensions can set attributes on msg headers without changing nsimsghdr.idl.msg threads we store thread information persistently in the database and expose these object through the [nsimsgthread interface.
...And 2 more matches
Actionscript Acceptance Tests - Archive of obsolete content
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.
... (note that if a .err file is defined, the .exitcode file will be ignored).
...And 2 more matches
getLastError - Archive of obsolete content
getlasterror returns the most recent nonzero error code.
...returns the most recent nonzero error code.
... for a list of possible values, see return codes.
...And 2 more matches
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.
...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.
...And 2 more matches
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
just add code like this to your overlay: <toolbarpalette id="browsertoolbarpalette"> <toolbarbutton id="myextension-button" class="toolbarbutton-1" label="&toolbarbutton.label;" tooltiptext="&toolbarbutton.tooltip;" oncommand="myextension.ontoolbarbuttoncommand(event);"/> </toolbarpalette> notes: the id of the palette (browsertoolbarpalette in the example) depends on the window (the parent wind...
...this is the code to create and add it in.
...lbarbutton"); 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", main.action, false); toolbox.palette.appendchild(button); this code is thanks to dgutov and is seen in full context at his repository here at github: dgutov / bmreplace / bootstrap.js.
...And 2 more matches
Commands - Archive of obsolete content
commands provide a suitable way to abstract operations from the code.
...this means that code is all together and not scattered throughout the ui code.
...rather than repeat the code three times, you can hook all three up to the same command.
...And 2 more matches
More Event Handlers - Archive of obsolete content
in the attribute form of the event handler, the event object is an implied argument to the script code which can be referred to using the name 'event'.
...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.
...you can do this by subtracting the element's position from the event position, as in the following code.
...And 2 more matches
Tree View Details - Archive of obsolete content
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.
...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.
...And 2 more matches
Using Visual Studio as your XUL IDE - Archive of obsolete content
you can download it at xulschema.codeplex.com under the downloads tab.
...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.
...And 2 more matches
XUL Event Propagation - Archive of obsolete content
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.
...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".
...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.
...And 2 more matches
Building XULRunner with Python - Archive of obsolete content
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.
...it uses the trunk (or latest) code in cvs so may be unstable.
...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
application/http-index-format specification - Archive of obsolete content
number codes 100 a human readable comment line.
... 200 defines the field names for the 201 file index code.
...white space and 8 bit characters must be url encoded.
...And 2 more matches
Writing a plugin for Mac OS X - Archive of obsolete content
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.
...And 2 more matches
Error.number - Archive of obsolete content
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.
...And 2 more matches
Old Proxy API - Archive of obsolete content
do not rely on it for production code.
...if a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on the proxy.
... 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.
...And 2 more matches
Standards-Compliant Authoring Tools - Archive of obsolete content
creating cross-browser code upfront will save you lots of time quality testing your web content.
...if you're using older versions of tools that rely on old browser bugs or generate browser-specific code, it may be time to upgrade: nvu is a standalone editor created from the remains of mozilla composer.
... currently the work done on nvu is being ported back to mozilla source code.
...And 2 more matches
Archived open Web documentation - Archive of obsolete content
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.
...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.
... standards-compliant authoring tools creating cross-browser code upfront will save you lots of time quality testing your web content.
...And 2 more matches
Async scripts for asm.js - Game development
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).
... two common situations in which a script is *not* async (as defined by the html spec) are: <script async>code</script> and var script = document.createelement('script'); script.innerhtml = "code"; document.body.appendchild(script); both are counted as 'inline' scripts and get compiled and then run immediately.
...And 2 more matches
Move the ball - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson04.html.
...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.
...And 2 more matches
Visual-js game engine - Game development
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 .
...path object can be saved intro localhost , you can collect object and put it direct source code .
...And 2 more matches
Gecko FAQ - Gecko Redirect 1
gecko has been known previously by the code names "raptor" and "nglayout"; the new name was chosen following a trademark infringement dispute.
... 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?
...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.
...And 2 more matches
Plug-in Development Overview - Gecko Plugin API Reference
write your plug-in code and implement the appropriate plug-in api methods for basic plug-in operation.
... the resource code for this language and character set combination is 040904e4.
...the returned value is the unicode serialization of the document's origin converted to nfkc-encoded (that is, normalized) utf-8.
...And 2 more matches
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... 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.
...And 2 more matches
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.
...And 2 more matches
Advanced styling effects - Learn web development
you can find the examples in this section at box-shadow.html (see the source code too).
... 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.
...for more information and example code for css shapes see the guides to css shapes on mdn.
...And 2 more matches
Test your skills: Images and Form elements - Learn web development
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.
... 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.
... 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.
...And 2 more matches
Flexbox - Learn web development
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.
...they lead to a lot of extra code being written, and they can be somewhat confusing.
... 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.
...And 2 more matches
Test Your Skills: Fundamental layout comprehension - Learn web development
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 don't want to work locally then using a tool such as codepen or jsfiddle will work as well.
... 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.
...And 2 more matches
Fundamental text and font styling - Learn web development
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).
... my big red elephant monospace fonts where every character has the same width, typically used in code listings.
...you can either do this using offline html/css files, or enter your code into the live editable example below.
...And 2 more matches
Styling lists - Learn web development
the unstyled example is available on github (check out the source code too.) the html for our list example looks like so: <h2>shopping (unordered) list</h2> <p>paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference.</p> <ul> <li>hummus</li> <li>pita</li> <li>green salad</li> <li>halloumi</li> </ul> <h2>recipe (ordered) list</h2> <p>paragraph for reference, par...
... handling list spacing when styling lists, you need to adjust their styles so they keep the same vertical spacing as their surrounding elements (such as paragraphs and images; sometimes called vertical rhythm), and the same horizontal spacing as each other (you can see the finished styled example on github, and find the source code too.) the css used for the text styling and spacing is as follows: /* general styles */ html { font-family: helvetica, arial, sans-serif; font-size: 10px; } h2 { font-size: 2rem; } ul,ol,dl,p { font-size: 1.5rem; } li, p { line-height: 1.5; } /* description list styles */ dd, dt { line-height: 1.5; } dt { font-weight: bold; } the first rule sets a sitewide font and a b...
... playable code <div class="body-wrapper" style="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;"><ul> <li>first, light the candle.</li> <li>next, open the box.</li> <li>finally, place the three magic items in the box, in this exact order, to complete the spel...
...And 2 more matches
How do you set up a local testing server? - Learn web development
server-side languages (such as php or python) require a special server to interpret the code and deliver the results.
... 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.
...here are a few examples: to run python server-side code, you'll need to use a python web framework.
...And 2 more matches
What will your website look like? - Learn web development
discusses the planning and design work you have to do for your website before writing code, including "what information does my website offer?", "what fonts and colors do i want?", and "what does my site do?" first things first: planning before doing anything, you need some ideas.
...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.
...And 2 more matches
Document and website structure - Learn web development
in your html code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." as we mentioned earlier in the course, there are a number of consequences of not u...
... 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).
...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.
...And 2 more matches
HTML table advanced features and accessibility - Learn web development
save your code and open it in a browser to see what it looks like.
... 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.
...And 2 more matches
Video and Audio APIs - Learn web development
at the top of this file, insert the following code: const media = document.queryselector('video'); const controls = document.queryselector('.controls'); const play = document.queryselector('.play'); const stop = document.queryselector('.stop'); const rwd = document.queryselector('.rwd'); const fwd = document.queryselector('.fwd'); const timerwrapper = document.queryselector('.timer'); const timer = document.queryselector('.timer span'); cons...
... next, insert the 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.
... first of all, add the following to the bottom of your code, so that the playpausemedia() function is invoked when the play button is clicked: play.addeventlistener('click', playpausemedia); now to define playpausemedia() — add the following, again at the bottom of your code: function playpausemedia() { if(media.paused) { play.setattribute('data-icon','u'); media.play(); } else { play.setattribute('data-icon','p'); media.pause(); } } here we use an if statement to check whether the video is paused.
...And 2 more matches
Ember app structure and componentization - Learn web development
now we need to break up our html code into dynamic components; later we'll turn it into a fully interactive app.
... looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up the ui, but let's plan on splitting the html out into the following components: the component groupings are as follows: the main input / "new-todo" (red in the image) the containing body of the todo list + the mark-all-complete button (purple in the image) the mark-all-complete button, explicitly highlighted for reasons given below (yellow in the image) each todo is an individual component (green in the image) the footer (blue in the image) something odd to note is that the mark-all-complete checkbox (marked in yellow), while in the "main" section, is rendered next to the "new-todo" input.
... before we start adding any component code, let’s create the scaffolding for the other components.
...And 2 more matches
Adding a new event
this draft document covers how to add a new event to the mozilla (firefox) source code.
...this type of event is useful if the event isn't handled by c++ code.
...this type of event allows c++ code to handle it easier.
...And 2 more matches
Testopia
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.
... if you find bugs in the code available from the git repository, please report it to us so that we can fix most critical ones on time for testopia 3.0.
...And 2 more matches
Creating a Language Pack
d steps in the .mozconfig, you want to have mk_add_options moz_objdir=@topsrcdir@/obj-firefox-build ac_add_options --disable-compile-environment ac_add_options --with-l10n-base=../l10n-central # path relative to moz_objdir ac_add_options --enable-application=[browser or mail] the given path should have your localization directory as child (i.e., a subdirectory ab-cd where ab-cd is your locale code).
...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.
...And 2 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:...
...neleventsink) || aiid.equals(components.interfaces.nsiprogresseventsink) || aiid.equals(components.interfaces.nsihttpeventsink) || aiid.equals(components.interfaces.nsistreamlistener)) return this; throw components.results.ns_nointerface; } }; quick note: storing the channel in a global (especially in an extension) isn't a good idea, but was done to make the code easier to read.
... 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.
...And 2 more matches
Debugging
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.
... 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 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.
...And 2 more matches
Creating Custom Events That Can Pass Data
(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.
...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.
...you will find that there is a bunch of code like: if (aeventtype.lowercaseequalsliteral("{somethingsomething}event")) return ns_{somethingsomething}event(adomevent, aprescontext, nsnull); you can either have a function like this or write the code straight in nseventlistenermanager::createevent() like this: if (aeventtype.lowercaseequalsliteral("nsmyevent")){ //note: the lowercase is important!
...And 2 more matches
Displaying Places information using views
it runs code similar to the above when you set its place property or call its load method.
...if, on the other hand, you are writing a custom tree view, you will need to write similar code at some point.
...result.addobserver(myview.viewer); more practically, a variation of the code above might be internal to a method on your view.
...And 2 more matches
Performance
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.
... 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.
...And 2 more matches
Firefox
firefox is an open source project; much of the code is contributed by our huge community of volunteers.
... 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.
...And 2 more matches
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
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.
... in any case, you should at least download the repo and refer to the code as you read the sections below.
... 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.
...And 2 more matches
ChromeWorker
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.
...addons that wish to use file:// urls must first register a resource replacement path, using code like this: var fileuri = services.io.newfileuri(file); services.io.getprotocolhandler('resource').
... 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.
...And 2 more matches
HTTP Cache
the code resides in /network/cache2.
... 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.
... 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.
...And 2 more matches
PerfMeasurement.jsm
the perfmeasurement.jsm javascript code module lets you take detailed performance measurements of your code.
... note: the perfmeasurement.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on.
... before you can use this module, you need to import it into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") see measuring performance using the perfmeasurement.jsm code module for details on how to use this api.
...And 2 more matches
PopupNotifications.jsm
the popupnotifications.jsm javascript code module provides a popup notification box service.
... 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.
...And 2 more matches
Promise
if you see the message "a promise chain failed to handle a rejection", there is likely something to be fixed in the code.
... promise catch( function onreject ); the following calls are therefore identical: p.then(undefined, logerror); p.catch(logerror); debugging by design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the then() method.
... to help with debugging, only when inspecting a promise object manually, you can see more information as special properties that are inaccessible from code (this, at present, is implemented by randomizing the property name, for the lack of more sophisticated language or debugger support).
...And 2 more matches
Sqlite.jsm
the sqlite.jsm javascript code module is a promise-based wrapper around the storage/sqlite interface.
...this translates to fewer lines of code to talk to sqlite.
...this makes code easy to write and read.
...And 2 more matches
Bootstrapping a new locale
clone the source code the next step is to download a copy of the source code to your local system, using mercurial.
... 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.
... 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.
...And 2 more matches
Initial setup
as a pre-requisite to contributing to the l10n program, you need to have access to code, tools, and a properly configured local environment (i.e., your personal computer).
...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.
...And 2 more matches
QA phase
if you don't have a lot of experience with code, you might even be concerned that you've broken something (oops!).
... 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.
... to create and configure this file, follow these instructions: until the fix for bug 1063880 lands on mozilla-aurora and mozilla-beta when building language packs against those two trees you should: remove ac_add_options --disable-compile-environment from .mozconfig in step 3 use ./mach build config after step 4 update the mozilla source code: $ cd mozilla-aurora $ hg pull -u enter the following command to create the .mozconfig file: $ nano -w .mozconfig enter the following lines in your .mozconfig file: mk_add_options moz_objdir=@topsrcdir@/../firefox-build ac_add_options --disable-compile-environment ac_add_options --with-l10n-base=../l10n-central # path relative to moz_objdir ac_add_options --enable-application=[browser or...
...And 2 more matches
AsyncTestUtils extended framework
boilerplate add the following code to the top of your test file to import everything you need: load("../../mailnews/resources/loghelper.js"); load("../../mailnews/resources/asynctestutils.js"); load("../../mailnews/resources/messagegenerator.js"); load("../../mailnews/resources/messagemodifier.js"); load("../../mailnews/resources/messageinjection.js"); if the directory where you are adding the tests does not have a head_*.js file that has the two following lines, add them at the top of your test file (before the lines shown above): load("../../mailnews/resources/maildirservice.js"); load("..
... 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.
... synthetic message sets the code that creates synthetic message sets returns instances of the syntheticmessageset class.
...And 2 more matches
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?
...to find the certificate that matches the der-encoded certificate.
...And 2 more matches
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
is there any sample code and documentation?
... is there any sample code and documentation?
... 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 org/mozilla/jss/tests/keywrapping.java org/mozilla/jss/tests/listcerts.java org/mozilla/jss/tests/pk10gen.java org/mozilla/jss/tests/sdr.java org/mozilla/jss/tests/selftest.java org/mozilla/jss/tests/setupdbs.java ...
...And 2 more matches
NSS Key Log Format
<clientrandom> is 32 bytes random value from the client hello message, encoded as 64 hexadecimal characters.
... the following labels are defined, followed by a description of the secret: rsa: 48 bytes for the premaster secret, encoded as 96 hexadecimal characters (removed in nss 3.34) client_random: 48 bytes for the master secret, encoded as 96 hexadecimal characters (for ssl 3.0, tls 1.0, 1.1 and 1.2) client_early_traffic_secret: the hex-encoded early traffic secret for the client side (for tls 1.3) client_handshake_traffic_secret: the hex-encoded handshake traffic secret for the client side (for tls 1.3) server_handshake_traffic_secret: the hex-encoded handshake traffic secret for the server side (for tls 1.3) client_traffic_secret_0: the first hex-encoded application traffic secret for the client side (for tls 1.3) server_traffic_secret_0: the f...
...irst hex-encoded application traffic secret for the server side (for tls 1.3) early_exporter_secret: the hex-encoded early exporter secret (for tls 1.3, used for 0-rtt keys in older quic drafts).
...And 2 more matches
NSS Developer Tutorial
try to stay consistent when you modify existing code.
...when modifying existing code, try to stay consistent.
... in new code, prefer the former style, as it conserves vertical space.
...And 2 more matches
nss tech note7
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.
...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.
...And 2 more matches
NSPR functions
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.
...And 2 more matches
NSS tools : ssltab
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.
...-x turn on hex/ascii printing of undecoded data inside parsed ssl records.
...And 2 more matches
NSS tools : ssltap
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.
...-x turn on hex/ascii printing of undecoded data inside parsed ssl records.
...And 2 more matches
OLD SSL Reference
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.
... pk11_findcertfromnickname pk11_findkeybyanycert pk11_getslotname pk11_gettokenname pk11_ishw pk11_ispresent pk11_isreadonly pk11_setpasswordfunc chapter 8 nss and ssl error codes nss error codes are retrieved using the nspr function pr_geterror.
...And 2 more matches
S/MIME functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions nss_cmscontentinfo_getbulkkey mxr 3.2 and later nss_cmscontentinfo_getbulkkeysize mxr 3.2 and later nss_cmscontentinfo_getcontent mxr 3.2 and later nss_cmscontentinfo_getcontentencalgtag mxr 3.2 and later nss_cmscontentinfo_getcontenttypetag mxr 3.2 and later nss_cmscontentinfo_setbulkkey mxr 3.2 and later nss_cmscontentinfo_setcontent mxr 3.2 and later nss_cmscontentinfo_setcontent_data mxr 3.2 and later ...
... 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 Tools ssltap
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.
... -x turn on hex/ascii printing of undecoded data inside parsed ssl records.
...And 2 more matches
certutil
in each category position, use none, any, or all of the attribute codes: o p - valid peer o p - trusted peer (implies p) o c - valid ca o t - trusted ca to issue client certificates (implies c) o c - trusted ca to issue server certificates (ssl only) (implies c) o u - certificate can be used for authentication or signing o w - send warning (use wi...
...th other attributes to include a warning when the certificate is used in that context) the attribute codes for the categories are separated by commas, and the entire set of attributes enclosed by quotation marks.
...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.
...And 2 more matches
NSS tools : signtool
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.
...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.
...And 2 more matches
NSS tools : ssltap
MozillaProjectsNSStoolsssltap
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.
... -x turn on hex/ascii printing of undecoded data inside parsed ssl records.
...And 2 more matches
Rhino Debugger
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.
... 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.
...And 2 more matches
Performance Hints
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.
...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).
...And 2 more matches
JSPropertyOp
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.
...the getter callback is called each time javascript code accesses the property's value using the syntax obj.prop or obj[propname].
...And 2 more matches
JS_ConvertArguments
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.
...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.
...format can contain one or more instances of the following characters, as appropriate: character c type description b bool boolean c uint16_t ecma uint16_t, unicode character i int32_t ecma int32_t j int32_t ecma int32_t (used to be different, behaves like i now) obsolete since jsapi 28 u uint32_t ecma uint32_t d double ieee double i double integral ieee double s char * (c string) bug 607292 s jsstring * unicode string, accessed by a jsstring pointer ...
...And 2 more matches
JS_DecompileScript
return the source code of the script or the function.
... description js_decompilescript returns the source code of script.
...otherwise, it returns the original source code of the script.
...And 2 more matches
JS_InitClass
make a jsclass accessible to javascript code by creating its prototype, constructor, properties, and functions.
...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.
...(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.
...And 2 more matches
SpiderMonkey 31
compiling it requires a c++ compiler, and the jsapi can only be used from c++ code.
... spidermonkey 31 includes a just-in-time compiler (jit) that compiles javascript to machine code, for a significant speed increase.
... on all other platforms the jit is simply disabled; javascript code runs in an interpreter, as in previous versions.
...And 2 more matches
Mozilla Projects
it takes llvm bytecode (e.g.
... jshydra jshydra is a static analysis tool that is capable of performing analysis of general javascript code.
... midas midas is the code name for gecko's built-in rich text editor.
...And 2 more matches
Embedded Dialog API
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.
...And 2 more matches
Manipulating bookmarks using Places
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.
... you can easily change this code to insert the new folder into the bookmarks toolbar by changing bookmarksmenufolder to another folder attribute.
... 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").
...And 2 more matches
XPCOM glue
MozillaTechXPCOMGlue
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.
...then, the code must call xpcomgluestartup, which will dynamically link against the xpcom runtime.
... 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.
...And 2 more matches
XPCOM guide
MozillaTechXPCOMGuide
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.
...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).
...And 2 more matches
Components.utils.exportFunction
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 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.
...And 2 more matches
Components.utils
evalinsandbox() runs javascript code in a sandbox, usually used to run code with restricted privileges.
... evaluate javascript code in a less-privileged javascript context.
... 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).
...And 2 more matches
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.
...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.
...And 2 more matches
nsIAppShellService
lemented by: @mozilla.org/appshell/appshellservice;1 as a service: var appshellservice = components.classes["@mozilla.org/appshell/appshellservice;1"] .getservice(components.interfaces.nsiappshellservice); method overview void closetoplevelwindow(in nsixulwindow awindow); obsolete since gecko 1.8 void createhiddenwindow(in nsiappshell aappshell); native code only!
...lean caninteract); obsolete since gecko 1.8 void ensure1window(in nsicmdlineservice acmdlineservice); obsolete since gecko 1.8 void enterlastwindowclosingsurvivalarea(); obsolete since gecko 1.8 void exitlastwindowclosingsurvivalarea(); obsolete since gecko 1.8 void gethiddenwindowandjscontext(out nsidomwindow ahiddendomwindow, out jscontext ajscontext); native code only!
... native code only!createhiddenwindow creates a hidden window.
...And 2 more matches
nsIContentFrameMessageManager
parameters name type description aasciistring string ascii string to decode.
... returns string: the decoded binary data.
... parameters name type description abase64data string binary data to encode as base64.
...And 2 more matches
nsIDOMEvent
method overview boolean deserialize(in constipcmessageptr amsg, out voidptr aiter); violates the xpcom interface guidelines void duplicateprivatedata(); native code only!
...boolean isdispatchstopped(); violates the xpcom interface guidelines void preventbubble(); obsolete since gecko 24 void preventcapture(); obsolete since gecko 24 void preventdefault(); void serialize(in ipcmessageptr amsg, in boolean aserializeinterfacetype); violates the xpcom interface guidelines void settarget(in nsidomeventtarget atarget); native code only!
... void settrusted(in boolean atrusted); native code only!
...And 2 more matches
nsIDragService
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.
... method overview void enddragsession( in prbool adonedrag ) ; void dragmoved(in long ax, in long ay); native code only!
... void firedrageventatsource(in unsigned long amsg); obsolete since gecko 43 void firedrageventatsource(in mozilla::eventmessage aeventmessage); native code only!
...And 2 more matches
nsIFrameLoader
method overview void activateframeevent(in astring atype, in boolean capture); void activateremoteframe(); void destroy(); void loadframe(); void loaduri(in nsiuri auri); void sendcrossprocesskeyevent(in astring atype, in long akeycode, in long acharcode, in long amodifiers, [optional] in boolean apreventdefault); void sendcrossprocessmouseevent(in astring atype, in float ax, in float ay, in long abutton, in long aclickcount, in long amodifiers, [optional] in boolean aignorerootscrollframe); void updatepositionandsize(in nsiframe aiframe); native code only!
... void sendcrossprocesskeyevent( in astring atype, in long akeycode, in long acharcode, in long amodifiers, [optional] in boolean apreventdefault ); parameters atype the event type.
... akeycode the key code.
...And 2 more matches
nsIPlacesImportExportService
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.
... 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.
...And 2 more matches
nsIProgressEventSink
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.
...And 2 more matches
nsIScriptError
category a string indicating what kind of code caused the message.
... 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.
...And 2 more matches
nsISmsRequestManager
aerror a number with an error code.
...aerror a number with an error code.
...aerror a number with an error code.
...And 2 more matches
nsISocketTransportService
to create an instance, use: var sockettransportservice = components.classes["@mozilla.org/network/socket-transport-service;1"] .getservice(components.interfaces.nsisockettransportservice); 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!
...obsolete since gecko 1.8 methods native code only!
...And 2 more matches
nsIStructuredCloneContainer
you can also get a base-64-encoded string containing a copy of the container's serialized data, using getdataasbase64().
...getdataasbase64() get this structured clone container's data as a base-64-encoded string.
...return value a base-64-encoded string.
...And 2 more matches
nsITransferable
void init(in nsiloadcontext acontext); boolean islargedataset( ); void removedataflavor( in string adataflavor ); void settransferdata( in string aflavor, in nsisupports adata, in unsigned long adatalen ); attributes attribute type description converter nsiformatconverter an nsiformatconverter instance which implements the code needed to convert data into and out of the transferable given the supported flavors.
...native code only!
...native code only!
...And 2 more matches
nsITreeView
1.8 progress_none 3 note: renamed from progressnone in gecko 1.8 drop_before -1 drop_on 0 drop_after 1 indropbefore 0 obsolete since gecko 1.8 indropon 1 obsolete since gecko 1.8 indropafter 2 obsolete since gecko 1.8 methods candrop() methods used by the drag feedback code to determine if a drag is allowable at the current location.
... 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.
... 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.
...And 2 more matches
nsIWebSocketListener
last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview void onacknowledge(in nsisupports acontext, 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 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.
...And 2 more matches
nsIWindowsRegKey
native code only!
...readstringvalue() this method reads the string contents of the named value as a unicode string.
... return value the string contents of the named value as a unicode string.
...And 2 more matches
Storage
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.
...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).
... 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.
...And 2 more matches
XPCOM tasks
there is likely to be code outside of xpcom that should be in it.
... there is code above xpcom that should be below it.
... 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.
...And 2 more matches
nsIMsgCloudFileProvider
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.
... if awithui is false, and the credentials are stale, the onstoprequest of the acallback nsirequestlistener will get the autherr status code passed to it.
... providerurlforerror() for an error code, for example uploadwouldexceedquota, a provider might have a url with information on how to deal with that error.
...And 2 more matches
MailNews Filters
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.
...the protocol specific code will then apply all of the actions of the filter to the current msg header.
... how to add a filter action add your new action to nsimsgfilteraction add code to file out the new action here add new action to the rulesactiontable add string for the new action to the filter editor dtd file add new action to the filter editor js code add new action to the xbl widget in the filter editor if your action has a parameter, add code to initialize the ui editing an existing filter here and to save to the filter here add your action to filter.properties so...
...And 2 more matches
Thunderbird Binaries
they are built every 24 hours by the tinderboxes from the very latest source code.
... nightly builds from the comm-central trunk the trunk is the central source code that is used for continuous and ongoing development.
... the trunk is the central source code that is used for continuous and ongoing development.
...And 2 more matches
Zombie compartments
roughly speaking, all memory used by javascript code that is from a particular origin (i.e.
... firefox’s own javascript code also gets one or more compartments and so do add-on scripts.
...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...
...And 2 more matches
Declaring and Using Callbacks
this is very powerful, since it allows native code to transparently call into javascript.
...consider the following code: function myjscallback(foo, bar) { ....
...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.
...And 2 more matches
Standard OS Libraries
you just need to supply the path to appropriate files and set up the proper types of values/arguments in the js-ctypes code.
...gtk+ and qt have begun porting their code to wayland.
... 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.
...And 2 more matches
Using js-ctypes
before you can use js-ctypes, you need to import the ctypes.jsm code module.
... this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use.
... once you've declared the types and functions, you can write your code to make use of them.
...And 2 more matches
Plug-in Development Overview - Plugins
write your plug-in code and implement the appropriate plug-in api methods for basic plug-in operation.
... the resource code for this language and character set combination is 040904e4.
...the returned value is the unicode serialization of the document's origin converted to nfkc-encoded (that is, normalized) utf-8.
...And 2 more matches
Scripting plugins - Plugins
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.
... 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.
... this way such code can be executed with only the privileges of the origin of the code, and not the privileges of the plugin page's origin.
...And 2 more matches
Debugging service workers - Firefox Developer Tools
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 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.
...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.
...And 2 more matches
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
(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.
...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.
...after the count, we see the function name, and the source code location of the call site or allocation.
...And 2 more matches
Call Tree - Firefox Developer Tools
by analyzing its results, you can find bottlenecks in your code - places where the browser is spending a disproportionately large amount of time.
...it periodically samples the state of the javascript engine and records the stack for the code executing at the time.
...if your site is making the browser work hard, this might not show up as samples recorded in your code, but it is still your problem.
...And 2 more matches
Intensive JavaScript - Firefox Developer Tools
here's the code, together with its immediate caller: const iterations = 50; const multiplier = 1000000000; function calculateprimes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime ...
...even this very simple case produced more complex code.
... the main thread code would look something like this: const iterations = 50; const multiplier = 1000000000; var worker = new worker("js/calculate.js"); function dopointlesscomputationsinworker() { function handleworkercompletion(message) { if (message.data.command == "done") { pointlesscomputationsbutton.disabled = false; console.log(message.data.primes); worker.removeeventlistener("message...
...And 2 more matches
Waterfall - Firefox Developer Tools
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.
... for example, suppose we have code like this: var iterations = 70; var multiplier = 1000000000; function calculateprimes() { console.time("calculating..."); var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = fal...
...And 2 more matches
The JavaScript input interpreter - Firefox Developer Tools
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.
...And 2 more matches
BasicCardResponse - Web APIs
basiccardresponse.cardsecuritycode read only secure context optional contains the security code of the card used to make the payment.
...dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc.
... 56notes disabled full support 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true) and the dom.payments.request.supportedregions preference (needs to be set to a comma-delineated list of one or more 2-character iso country codes indicating the countries in which to support payments (for example, us,ca.).
...And 2 more matches
Drawing shapes with canvas - Web APIs
drawing a triangle for example, the code for drawing a triangle would look something like this: <html> <body onload="draw();"> <canvas id="canvas" width="100" height="100"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(75, 50); ctx.lineto(100, 75); ctx.lineto(100, 25); ...
... to try this for yourself, you can use the code snippet below.
...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.
...And 2 more matches
Using images - Web APIs
data urls allow you to completely define an image as a base64 encoded string of characters directly in your code.
... some disadvantages of this method are that your image is not cached, and for larger images the encoded url can become quite long.
...using backdrops can make your script considerably smaller because we can avoid the need for code to generate the background.
...And 2 more matches
Document.cookie - Web APIs
WebAPIDocumentcookie
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.
... write a new cookie document.cookie = newcookie; in the code above, newcookie is a string of form key=value.
... 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).
...And 2 more matches
Using the Gamepad API - Web APIs
technologies like <canvas>, webgl, <audio>, and <video>, along with javascript implementations, have matured to the point where they can now support many tasks previously requiring native code.
...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.
...you can view the demo live, and find the source code on github.
...And 2 more matches
Ajax navigation example - Web APIs
"</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>this is the content of <strong>first_page.php</strong>.</p> <?php if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); } else { ?> </div> <p>this paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</body>\n</html>"; } ?> second_page.php: <?php $page_title = "second page"; $as_json = false; if (isset($_get["view_as"]) && $...
..."</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>this is the content of <strong>second_page.php</strong>.</p> <?php if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); } else { ?> </div> <p>this paragraph is shown only when the navigation starts from <strong>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...
...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>" .
...And 2 more matches
Timing element visibility with the Intersection Observer API - Web APIs
tying it together with javascript that brings us to the javascript code which makes everything work.
...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.
... 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.
...And 2 more matches
KeyboardEvent.initKeyEvent() - Web APIs
syntax event.initkeyevent (type, bubbles, cancelable, viewarg, ctrlkeyarg, altkeyarg, shiftkeyarg, metakeyarg, keycodearg, charcodearg) parameters type is a domstring representing the type of event.
... 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.
...And 2 more matches
Recording a media element - Web APIs
; padding-bottom: 4px; color: white; background-color: darkgreen; text-decoration: none; } h2 { margin-bottom: 4px; } .left { margin-right: 10px; float: left; width: 160px; padding: 0px; } .right { margin-left: 10px; float: left; width: 160px; padding: 0px; } .bottom { clear: both; padding-top: 10px; } javascript content now let's have a look at the javascript code; this is where the majority of the action happens, after all!
... getting an input stream and setting up the recorder now let's look at the most intricate piece of code in this example: our event handler for clicks on the start button: startbutton.addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: true, audio: true }).then(stream => { preview.srcobject = stream; downloadbutton.href = stream; preview.capturestream = preview.capturestream || preview.mozcapturestream; return new promise(resolve => previe...
...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.
...And 2 more matches
Using the MediaStream Recording API - Web APIs
you can see this demo running live, or grab the source code on github.
... 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.
...And 2 more matches
PaymentAddress - Web APIs
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.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.
... paymentaddress.sortingcode read only a domstring providing a postal sorting code such as is used in france.
...And 2 more matches
Using the Permissions API - Web APIs
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.
... "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).
...And 2 more matches
RTCInboundRtpStreamStats - Web APIs
framesdecoded a long integer value indicating the total number of frames of video which have been correctly decoded so far for this media source.
... 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.
...And 2 more matches
RTCPeerConnection.setLocalDescription() - Web APIs
deprecated parameters in older code and documentation, you may see a callback-based version of this function used.
...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.
...And 2 more matches
RTCPeerConnection.setRemoteDescription() - Web APIs
this lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmys...
... deprecated syntax in older code and documentation, you may see a callback-based version of this function used.
...you should update any existing code to use the promise-based version of setremotedescription() instead.
...And 2 more matches
RTCRtpSender.replaceTrack() - Web APIs
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).
... 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.
...And 2 more matches
Screen Wake Lock API - Web APIs
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).
... examples feature detection this code checks for wake lock support and updates the ui accordingly.
... 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.
...And 2 more matches
ServiceWorkerGlobalScope.onfetch - Web APIs
}; 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.
...And 2 more matches
ServiceWorkerGlobalScope - Web APIs
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.
...And 2 more matches
Boilerplate 1 - Web APIs
« previousnext » this example describes repeated pieces of code that will be hidden from now on, as well as defining a javascript utility function to make webgl initialization easier.
... boilerplate code for setting up webgl rendering context by now you are quite used to seeing the same pieces of html, css, and javascript repeated again and again.
...this would allow us to focus on the interesting pieces of code that are most relevant for learning webgl.
...And 2 more matches
Creating 3D objects using WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
... 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 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.
...And 2 more matches
Getting started with WebGL - Web APIs
webgl programs consist of control code written in javascript and shader code (glsl) that is executed on a computer's graphics processing unit (gpu).
... the code examples in this tutorial can also be found in the webgl-examples github repository.
... <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.
...And 2 more matches
Using shaders to apply color in WebGL - Web APIs
you'll need to include it if you create your own project based on this code.
...we'll do that by adding the following code to our initbuffers() function: function initbuffers(){ ...
... 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_draw); return { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color.
...And 2 more matches
Lifetime of a WebRTC session - Web APIs
see signaling and video calling for an actual example with a step-by-step explanation of what the code does.
... 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.
... media capability negotiation: what codecs and media data formats can the peers understand?
...And 2 more matches
Improving compatibility using WebRTC adapter.js - Web APIs
while you can manually code around these issues, there is an easier way.
...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.
... 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.
...And 2 more matches
WebRTC API - Web APIs
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.
... 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.
...And 2 more matches
Keyboard-navigable JavaScript widgets - Accessibility
see the source code of this aria radiogroup example for a direct illustration of how this works.
... 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.
...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
text-justify - CSS: Cascading Style Sheets
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.
...cras eu elementum dui.</p> <p class="auto"><code>text-justify: auto</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit.
...cras eu elementum dui.</p> <p class="dist"><code>text-justify: distribute</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit.
...And 2 more matches
DOM onevent handlers - Developer guides
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.
... 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>.
... let logelement = document.queryselector('div'); let el = document.queryselector("a"); function log(msg) { logelement.innerhtml += `${msg}<br>` }; function anchoronclick(event) { log("changed onclick handler") }; // original handler log(`element's onclick as a javascript property: <code> ${el.onclick.tostring()} </code>`); //changing handler using .onclick log('<br>changing onclick handler using <strong> onclick property </strong> '); el.onclick = anchoronclick; log(`changed the property to: <code> ${el.onclick.tostring()} </code>`); log(`but the html attribute is unchanged: <code> ${el.getattribute("onclick")} </code><br>`); //changing handler using .setattribute log('<hr/>...
...And 2 more matches
Localizations and character encodings - Developer guides
browsers process text as unicode internally.
...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.
...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.
...And 2 more matches
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
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).
... <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...
...er part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="date">.
...And 2 more matches
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
once chosen, the files can be uploaded to a server using form submission, or manipulated using javascript code and the file api.
...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.
...> using file inputs a basic example <form method="post" enctype="multipart/form-data"> <div> <label for="file">choose file to upload</label> <input type="file" id="file" name="file" multiple> </div> <div> <button>submit</button> </div> </form> div { margin-bottom: 10px; } this produces the following output: note: you can find this example on github too — see the source code, and also see it running live.
...And 2 more matches
<input type="image"> - HTML: Hypertext Markup Language
WebHTMLElementinputimage
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().
...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.
...possible values are: application/x-www-form-urlencoded: the default value if the attribute is not specified.
...And 2 more matches
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...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).
...</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.
...And 2 more matches
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
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>.
... 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>.
... 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.
...And 2 more matches
CSP: script-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
...And 2 more matches
HTTP Public Key Pinning (HPKP) - HTTP
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.
... 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.
...And 2 more matches
Redirections in HTTP - HTTP
redirect responses have status codes that start with 3, and a location header holding the url to redirect to.
... code text method handling typical use case 301 moved permanently get methods unchanged.
... code text method handling typical use case 302 found get methods unchanged.
...And 2 more matches
Details of the object model - JavaScript
creating objects with simple definitions object hierarchy the following hierarchy is created using the code on the right side.
...therefore, this line of code tests to see if name has a useful value for the name property.
...if you want to specify an initial value for inherited properties in javascript, you need to add more code to the constructor function.
...And 2 more matches
Introduction - JavaScript
and, likewise, node.js javascript on the server can respond to custom requests from code written in the browser.
...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.
... hello world to get started with writing javascript, open the web console in multi-line mode, and write your first "hello world" javascript code: (function(){ "use strict"; /* start of your code */ function greetme(yourname) { alert('hello ' + yourname); } greetme('world'); /* end of your code */ })(); press cmd+enter or ctrl+enter (or click the run button) to watch it unfold in your browser!
...And 2 more matches
JavaScript modules - JavaScript
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.
...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.
...re.js'; import * as circle from './modules/circle.js'; import * as triangle from './modules/triangle.js'; in each case, you can now access the module's imports underneath the specified object name, for example: let square1 = square.draw(mycanvas.ctx, 50, 50, 100, 'blue'); square.reportarea(square1.length, reportlist); square.reportperimeter(square1.length, reportlist); so you can now write the code just the same as before (as long as you include the object names where needed), and the imports are much neater.
...And 2 more matches
Deprecated and obsolete features - JavaScript
you should work to remove their use from your code.
... you should use toisostring instead of the deprecated togmtstring method in new code.
...use encodeuri, encodeuricomponent, decodeuri or decodeuricomponent to encode and decode escape sequences for special characters.
...And 2 more matches
URIError: malformed URI sequence - JavaScript
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?
...an argument given to either the decodeuri, encodeuri, encodeuricomponent, or decodeuricomponent function was not valid, so that the function was unable encode or decode properly.
...an urierror will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example: encodeuri('\ud800'); // "urierror: malformed uri sequence" encodeuri('\udfff'); // "urierror: malformed uri sequence" a high-low pair is ok.
...And 2 more matches
Array.prototype.map() - JavaScript
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.
...return a return a; }; } examples mapping 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.
...And 2 more matches
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.
...And 2 more matches
Function.prototype.bind() - JavaScript
[[call]] executes code associated with this object.
... 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.
...g possible to the ecmascript 5 // internal iscallable function throw new typeerror('function.prototype.bind - ' + 'what is trying to be bound is not callable'); } return function(){ var funcargs = args.concat(slice.call(arguments)) return thatfunc.apply(thatarg, funcargs); }; }; })(); 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 bind() in implementations that do not natively support it.
...And 2 more matches
Function.prototype.toString() - JavaScript
the tostring() method returns a string representing the source code of the function.
... syntax function.tostring() return value a string representing the source code of the function.
... function.prototype.tostring.call('foo'); // typeerror if the tostring() method is called on built-in function objects or a function created by function.prototype.bind, tostring() returns a native function string which looks like "function () {\n [native code]\n}" if the tostring() method is called on a function created by the function constructor, tostring() returns the source code of a synthesized function declaration named "anonymous" using the provided parameters and function body.
...And 2 more matches
Intl.DisplayNames - JavaScript
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.
... examples region code display names to create an intl.displaynames for a locale and get the display name for a region code.
...nguagenames.of('zh-hant'); // "traditional chinese" languagenames.of('en-us'); // "american english" languagenames.of('zh-tw'); // "chinese (taiwan)"] // get display names of language in traditional chinese languagenames = new intl.displaynames(['zh-hant'], {type: 'language'}); languagenames.of('fr'); // "法文" languagenames.of('zh'); // "中文" languagenames.of('de'); // "德文" script code display names to create an intl.displaynames for a locale and get the display name for a script code.
...And 2 more matches
Intl.NumberFormat() constructor - JavaScript
the following unicode extension key is allowed: nu the numbering system to be used.
...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.
...possible values are: "symbol" to use a localized currency symbol such as €, this is the default value, "narrowsymbol" to use a narrow format symbol ("$100" rather than "us$100"), "code" to use the iso currency code, "name" to use a localized currency name such as "dollar", currencysign in many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign.
...And 2 more matches
Object.create() - JavaScript
rt object to primitive value > oco.tostring() // shows [object object] > ocn.tostring() // throws error: ocn.tostring is not a function > oco.valueof() // shows {} > ocn.valueof() // throws error: ocn.valueof is not a function > oco.hasownproperty("p") // shows "true" > ocn.hasownproperty("p") // throws error: ocn.hasownproperty is not a function > oco.constructor // shows "object() { [native code] }" > ocn.constructor // shows "undefined" as said, these differences can make debugging even simple-seeming problems quickly go astray.
... 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.
... adding the missing object-method directly from the standard-object does not work: ocn = object.create( null ); // create "null" object (same as before) ocn.tostring = object.tostring; // since new object lacks method then try assigning it directly from standard-object > ocn.tostring // shows "tostring() { [native code] }" -- missing method seems to be there now > ocn.tostring == object.tostring // shows "true" -- method seems to be same as the standard object-method > ocn.tostring() // error: function.prototype.tostring requires that 'this' be a function adding the missing object-method directly to new object's "prototype" does not work either, since the new object does not have a real prototype (which is...
...And 2 more matches
RegExp - JavaScript
regexp.prototype.unicode whether or not unicode features are enabled.
... 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.
...And 2 more matches
String length - JavaScript
the length property of a string object contains the length of the string, in utf-16 code units.
... description this property returns the number of code units in the string.
... utf-16, the string format used by javascript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.
...And 2 more matches
WebAssembly - JavaScript
description the primary uses for the webassembly object are: loading webassembly code, using the webassembly.instantiate() function.
... 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.
... static methods webassembly.instantiate() the primary api for compiling and instantiating webassembly code, returning both a module and its first instance.
...And 2 more matches
escape() - JavaScript
… … programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code.
...(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.
...And 2 more matches
JavaScript
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.
... tools & resources helpful tools for writing and debugging your javascript code.
...And 2 more matches
Digital video concepts - Web media technologies
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.
... 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.
... the first number specifies the number of luminance samples per row encoded from the 4x2 pixel block.
...And 2 more matches
Progressive loading - Progressive web apps (PWAs)
here's what the relevant code looks like: if('intersectionobserver' in window) { const observer = new intersectionobserver((items, observer) => { items.foreach((item) => { if(item.isintersecting) { loadimages(item.target); observer.unobserve(item.target); } }); }); imagestoload.foreach((img) => { observer.observe(img); }); } else { imagestoload.foreach((img) => { loadimag...
... 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.
... 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.
...And 2 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
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.
...you don't get caught in the situation of having to bring out more new site versions as more new browsers and platforms come out, and adjust code as feature support in existing browsers changes.
...And 2 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
you can <a href="https://github.com/mdn/pwa-examples/blob/master/js13kpwa"> fork js13kpwa on github</a> to check its source code.</p> <button id="notifications">request dummy notifications</button> <section id="content"> // content inserted in here </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com"> andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a>.</p> </footer> </body> </html> the <head> section contains basic information ab...
...out the app, including its title, description, and the needed references to its css file, web manifest, the main application javascript file (app.js, in which the app is initialized) as well as an additional javascript code file.
... var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if (result === 'granted') { randomnotification(); } }); }); the randomnotification() function follows, rounding out the last of the code in the file: function randomnotification() { var randomitem = math.floor(math.random()*games.length); var notiftitle = games[randomitem].name; var notifbody = 'created by '+games[randomitem].author+'.'; var notifimg = 'data/img/'+games[randomitem].slug+'.jpg'; var options = { body: notifbody, icon: notifimg } var notif = new notification(notiftitle, options); settimeout...
...And 2 more matches
Index - WebAssembly
found 12 pages: # page tags and summary 1 webassembly landing, webassembly, wasm webassembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as c/c++ with a compilation target so that they can run on the web.
... 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.
... 5 compiling from rust to webassembly compiling, webassembly, rust, wasm if you've written some rust code, you can compile it into webassembly!
...And 2 more matches
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.
... 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.
... 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.
Private Properties - Archive of obsolete content
to make the above code work, a unique identifier must be associated with each image and override its tostring method.
...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.
... namespaces in the add-on sdk the add-on sdk is built on top of xpcom, the interface between javascript and c++ code.
...as always with code that is heavily reused, the sdk defines a helper function to create namespaces.
Guides - Archive of obsolete content
contributor's guide getting started learn how to contribute to the sdk: getting the code, opening/taking a bug, filing a patch, getting reviews, and getting help.
... 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.
... sdk idioms working with events write event-driven code using the the sdk's event emitting framework.
... 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.
l10n - Archive of obsolete content
localize strings appearing in the add-on's javascript code.
... usage to learn how to use this module to write localizable code, read the localization tutorial.
... and the following code: var _ = require("sdk/l10n").get; console.log(_("hello_string")); the following output will be logged: info: hello!
...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.
Implementing the widget - Archive of obsolete content
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.
... main.js now in the lib directory open main.js and add the following code: var widgets = require('sdk/widget'); var data = require('sdk/self').data; var annotatorison = false; function toggleactivation() { annotatorison = !annotatorison; return annotatorison; } exports.main = function() { var widget = widgets.widget({ id: 'toggle-switch', label: 'annotator', contenturl: data.url('widget/pencil-off.png'), contentscriptwhen: 'ready', contentscriptfile: data.url('widget/widget.js') }); widget.port.on('left-click', function() { console.log('activate/deactivate'); widget.con...
...since we don't have any code to display annotations yet, we just log the right-click events to the console.
... next we'll add the code to create annotations.
Getting started (cfx) - Archive of obsolete content
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.
...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.
... the add-on code itself uses two sdk modules, action button and tabs.
...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.
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).
... 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...
... // 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]);} })(); // can put an object argument here ...
Extension Etiquette - Archive of obsolete content
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.
...in general, care must be taken whenever defining a name anywhere that other code might do likewise.
...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.
... when available, these methods should always be used to prevent conflicts with third-party code.
Installing Extensions and Themes From Web Pages - Archive of obsolete content
aevent.target.getattribute("hash"), tostring: function () { return this.url; } }; this specifies the display name (foo) for use in the confirmation dialog, the url to the extension (which is the link href, recall), the icon url to display in the confirmation dialog, a hash of the xpi file contents (to protect against corrupted downloads), and a tostring function which will allow this code to work with versions of firefox 0.8 and earlier.
...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 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.
Adding menus and submenus - Archive of obsolete content
the toolbox should be positioned near the top of the xul document, and the code should be similar to this: <toolbox> <menubar id="xulschoolhello-menubar"> <menu id="xulschoolhello-greeting-menu" label="&xulschoolhello.greeting.label;"> <menupopup> <menuitem label="&xulschoolhello.greet.short.label;" oncommand="xulschoolchrome.greetingdialog.greetingshort(event);" /> <menuitem label="&xulschoolhello.greet.medium.label;" oncomma...
...dialog.greetingmedium(event);" /> <menuitem label="&xulschoolhello.greet.long.label;" oncommand="xulschoolchrome.greetingdialog.greetinglong(event);" /> <menuseparator /> <menuitem label="&xulschoolhello.greet.custom.label;" oncommand="xulschoolchrome.greetingdialog.greetingcustom(event);" /> </menupopup> </menu> </menubar> </toolbox> this code displays a simple menu with options for 3 different types of greetings, a menuseparator, and finally an option to show a custom greeting.
...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.
...the oncommand attribute is set on the menupopup to avoid code duplication, since now the 3 items call the same function.
Security best practices in extensions - Archive of obsolete content
in certain circumstances you may want to run code in your extension, but you would like to give it restricted privileges.
...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.
...give the element a type="content" attribute, which essentially sandboxes the code there and blocks callback rights into chrome.
...it is not unheard of in add-ons as well, and can provide a useful way to avoid code duplication and accelerate development.
Session store API - Archive of obsolete content
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 code sets the value of the key "key-name-here" to datatoattach.
... 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".
... 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.
Setting up an extension development environment - Archive of obsolete content
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.
...this enables to run javascript code snippets in the chrome context of the scratchpad from the tools menu.
... the browser debugger can be used to debug the javascript code of extensions.
...detect deprecated code use.
Promises - Archive of obsolete content
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.
... 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.
... 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.
Creating reusable content with CSS and XBL - Archive of obsolete content
this page illustrates how you can use css in mozilla to improve the structure of complex applications, making code and resources more easily reusable.
... note: xbl cannot be loaded over http, so this technique is only useful for local content accessed using the file:/// scheme, or from add-on code.
...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 binding links its own stylesheet, and it supplies its own content and javascript code.
Creating a dynamic status bar extension - Archive of obsolete content
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.
...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.
...write the xul file we need a slightly more complicated xul file this time, in order to add a reference to the javascript code that will do the real work: <?xml version="1.0" encoding="utf-8"?> <!doctype overlay> <overlay id="stockwatcher-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://stockwatcher/content/stockwatcher.js"/> <!-- firefox --> <statusbar id="status-bar"> <statusbarpanel id="stockwatcher" label="loading..." ...
...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.
Install.js - Archive of obsolete content
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 ).
... 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.
...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
code with universalxpconnect privileges can monitor the list of available wifi access points to obtain information about them including their ssid, mac address, and signal strength.
...security.privilegemanager.enableprivilege('universalxpconnect'); var listener = new test(); var wifi_service = components.classes["@mozilla.org/wifi/monitor;1"].getservice(components.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 onerror() method simply opens an alert that displays the error code received.
Source Navigator - Archive of obsolete content
(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.
...now you can enjoy searching the mozilla code in a faster speed.
...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 ...
Locked config settings - Archive of obsolete content
the mozilla.cfg file is an encoded file of javascript commands.
...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.
...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 { ...
Creating a Microsummary - Archive of obsolete content
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.
... 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.
... for example, if we put the generator file on the web at http://people.mozilla.com/~myk/micro...-generator.xml, and we wanted users to be able to install it from http://people.mozilla.com/~myk/micro...ial/index.html, we might add the following code to the index.html page: <button onclick="window.sidebar.addmicrosummarygenerator('http://people.mozilla.com/~myk/microsummaries/tutorial/sfx-generator.xml')">install the spread firefox home page microsummary!</button> clicking that button will generate a javascript error on browsers that don't support microsummaries, however, so to improve the experience for those users, we should check to see...
...we might do so via the following code: <script> const warning = "sorry, you need a microsummary-enabled browser like firefox 2.0 to install and use microsummary generators."; function addgenerator(url) { if (typeof window.sidebar == "object" && typeof window.sidebar.addmicrosummarygenerator == "function") window.sidebar.addmicrosummarygenerator(url); else alert(warning); } </script> <button onclick="addgenerator('http://people.mozilla.com/~myk/microsummaries/tutorial/sfx-generator.xml')">install the spread firefox home page microsummary!</button> note that due to bug 341283, addmicrosummarygenerator() will not accept a relative url.
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.
...example: printing the location of type declarations save the following c++ code dumptypes.cc: typedef int myint; struct foo { int i; char *c; }; save the following analysis script dumptypes.js: function process_type(t) { print("type found: " + t.name + " location: " + t.loc); } function input_end() { print("hello, world!"); } compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/dumptypes.js -o/dev/null -c dumptypes.cc note:for g++4.5 and up use -fplugin-arg-gcc_dehydra-script= rather than -fplugin-arg it should print the following results: type found: foo location: test.cc:2:12 type found: myint location: test.cc:1:13 hello, world!
... see documentation for: process_type, input_end, print, .loc property example: using attributes to mark a class as "final" save the following code as final.cc: // this class should not be subclassed!
... 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
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.
... here is the code : import org.eclipse.swt.swt; import org.eclipse.swt.browser.mozillabrowser; import org.eclipse.swt.browser.progressevent; import org.eclipse.swt.browser.progresslistener; import org.eclipse.swt.widgets.display; import org.eclipse.swt.widgets.shell; import org.mozilla.xpcom.nsidomdocument; public class test { public static void main(string args[]) { display display = new display(); shell shell = new shell(display); final mozillabrowser browser = new mozillabrowser(shell,wt.border); browser.seturl("http://www.google.com"); browser.addprogresslistener(new progresslistener() { public void changed(progressevent event) { } ...
...then pass the object to your xpcom coded object and call it from c++.
Layout System Overview - Archive of obsolete content
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.
...if you write your own code, document it.
... much of the existing code <b>isn’t very well documented</b>.
...the two classes should probably be folded into one, or the distinction between them formalized and utilized in the code.
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.
...someplace easy and straightforward, so you can get a feel for the lay of the code.
...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.
PyDOM - Archive of obsolete content
this allows you to use python code (almost) anywhere you can use javascript.
...for example, let's say you have xul similar to pyxultest: top-level script code says something like: button = document.getelementbyid("some-button") button.foo = 0 and the button itself might look like: <button id="some-button" label="click here" onclick="event.target.foo += 1; print 'foo is now', event.target.foo"/> note that (a) we have stuck an arbitrary attribute on a dom element and (b) in all cases (e.g., event handler and top-level script), the dom node nee...
...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.
Table Cellmap - Archive of obsolete content
introduction the table layout use the cellmap for two purposes: quick lookup of table structural data store of the border collapse data the cellmap code is contained in nscellmap.cpp and nscellmap.h this document does currently describe only the quick lookup part of the game, border collapse is still far away cellmap data - overview the entries in the cellmap contain information about the table cell frame corresponding to a given row and column number (celldata.h).
...a typical code segment to come from the table level down to the rowgroup level nscellmap* map = mfirstmap; while (map) { if (map->getrowcount() > rowindex) { // add your action here } rowindex -= map->getrowcount(); map = map->getnextsibling(); } data entry the usual way to populate the cellmap is via nstableframe::insertrows.
... enabling the debug code at the function entrance and exit gives a quite complete picture of the cellmap structure.
...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.
Mac stub installer - Archive of obsolete content
where does the mac stub installer code reside?
... the mac stub installer project resides at: <http://lxr.mozilla.org/seamonkey/sou...ll/wizard/mac/> the mac stub installer source code resides at: <http://lxr.mozilla.org/seamonkey/sou...izard/mac/src/> how do we get setup to debug the mac installer?
...now run the built installer from the "macbuild" itself or by running it from the miw.mcp codewarrior project.
...ed to do the following: create a file named xpcom.xpi with the shared libraries in the structure described under the [xpcom] section in: <http://lxr.mozilla.org/seamonkey/sou...ackages-mac#33> note that if you are using the debug target of the installer binary all shared libraries are expected to have the name format <libname>debug.shlb now set a break point at xpi_init() in the mac installer code and step into xpistub and eventually the xpinstall engine will load including symbols so you can set a break point in the xpinstall engine itself.
Install Wizards (aka: Stub Installers) - Archive of obsolete content
what do we mean by engine code?
...it then proceeds to extract the xpinstall engine and feed it the downloaded software packages to install.) the stub installer code includes: the logic to display the install wizard widgets and dialogs the code that reads in the configuration file (config.ini) and dynamically installs from the net or from local xpi modules found next to the installer binary the code that processes user selections the code that calls the xpinstall engine through xpistub the libxpnet code that is statically linked in the stub installers ...
...are written in code native to the platform using native widget toolkits including the windows api for windows, the mac toolbox for the mac, and gtk for the unix version.
...the stub installer calls some glue code: xpistub which resides at: < http://lxr.mozilla.org/seamonkey/sou...pinstall/stub/> this "glue" code initialized xpcom and registers the xpinstall engine and requisite components to prepare for use by the stub installer.
textbox.onblur - Archive of obsolete content
« xul reference home onblur type: script code this event is sent when a textbox loses keyboard focus.
...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.onfocus - Archive of obsolete content
« xul reference home onfocus type: script code this event is sent when a textbox receives keyboard focus.
...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.
Reading from Files - Archive of obsolete content
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 binary stream would be used to read bytes or numbers encoded within the file.
...in effect, the above code ends up reading the entire contents of the file into a single string.
...the difference is handled internally so you don't need to write any other part of the code differently.
International characters in XUL JavaScript - Archive of obsolete content
unicode escapes, as discussed below, have always worked.
... 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.
MenuItems - Archive of obsolete content
<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.
...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.
...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.
...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.
Menus - Archive of obsolete content
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.
...or, you could write code that handles multiple platforms in different ways.
...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.
...this allows the menu bar to be shared between each window without having to duplicate code.
Adding Buttons - Archive of obsolete content
the example code below shows how to do this.
... 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.
... the code to add is shown in red below: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <button id="find-button" label="find"/> <button id="cancel-button" label="cancel"/> </window> you'll notice that the cancel button was added also.
Adding Methods to XBL-defined Elements - Archive of obsolete content
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.
...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.
...for code inside a binding method, you can pass 'this' as the parameter to getanonymousnodes().
Cross Package Overlays - Archive of obsolete content
the id of the toolbox changed from "<code>navigator-toolbox</code>" to "<code>browser-toolbox</code>" in firefox 3 beta 3.
... you can support both firefox 2 and earlier and firefox 3 by duplicating the <code><span class="plain">' ..
...'</span></code> section with that id.
...the code below should be added into contents.rdf just before the closing rdf tag.
Localization - Archive of obsolete content
the codes &lt; and &gt; are examples of entities which can be used to place less than and greater than signs into the text.
... note: you should encode dtd files as utf-8 for non-ascii characters.
...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...
...the entity names here follow similar conventions as the rest of the mozilla code.
XUL element attributes - Archive of obsolete content
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.
...this is reverse of the order in which they appear in the xul code.
...by default, elements appear in the order they appear in the xul code.
... 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.
command - Archive of obsolete content
you attach the code to the command using the oncommand attribute.
...see also: command attribute, commandset element attributes disabled, label, oncommand,reserved examples the following code will send a paste command (cmd_paste) to the currently focused element: // first include chrome://global/content/globaloverlay.js godocommand("cmd_paste"); example with two buttons <commandset><command id="cmd_openhelp" oncommand="alert('help');"/></commandset> <button label="help" command="cmd_openhelp"/> <button label="more help" command="cmd_openhelp"/> attributes disabled type: b...
... oncommand type: script code this event handler is called when the command is activated.
... setting this attribute to "true" indicates that the command is reserved for chrome code and is not available for use in the content.
menupopup - Archive of obsolete content
onpopuphidden type: script code this event is sent to a popup after it has been hidden.
...-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.
... onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened.
panel - Archive of obsolete content
ArchiveMozillaXULpanel
onpopuphidden type: script code this event is sent to a popup after it has been hidden.
...-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.
... onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened.
tabbrowser - Archive of obsolete content
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.
... see code snippets: tabbed browser for examples.
... related code snippets: tabbed browser ...
tooltip - Archive of obsolete content
onpopuphidden type: script code this event is sent to a popup after it has been hidden.
...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.
... onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened.
window - Archive of obsolete content
to get the window state from javascript code, use window.windowstate.
... 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 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.
How to enable locale switching in a XULRunner application - Archive of obsolete content
you can hardwire the choices into the xul code using fixed list items, or could take the elegant approach and construct the list dynamically.
...here is a code snippet showing how this is done: the definition of the xul control: <listbox id="locale-listbox"> <!-- generated list items go in here --> </listbox> <button label="&switchlocale.button;" oncommand="changelocale()"/> the javascript code to populate the control: try { // query available and selected locales var chromeregservice = components.classes["@mozilla.org/chrome/chrome-registry;1"].getservice(); var xulchromereg = chromeregservice.queryinterface(components.interfaces.nsixulchromeregistry); var toolkitchromereg = chromeregservice.queryinterface(components.interfaces.nsitoolkitchromeregistry); var selectedlocale = x...
...code to update the locale user preference and restart the application mozilla xulrunner doesn't allow runtime switching of the locale, therefore the application must be restarted to activate the new choice.
...the code snippets above were taken from it.
XULRunner tips - Archive of obsolete content
contains tons of non-working code (bit rot).
...e=themes extension:manager-themes javascript console chrome://global/content/console.xul global:console about:config chrome://global/content/config.xul developer extensions venkman need a custom build or a compatible extension need to edit compatibility in needs a method to start venkman (usually by overlaying the main xul file, similar to existing code for firefox, suite, etc.) the function toopenwindowbytype() needs to be defined.
...age." create a file in the extensions directory of your application with the same name as the dom inspector id (inspector@mozilla.org) containing one line of text -- the exact path to the root directory of dom inspector (where the install.rdf is) like this one: /home/username/.mozilla/firefox/numbersandletters/extensions/inspector@mozilla.org/ now create a javascript file with the following code and include it in the main window of your application: function startdomi() { // load the window datasource so that browser windows opened subsequent to dom // inspector show up in the dom inspector's window list.
....download.manager.opendelay", 0); pref("browser.download.manager.focuswhenstarting", false); pref("browser.download.manager.flashcount", 2); // pref("alerts.slideincrement", 1); pref("alerts.slideincrementtime", 10); pref("alerts.totalopentime", 4000); pref("alerts.height", 50); if you are missing preferences that a dialog requires, you will get the following errors: component returned failure code: 0x8000ffff (ns_error_unexpected) [nsiprefbranch.getboolpref] error: dialog has no properties source file: chrome://mozapps/content/downloads/u...ontenttype.xul line: 1 enabling password manager these preferences seem to be the default in firefox, however, they are missing in xulrunner.
External resources for plugin creation - Archive of obsolete content
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.
...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.
... 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).
NPP_URLNotify - Archive of obsolete content
reason reason code for completion of request.
... 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.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
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.
... 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.
...this is an incomplete example of what a piece of code might look like that tries to check for the proper mozilla version.
...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.
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
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).
...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> ...
... <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[this is <b>bold</b>.]]></content:encoded> </item> </channel> </rss> the <content:encoded> element is the reason that the rss content module is popular.
... note: strictly speaking, the rss content module and <content:encoded> are not quite being used correctly.
Using workers in extensions - Archive of obsolete content
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.
...; } var httprequest = new xmlhttprequest(); httprequest.open("get", fullurl, true); httprequest.onload = inforeceived; httprequest.send(null); } setinterval(function() { refreshinformation(); }, 10*60*1000); onmessage = function(event) { if (event.data) { symbol = event.data.touppercase(); } refreshinformation(); } when the worker thread is started, the main body of this code (in lines 26-35) is executed.
...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.
XUL Parser in Python - Archive of obsolete content
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.
... 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.
...this is another hard-coded thing i have to open up.
Finishing up - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson10.html.
...we could also improve our code rendering.
...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.
... compare your code that's all — the final version of the game is ready and set to go !
Game over - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson5.html.
...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.
...update the last bit of code you modified again, to the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { if(x > paddlex && x < paddlex + paddlewidth) { dy = -dy; } else { alert("game over"); document.location.reload(); clearinterval(interval); } } if the ball hits the bottom edge of the canvas we need to check whether it hits t...
... 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.
Track the score and win - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson8.html.
...the first parameter is the text itself — the code above shows the current number of points — and the last two parameters are the coordinates where the text will be placed on the canvas.
...add the following highlighted line to your code: function collisiondetection() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { var b = bricks[c][r]; if(b.status == 1) { if(x > b.x && x < b.x+brickwidth && y > b.y && y < b.y+brickheight) { dy = -dy; b.status = 0; score++; } } } } } calling drawscore() from the draw() function keeps the score up to date with every new frame — add the following line inside draw(), just below the drawpaddle() c...
... 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.
Visual typescript game engine - Game development
text editor used and recommended: visual studio code.
... ├── package.json ├── package-lock.json ├── webpack.config.js ├── tsconfig.json ├── tslint.json ├── launch.json ├── workplace.code-workspace logo.png license ├── build/ (this is auto generated) | ├── externals/ | ├── templates/ | ├── imgs/ | ├── styles/ | | └── favicon.ico | ├── visualjs2.js | ├── app.html ├── src/ | ├── style/ | | ├── styles.css | ├── libs/ | | ├── class/ | | | ├── networking/ | | | |...
... -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".
... code format : npm run fix npm run tslint or use : tslint -c tslint.json 'src/**/*.ts' --fix tslint -c tslint.json 'src/**/*.ts' the external licence in this project : - networking based on : muaz khan mit license www.webrtc-experiment.com/licence - base physics based on : original source: matter.js https://github.com/liabru/matter-js matter.ts used because typescript orien...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
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.
...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.
...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.
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')?
... html should be coded to represent the data that will be populated and not based on its default presentation styling.
... 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 visually impaired users navigate a page finding blocks of meaningful code is significantly easier than searching though endless divs with or without semantic or namespaced classes suggests to the developer the type of data that will be populated semantic naming mirrors proper custom element/component naming when approaching which markup to use, ask yourself, "what element(s) best describe/represent the data that i'm going to populate?" for example, is it a list of data?; ordered, unordered?
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
syntax specifies the required combination and sequence of characters making up correctly structured code.
... 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.
...if a codebase uses "a lot of syntax", it requires more characters to achieve the same functionality.
Test your skills: The Cascade - Learn web development
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 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.
...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.
Test your skills: tables - Learn web development
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 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.
...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.
Introduction to CSS layout - Learn web development
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.
... adding this code will give the following result: relative positioning example <h1>relative positioning</h1> <p>i am a basic block level element.</p> <p class="positioned">this is my relatively positioned element.</p> <p>i am a basic block level element.</p> body { width: 500px; margin: 0 auto; } p { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); padding: 10px; ma...
...adding this code, however, will give the following result: absolute positioning example <h1>absolute positioning</h1> <p>i am a basic block level element.</p> <p class="positioned">this is my absolutely positioned element.</p> <p>i am a basic block level element.</p> body { width: 500px; margin: 0 auto; } p { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); padding: 10...
...form input { display: table-cell; margin-bottom: 10px; } form label { width: 200px; padding-right: 5%; text-align: right; } form input { width: 300px; } form p { display: table-caption; caption-side: bottom; width: 300px; color: #999; font-style: italic; } this gives us the following result: you can also see this example live at css-tables-example.html (see the source code too.) multi-column layout the multi-column layout module gives us a way to lay out content in columns, similar to how text flows in a newspaper.
Test your skills: Media Queries and Responsive Design - Learn web development
download the code and work locally, or use an online tool such as codepen, jsfiddle, or glitch to work on the tasks.
... 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.
...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.
Advanced form styling - Learn web development
the above code is good for future-proofing against such an eventuality.
...%; padding: 5px; height: 30px; } input[type="text"], input[type="datetime-local"], input[type="color"], select { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } label { margin-bottom: 5px; } button { width: 60%; margin: 0 auto; } note: if you want to test these examples across a number of browsers simultaneously, you can find it live here (also see here for the source code).
...replace it with a custom style (a thin red track, in this case): input[type="range"] { appearance: none; -webkit-appearance: none; background: red; height: 2px; padding: 0; outline: 1px solid transparent; } however, it is very difficult to customize the style of the range control's drag handle — to get full control over range styling you'll need to use a whole bunch of complex css code, including multiple non-standard, browser-specific pseudo-elements.
...#eee, #ccc); border: 1px solid rgb(169, 169, 169); border-radius: 5px; text-align: center; line-height: 1.5; } label[for="file"]:hover { background: linear-gradient(to bottom, #fff, #ddd); } label[for="file"]:active { box-shadow: inset 1px 1px 3px #ccc; } you can see the result of the above css styling in the below live example (see also styled-file-picker.html live, and the source code).
Test your skills: Form structure - Learn web development
note: you can try out the solution in the interactive editor 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 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.
...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.
Test your skills: Form validation - Learn web development
note: you can try out solutions locally, however it may be helpful to put your code in an online tool such as codepen, jsfiddle, or glitch to work on the tasks.
... 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.
...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.
Test your skills: Styling basics - Learn web development
note: you can try out solutions by editing the starting point file locally, however it may be helpful to put your code in an online tool such as codepen, jsfiddle, or glitch to work on the tasks.
... 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.
...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.
HTML basics - Learn web development
previous overview: getting started with the web next html (hypertext markup language) is the code that is used to structure a web page and its content.
... 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.
...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.
... 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.
React interactivity: Events and state - Learn web development
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.
... write the following above your handlesubmit() function, inside form(): const [name, setname] = usestate('use hooks!'); what's going on in this line of code?
...update the code you just added as follows: const tasksnoun = tasklist.length !== 1 ?
...we have to write our own code to put the browser back in sync with our app.
Beginning our React todo list - Learn web development
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.
... 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 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.
... implementing our styles paste the following css code into src/index.css so that it replaces what's currently there: /* resets */ *, *::before, *::after { box-sizing: border-box; } *:focus { outline: 3px dashed #228bec; outline-offset: 0; } 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; width: auto; overflow: visible; background: transparent; color: inherit; font: inherit; line-height: normal; -webkit-font-smoothing: inherit; -moz-osx-font-smoothing: inherit; -webkit-appearance: none; } button::-moz-focus-inner { border: 0; } button, input, optgroup, select, textarea { font-family: inherit; font-size: 100%; line-height: 1.15; margin: 0; } ...
Vue conditional rendering: editing existing todos - Learn web development
copy the following code into that file: <template> <form class="stack-small" @submit.prevent="onsubmit"> <div> <label class="edit-label">edit name for &quot;{{label}}&quot;</label> <input :id="id" type="text" autocomplete="off" v-model.lazy.trim="newlabel" /> </div> <div class="btn-group"> <button type="button" class="btn" @click="oncancel"> cancel <span class="visually-h...
... antialiased; -moz-osx-font-smoothing: grayscale; color: #0b0c0c; display: block; margin-bottom: 5px; } input { display: inline-block; margin-top: 0.4rem; width: 100%; min-height: 4.4rem; padding: 0.4rem 0.8rem; border: 2px solid #565656; } form { display: flex; flex-direction: row; flex-wrap: wrap; } form > * { flex: 0 0 100%; } </style> note: walk through the above code then read the below description to make sure you understand everything the component is doing before moving on.
... this code sets up the core of the edit functionality.
...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.
Cross browser testing - Learn web development
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.
... 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.
... 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.
Tools and testing - Learn web development
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.
...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.
... 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.
...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.
Learn web development
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.
... 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.
... getting our code examples the code examples you'll encounter in the learning area are all available on github.
... if you want to copy them all to your computer, the easiest way is to download a zip of the latest master code branch.
Accessibility Features in Firefox
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.
...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".
... sun contributes code to improve accessibility on unix a similar story occurred at sun microsystems.
... that's the great thing about the open firefox community model and source code license -- anyone can contribute, and everyone benefits.
CSUN Firefox Materials
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.
...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".
...sun contributes code to improve accessibility on unix a similar story occurred at sun microsystems.
...that's the great thing about the open firefox community model and source code license -- anyone can contribute, and everyone benefits.
Benchmarking
this setting reduces build times significantly but comes with a serious hit to runtime performance for any rust code (for example stylo and webrender).
... 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.
... 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.
... some example tools include instruments on osx (part of xcode), rotateright zoom on linux (uses perf underneath), and intel vtune on windows or linux.
Choosing the right memory allocator
allocating memory in xpcom these are general purpose memory-management routines that you should use unless your code falls into one of the other categories below.
... 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.
... nspr memory allocators you should only use the nspr allocators within nspr or the security code located in the /security/ subtree of the source code.
...this is the /js/ subtree of the source code.
Creating JavaScript callbacks in components
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 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.
Gecko Logging
a minimal c++ logging framework is provided for use in core gecko code.
...this should not be used directly in code.
... example usage code sample #include "mozilla/logging.h" using mozilla::loglevel; static mozilla::lazylogmodule slogger("example_logger"); static void dostuff() { moz_log(slogger, loglevel::info, ("doing stuff.")); int i = 0; int start = time::nowms(); moz_log(slogger, loglevel::debug, ("starting loop.")); while (i++ < 10) { moz_log(slogger, loglevel::verbose, ("i = %d", i)); } // only calcula...
... rust we're gradually adding more rust code to gecko, and rust crates typically use a different approach to logging.
Listening to events on all tabs
astatus error status code associated with the state change; this indicates whether or not the request was successful.
... note: astatus may be a success code even for server generated errors, such as the http 404 file not found error.
... astatus this value is not an error code.
...this interface does not define the set of possible status codes.
Index
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.
... 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.
... 172 security best practices for firefox front-end engineers best practices, developing firefox, developing mozilla, firefox, front-end, mozilla, performance this article will help firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for firefox.
HTML parser threading
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.
...initialization an nshtml5parser is constructed without an nshtml5streamparser due to legacy code structure around parser creation.
...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.
How Mozilla determines MIME Types
if the server did not send a content-type header, mozilla uses the unknown decoder to find 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.
... 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.
Implementing QueryInterface
it generates less code than the typical implementation of queryinterface.
...this saves code-space and reduces complexity.
... the differences are highlighted in the following code.
...this is reflected in the code above.
Infallible memory allocation
currently, while code is transitioned to be compatible with infallible memory allocators, you have to explicitly decide whether to use infallible allocation or not.
... 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.
...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.
... 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.
JNI.jsm
the jni.jsm javascript code module abstracts all of the js-ctypes required for writing jni code.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/jni.jsm"); this module was available in firefox since version 17.
... if you would like to support versions before that, you can copy and paste the contents of the jsm file int jni stands for java native interface; this library allows calling java code running in java virtual machines (jvms), etc.
...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 ...
Localizing without a specialized tool
from the create a new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code.
...to do this, enter the following commands, keeping sure to change "x-testing" to the actual locale code of your locale.
... 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).
... 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).
gettext
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.
...for english, the above code will produce the following output: 1 user likes this.
...gettext will return one of the msgstrs, depending on the number passed to the gettext function in the code ($num in the above example).
...$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.
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".
... mfbt code goes to some length to document all its interfaces in comments, including examples when possible.
...most new code should use this rather than prclist.
Mozilla Development Tools
naturally, source code for all of these tools is also available.
... 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.
...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.
... mxr you can browse the up-to-the-minute latest version of the source code online through a massively-hyperlinked source code browser (based on lxr) that lets you cross-reference function and variable names.
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.
...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.
...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(); ...
Mozilla Style System Documentation
(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.
...the code that does this sharing work is mostly in nsstylecontext::getstyledata, nsrulenode::getstyledata, and nsrulenode::walkruletree.
...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.
...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.
Memory reporting
mozilla code has infrastructure that lets different parts of the code report on their memory usage.
... sometimes counter-based reporters are unavoidable, particularly when writing memory reporters for third-party code that cannot be modified.
...there are many such examples in the code, such as nscategorymanager.
... it identifies places in the code that allocate memory but do not have memory reporters for that memory.
TimerFirings logging
there are also timers for settimer or setinterval calls in javascript code, as the following sample shows.
...they can come from chrome code within firefox, or from web content.
... 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] gfxfontinfoloader::delayedstartcallback(nsitimer*, void*) second, on linux the code uses dladdr to get the symbol library and address, which can be post-processed by tools/rb/fix_stacks.py.
L20n Javascript API
locales are referenced by their bcp 47 language codes.
... 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.
...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.
... 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.
L20n
a javascript localization framework to unleash your natural language's power with simple code.
... l20n's html bindings tutorial on implementing l20n in your html code.
... l20n tinker test out your own l20n code in l20n tinker.
... github where the main code for the l20n infrastructure and design spec lives.
NSPR Contributor Guide
look at the extant code.
...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.
...these libraries exist, for the most part, as "legacy" code from nspr 1.0.
... 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].
PR_GetOSError
returns the current thread's last set os-specific error code.
... 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.
Function_Name
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.
...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.
... see also copy of the mxr link, with the following text occurrences of function_name in the current nss source code (generated by mxr).
Cryptography functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions pk11_algtagtomechanism mxr 3.2 and later pk11_authenticate mxr 3.2 and later pk11_blockdata mxr 3.2 and later pk11_changepw mxr 3.2 and later pk11_checkuserpassword mxr 3.2 and later pk11_cipherop mxr 3.2 and later pk11_clonecontext mxr 3.2 and later pk11_configurepkcs11 mxr 3.2 and later pk11_convertsessionprivkeytotokenprivkey mxr 3.6 and later pk11_convertsessionsymkeytoto...
... 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 ...
... 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_destroysubjectpublickeyinfo mxr 3.2 and later seckey_getpublickeytype mxr 3.3 and later seckey_publickeystrengthinbits mxr...
Encrypt Decrypt MAC Keys As Session Objects
nss sample code 4: encryption/decryption and mac keys using session.
... /* this source code form is subject to the terms of the mozilla public * license, v.
... 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_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; } ...
Encrypt and decrypt MAC using token
nss sample code 3: encryption/decryption and mac using token object.
... /* this source code form is subject to the terms of the mozilla public * license, v.
... 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_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; } ...
NSS FAQ
MozillaProjectsNSSFAQ
for instructions on how to check out and build the nss source code, see build instructions for nss.
... nss source code and binaries (when they become available) are completely free.
...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, nss source code is subject to the u.s.
NSS 3.14 release notes
for an additional explantation on gpl/lgpl compatibility, see security/nss/copying in the source code.
...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 types have been added in nss 3.14 certchainverifycallback (in certt.h) certchainverifycallbackfunc (in certt.h) cert_pi_chainverifycallback, a new option for certvalparamintype (in certt.h) a new error code: sec_error_application_callback_error (in secerr.h) new for pkcs #11 pkcs #11 mechanisms: ckm_aes_cts ckm_aes_ctr ckm_aes_gcm (see warnings against using c_encryptupdate/c_decryptupdate above) ckm_sha224_key_derivation ckm_sha256_key_derivation ckm_sha384_key_derivation ckm_sha512_key_derivation ...
... changes in nss 3.14 bug 333601 - performance enhancements for intel macs when building for intel macs, nss will now take advantage of optimized assembly code for common operations.
NSS 3.18 release notes
ource distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_18_rtm/src/ new in nss 3.18 new functionality when importing certificates and keys from a pkcs#12 source, it's now possible to override the nicknames, prior to importing them into the nss database, using new api sec_pkcs12decoderrenamecertnicknames.
... in p12.h sec_pkcs12decoderrenamecertnicknames - call an application provided callback for each certificate found in a sec_pkcs12decodercontext.
...an application that uses sec_pkcs12decoderrenamecertnicknames must implement a callback function that implements this function interface.
... the following ca certificates had the websites and code signing trust bits turned off ou = equifax secure certificate authority sha1 fingerprint: d2:32:09:ad:23:d3:14:23:21:74:e4:0d:7f:9d:62:13:97:86:63:3a cn = equifax secure global ebusiness ca-1 sha1 fingerprint: 7e:78:4a:10:1c:82:65:cc:2d:e1:f1:6d:47:b4:40:ca:d9:0a:19:45 cn = tc trustcenter class 3 ca ii sha1 fingerprint: 80:25:ef:f4:6e:...
NSS 3.19.2.1 release notes
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.
... because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss.
NSS 3.19.4 release notes
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.
... because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss.
NSS 3.20.1 release notes
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.
... because nss includes portions of the affected nspr code at build time, it is necessary to use nspr 4.10.10 when building nss.
NSS 3.35 release notes
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.
...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.
... 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.
...if these experimental functions are made permanent in a later nss release, no change to code is necessary.
Encrypt Decrypt_MAC_Using Token
nss sample code 3: encryption/decryption and mac using token object.
... /* this source code form is subject to the terms of the mozilla public * license, v.
... 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.
...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.
Overview of NSS
nss includes a framework to which developers and oems can contribute patches, such as assembler code, to optimize performance on their platforms.
... source code for a java interface to nss is available in the mozilla cvs tree.
... nss comes with an extensive and growing set of documentation, including introductory material, api references, man pages for command-line tools, and sample code.
...the latest source code is available for free worldwide from https://www.mozilla.org and its mirror sites.
PKCS 7 functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions sec_pkcs7addcertificate mxr 3.3 and later sec_pkcs7addrecipient mxr 3.2 and later sec_pkcs7addsigningtime mxr 3.2 and later sec_pkcs7containscertsorcrls mxr 3.4 and later sec_pkcs7contentisencrypted mxr 3.4 and later sec_pkcs7contentissigned mxr 3.4 and later sec_pkcs7contenttype mxr 3.2 and later sec_pkcs7copycontentinfo mxr 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_pkcs7destroycontentinfo mxr 3.2 and later sec_pkcs7encode m...
...xr 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_pkcs7getcertificatelist mxr 3.2 and later sec_pkcs7getcontent mxr 3.2 and later sec_pkcs7getencryptionalgorithm mxr 3.2 and later sec_pkcs7getsignercommonname mxr 3.4 and later sec_pkcs7getsigneremailaddress mxr 3.4 and later sec_pkcs7getsigningtime mxr 3.4 and later...
NSS tools : crlutil
if located in file it should be encoded in asn.1 encode format.
... * add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for the certificate revocation.
... reasoncode non-critical code where: reasoncode: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension code: the following codes are available: unspecified (0), keycompromise (1), cacompromise (2), affiliationchanged (3), superseded (4), cessationofoperation (5), certificatehold (6), removefromcrl (8), privilegewithdrawn (9), aacompromise (10) * add invalidity date extension: the invalidity date is a non-critical crl entry extension that provides the date on which it is known or suspected that the private key was compromised or that the certificate otherwise became invalid.
...the nss site relates directly to nss code changes and releases.
ssltyp.html
as long as you use the form shown here, your code will not need revision.
... 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.
...use pr_geterror to retrieve the error code.
...use pr_geterror to retrieve the error code.
NSS Tools cmsutil
the options and arguments for the cmsutil command are defined as follows: options -ddecode a message.
... arguments -c content use this detached content (decode only).
... -h num generate email headers with info about cms message (decode only).
... -n suppress output of contents (decode only).
NSS Tools crlutil
if located in file it should be encoded in asn.1 encode format.
... add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for the certificate revocation.
... reasoncode non-critical code where: reasoncode: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension code: the following codes are available: unspecified (0), keycompromise (1), cacompromise (2), affiliationchanged (3), superseded (4), cessationofoperation (5), certificatehold (6), removefromcrl (8), privilegewithdrawn (9), aacompromise (10) add invalidity date extension: the invalidity date is a non-critical crl entry extension that provides the date on which it is known or suspected that the private key was compromised or that the certificate otherwise became invalid.
... entry (2): serial number: 42 (0x2a) revocation date: wed feb 23 12:08:40 2005 deleting crl from a database this example deletes crl from a database in the specified directory: crlutil -d -n nickname -d certdir importing crl into a database this example imports crl into a database: crlutil -i -i crl-file -d certdir file should has binary format of asn.1 encoded crl data.
NSS tools : crlutil
MozillaProjectsNSStoolscrlutil
if located in file it should be encoded in asn.1 encode format.
... * add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for the certificate revocation.
... reasoncode non-critical code where: reasoncode: identifies the name of an extension non-critical: should be set to 0 since this is non-critical extension code: the following codes are available: unspecified (0), keycompromise (1), cacompromise (2), affiliationchanged (3), superseded (4), cessationofoperation (5), certificatehold (6), removefromcrl (8), privilegewithdrawn (9), aacompromise (10) * add invalidity date extension: the invalidity date is a non-critical crl entry extension that provides the date on which it is known or suspected that the private key was compromised or that the certificate otherwise became invalid.
...the nss site relates directly to nss code changes and releases.
Network Security Services
get the source code and build it instructions on how to build nss on the different supported platforms.
... 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.
... 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.
Rhino history
originally, rhino compiled all javascript code to java bytecodes in generated classfiles.
...first, compilation time was long since generating java bytecodes and loading the generated classes was a heavyweight process.
...the classfile generation code was moved to an optional, dynamically-loaded package.
...since its release to open source, rhino has found a variety of uses and an increasing number of people have contributed to the code.
Scripting Java
accessing java packages and classes every piece of java code is part of a class.
...for example, the following code actually calls the file object's getname and isdirectory methods.
... 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.
... java exceptions exceptions thrown by java methods can be caught by javascript code using try...catch statement.
Rhino serialization
however, serialization of code in compilation mode has some significant limitations.
...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.
...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.
...(it might be possible to save the java bytecodes in an array and then load the class upon deserialization, but at best that would eat up a lot of memory for just this feature.) one way around this is to compile the functions using the jsc tool: $ cat f.js function f() { return 3; } $ java -classpath js.jarorg.mozilla.javascript.tools.jsc.main f.js $ cat test2.js loadclass("f"); serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ jav...
SpiderMonkey Build Documentation
use these instructions to build the latest spidermonkey source code.
... and of course, you'll need to get the spidermonkey source code.
... 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.
... 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.
GC Rooting Guide
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.
...consider: jsobject* somefunction(jscontext* cx) { js::rooted<jsobject*> obj(cx, foo()); eventlogger logger(cx); ...code...
...there are two different approaches to resolving this; use whichever better fits your situation: void somefunction(jscontext* cx, js::mutablehandleobject obj) { eventlogger(cx); ...code...
... eventlogger(cx); ...code...
JS_GetLocaleCallbacks
callback functions struct jslocalecallbacks { jslocaletouppercase localetouppercase; jslocaletolowercase localetolowercase; jslocalecompare localecompare; // not used #if expose_intl_api jslocaletounicode localetounicode; }; typedef bool (* jslocaletouppercase)(jscontext *cx, js::handlestring src, js::mutablehandlevalue rval); typedef bool (* jslocaletolowercase)(jscontext *cx, js::handlestring src, js::mutablehandlevalue rval); typedef bool (* jslocalecompare)(jscontext *cx, js::handlestring src1, js::handlestring src2, js::mutablehandlevalue rval); typedef bool (* j...
...slocaletounicode)(jscontext *cx, const char *src, js::mutablehandlevalue rval); type description jslocaletouppercase implementation of string.prototype.tolocaleuppercase() function.
... jslocaletounicode convert locale specific string to unicode string.
...see also mxr id search for js_getlocalecallbacks mxr id search for js_setlocalecallbacks mxr id search for jslocalecallbacks mxr id search for jslocaletouppercase mxr id search for jslocaletolowercase mxr id search for jslocalecompare mxr id search for jslocaletounicode ...
JS_GetStringEncodingLength
str jsstring * a string to encode.
...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 js_encodestringtobuffer js::deflatestringtoutf8buffer js::getdeflatedutf8stringlength bug 607292 ...
JS_ReportErrorNumber
report an error with an application-defined error code.
... errornumber const unsigned an error code.
...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.
...otherwise, no javascript code is running in cx.
SpiderMonkey 1.8
you can download full source code here: http://ftp.mozilla.org/pub/mozilla.org/js/js-1.8.0-rc1.tar.gz (md5 checksum: eaad8815dcc66a717ddb87e9724d964e).
... the security apis js_setcheckobjectaccesscallback, js_setprincipalstranscoder, and js_setobjectprincipalsfinder are still present but are deprecated in this release.
... js_encodestring is a new variation on js_getstringbytes that returns a newly allocated, writable buffer which the application must js_free.
...this is to help applications share and reuse code regardless of whether they use threads.
AT APIs Support
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.
...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.
... 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.
Places utilities for JavaScript
void openurinodesintabs(array nsinavhistoryresultnode anodes, nsidomevent aevent); void createmenuitemfornode(nsinavhistoryresultnode anode, acontainersmap); constants mimetypes type_x_moz_place_container type_x_moz_place_separator: "text/x-moz-place-separator", type_x_moz_place: "text/x-moz-place", type_x_moz_url: "text/x-moz-url", type_html: "text/html", type_unicode: "text/unicode", services there's easy access to some of the common services used in bookmarks or history navigation here.
...this is useful for wrapping a container as type_x_moz_url, type_html or type_unicode.
...for example, given a uri, the traditional code to get all its annotations would be: var annotationservice = components.classes["@mozilla.org/browser/annotation-service;1"] .getservice(components.interfaces.nsiannotationservice); try { var names = annotationservice.getpageannotationnames(uri); } catch(e) { // no annotations } var annotations = new array(); for(var i in names) { try { annotations.push(annotationservice.g...
...etpageannotation(uri, names[i])); } catch(e) { // this shouldn't happen } } the code using placesutils collapses a bit to: var annotations = placesutils.getannotationsforuri(uri); saving you a bit of clumsy code and leaving mozilla to make sure everything is written correctly.
Creating a Python XPCOM component
note: there are exceptions; see this discussion for information on the use of string and wstring for unicode transfer.
...make a file named "py_simple.py" for the actual code (again, in the 'components' directory): from xpcom import components, verbose class pysimple: #pythontestcomponent _com_interfaces_ = components.interfaces.nsipysimple _reg_clsid_ = "{c456ceb5-f142-40a8-becc-764911bc8ca5}" _reg_contractid_ = "@mozilla.org/pysimple;1" def __init__(self): self.yourname = "a default name" # or mname ?
... # _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.
...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.
Detailed XPCOM hashtable guide
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.
...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.
...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.
...the mozilla codebase already contains hash functions for most key types, including narrow and wide strings, pointers, and most binary data: void* (or nsisupports*) cast using ns_ptr_to_int32 char* string nscrt::hashcode() prunichar* string nsastring hashstring() nsacstring nsid& nsidhashkey::hashkey() writing a good hash function is wel...
Components.utils.evalInWindow
this function enables code running in a more-privileged javascript context to evaluate a string in a less-privileged javascript context.
... 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).
...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.importGlobalProperties
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.
... 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.
...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.
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.
...if the javascript code module has not yet been imported then this method will do nothing.
... 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.
Components.utils.unwaiveXrays
for example, if privileged code accesses a dom object belonging to web content, it will by default see it using xray vision, meaning that among other things expando properties added to the object by content are not visible.
... privileged code can waive xray vision using waivexrays, and it will then see expandos.
...example suppose a page script adds an expando to its global window: // page script foo = "i'm an expando"; by default, chrome code won't see foo, because it sees the content window with xray vision, but the chrome code can waive xray protection.
... the chrome code can then use unwaivexrays to restore xray protection: // chrome code // contentwindow is an xray var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); // true // expandos are not visible in xrays var foo = gbrowser.contentwindow.foo; // undefined // you can waive xray vision for an object var waived = components.utils.waivexrays(gbrowser.contentwindow); isxray = components.utils.isxraywrapper(waived); // false foo = waived.foo; // "i'm an expando" // waiving is transitive isxray = components.utils.isxraywrapper(waived.document); // false // use unwaivexrays to undo the waiver var unwaived = components.utils.unwaivexrays(waived); isxray = com...
Components.utils.waiveXrays
when privileged javascript in gecko accesses objects belonging to less-privileged code (such as untrusted web content), it does so, by default, with "xray vision": a mechanism that filters out certain changes to the objects that could cause them to behave in unexpected ways.
... for example, privileged code using an xray to a dom object sees only the original, native version of the dom object.
...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.
...example suppose a page script adds an expando to its global window: // page script foo = "i'm an expando"; by default, chrome code won't see foo, because it sees the content window with xray vision, but the chrome code can waive xray protection: // chrome code // contentwindow is an xray var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); // true // expandos are not visible in xrays var foo = gbrowser.contentwindow.foo; // undefined // you can waive xray vision for an obje...
NS_NewNativeLocalFile
this string should be encoded using ascii or the multibyte character coding corresponding to the native filesystem.
...otherwise, it returns an error code.
...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.
... 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.
XPCOM glue classes
these "glue" classes are provided to make it easier to use xpcom from c++ code.
...nvertasciitoutf16 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.
...this class is typically used to represent unicode character arrays.nsastring (external)class declarationnsastring_internalclass declarationnsautorefnsautoref<t> is a template class implementing an object that holds a handle to a resource that must be released, typically on destruction 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 encodings understood by the ns_cstringtoutf16 and ns_utf16tocstring functions.nsdependentcstringclass declarationnsdependentcstring externalclass declarationnsdependentcsubstring...
nsIAbCard
following a huge refactoring of the address book code, most of the documentation below is out of date.
... inherits from: nsisupports method overview astring getcardvalue(in string name) void setcardvalue(in string attrname, in astring value) void copy(in nsiabcard srccard) boolean equals(in nsiabcard card) string converttobase64encodedxml() astring converttoxmlprintdata() string converttoescapedvcard() astring generatename(in long agenerateformat,[optional] in nsistringbundle abundle) astring generatephoneticname(in boolean alastnamefirst) attributes attribute type description firstname astring lastname astring phoneticfirstna...
... 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 ...
... 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.
nsIAppStartup
bracket the code where the last window could close with these.
...bracket the code where the last window could close with these.
... 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.
nsICrashReporter
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!
... native code only!appendobjcexceptioninfotoappnotes append note containing an obj-c exception's info.
... native code only!writeminidumpforexception write a minidump immediately, with the user-supplied exception information.
nsIDOMWindow
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.
...native code only!
...native code only!
...native code only!
nsIDeviceMotion
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!
... native code only!addwindowlistener sets the nsiaccelerometer as the source for mozorientation events on the specified dom window.
... native code only!removewindowlistener removes the nsiaccelerometer as the source for mozorientation events on the specified dom window.
nsIInputStream
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!
... native code only!read this method copies data from the stream into a buffer.
... native code only!readsegments this method provides direct access to the stream's internal buffer.
nsIOutputStream
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!
... 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.
... native code only!writesegments low-level write method that has access to the stream's underlying buffer.
nsIScriptableIO
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.
... 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.
... text: read unicode-converted text.
... text: write unicode-converted text.
nsISelection
mponents.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsiselection); method overview void addrange(in nsidomrange range); void collapse(in nsidomnode parentnode, in long offset); [noscript,notxpcom,nostdcall] boolean collapsed(); void 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!
... 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).
... native code only!extendnative void extendnative( in nsinode parentnode, in long offset ); parameters parentnode offset getrangeat() returns the nsidomrange at the specified index.
nsIServerSocket
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!
... native code only!getaddress returns the address to which this server socket is bound.
... 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).
nsISocketProvider
instance, use: var socketprovider = components.classes["@mozilla.org/network/socket;2?type="] .createinstance(components.interfaces.nsisocketprovider); method overview void addtosocket(in long 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!
... 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.
... native code only!newsocket creates a new socket.
nsITraceableChannel
see nsitraceablechannel, intercept http traffic for a more detailed description with code samples.
...holds chunks as they come, onstoprequest we join these junks to get the full source this.responsebody; // we'll set this to the this.responsestatuscode; this.deferreddone = { promise: null, resolve: null, reject: null }; this.deferreddone.promise = new promise(function(resolve, reject) { this.resolve = resolve; this.reject = reject; }.bind(this.deferreddone)); object.freeze(this.deferreddone); this.promisedone = this.deferreddone.promise; } tracinglistener.prototype = { ondataavailable: function(arequest, acontext, ainputstream...
... var data = istream.readbytes(acount); this.receivedchunks.push(data); ostream.writebytes(data, acount); this.originallistener.ondataavailable(arequest, acontext, sstream.newinputstream(0), aoffset, acount); }, onstartrequest: function(arequest, acontext) { this.originallistener.onstartrequest(arequest, acontext); }, onstoprequest: function(arequest, acontext, astatuscode) { this.responsebody = this.receivedchunks.join(""); delete this.receivedchunks; this.responsestatus = astatuscode; this.originallistener.onstoprequest(arequest, acontext, astatuscode); this.deferreddone.resolve(); }, queryinterface: function(aiid) { if (aiid.equals(ci.nsistreamlistener) || aiid.equals(ci.nsisupports)) { return this; } throw cr.ns_nointerface; } }; var htt...
...i.nsitraceablechannel); newlistener.originallistener = asubject.setnewlistener(newlistener); /////// end - do not edit newlistener.promisedone.then( function() { // no error happened console.log('yay response done:', newlistener.responsebody); }, function(areason) { // promise was rejected, right now i didnt set up rejection, but i should listen to on abort or bade status code then reject maybe } ).catch( function(acatch) { console.error('something went wrong, a typo by dev probably:', acatch); } ); } }; services.obs.addobserver(httpresponseobserver, 'http-on-examine-response', false); // services.obs.removeobserver(httpresponseobserver, 'http-on-examine-response'); // call this when you dont want to listen anymore ...
nsIXPCException
inherits from: nsiexception last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview void initialize(in string amessage, in nsresult aresult, in string aname, in nsistackframe alocation, in nsisupports adata, in nsiexception 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.
NS_CStringToUTF16
the result will be encoded using the host byte order.
...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.
NS_UTF16ToCString
the source string should be encoded using the host byte order.
...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.
nsIAbCard/Thunderbird3
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.
...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.
...most notably, the code a.equals(b) == b.equals(a) might not return true.
XPCOM reference
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.
...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.
...prior to gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16), this was an integer that simply returned an error code.
Frequently Asked Questions
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.
...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?
...exploring this code is not an adventure for the faint of heart.
wrappedJSObject
there are two kinds of xpconnect wrappers that support the wrappedjsobject property: xpcnativewrappers which are used to protect the chrome code working with content objects.
... for simplicity we omit the component registration code.
... 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.
... 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.
customDBHeaders Preference
also, it has been brought to my attention that the delimiter has been changed to a space in the latest code.
... when using the latest releases, the line should look like: // space-delimited list in the latest code!
...> <splitter class="tree-splitter" /> <treecol id="colsuperfluous" persist="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.
... 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.
Examples
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.
... the js-macosx bridge has dependency on bridgesupport metadata: whenever a cocoa class, function, struct or const is encountered in the javascript code, js-macosx will replace it with the corresponding js-ctypes declaration based on the bridgesupport file from the framework that object belongs to.
Working with ArrayBuffers
the second code example provides a specific illustration of the operation.
... the following codeblock provides a basic example of getting and setting uint8clampedarray and arraybuffer of imagedata: // context is a canvasrenderingcontext2d of some canvas var imagedata = context.getimagedata(x, y, w, h); var array = imagedata.data; // array is a uint8clampedarray var buffer = imagedata.data.buffer; // buffer is a arraybuffer // incomingbuffer is a typedarray var imagedata2 = context.createim...
...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.
... method 2: manually handled another strategy is to handle it manually, as illustrated by the following code example: 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 /** method a **/ for (var nindex = 0; nindex < casted.length; nindex = nindex + 4) { // casted.length is same as myimgdat.data.length var r = casted[nindex]; var g = casted[nin...
Constants - Plugins
error codes code value description nperr_no_error 0 no errors occurred.
... nperr_generic_error 1 error with no specific error code occurred.
... result codes constant value description npres_done 0 (most common): completed normally; all data was sent to the instance.
... plug-in version constants constant value description np_version_major 0 major version number; changes with major code release number.
Initialization and Destruction - Plugins
initialization: the browser calls the plug-in api function np_initialize when the plug-in code is first loaded.
... 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.
... 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.
... 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.
URLs - Plugins
javascript executes javascript code that follows the url.
... posting data to an http server the following code posts two name-value pairs to a cgi script through http.
... 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.
...the following code sends a mail message with the default headers from the client machine.
Set watch expressions - Firefox Developer Tools
when debugging code, sometimes it's useful to watch expressions as executions are paused.
...as you step through code, the debugger will watch the expression and return any results.
... 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.
UI Tour - Firefox Developer Tools
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.
... 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.
...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.
Debugger.Environment - Firefox Developer Tools
(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.
... 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.
... this is not an invocation function; if this call would cause debuggee code to run, this call throws a debugger.debuggeewouldrun exception.
Tutorial: Set a breakpoint - Firefox Developer Tools
since the debugger api is only available to privileged javascript code, you’ll need to use the browser content toolbox to try it out.
... 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.
... 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.
...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.
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.
... 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.
... 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.
Monster example - Firefox Developer Tools
here's the code: var monster_count = 5000; var min_name_length = 2; var max_name_length = 48; function monster() { function randomint(min, max) { return math.floor(math.random() * (max - min + 1)) + min; } function randomname() { var chars = "abcdefghijklmnopqrstuvwxyz"; var namelength = randomint(min_name_length, max_name_length); var name = ""; for (var j = 0; j &lt; namelength; j++) { name += chars[randomint(0, chars.length-1)]; } return name; } this.name = randomname(); this.eyecount = randomint(0, 25); this.tentaclecount = rando...
...or (var i = 0; i &lt; monster_count; i++) { monsters.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.
Migrating from Firebug - Firefox Developer Tools
both allow you to debug javascript code executed on a website.
... 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.
... 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.
Flame Chart - Firefox Developer Tools
the flame chart shows you the state of the javascript stack for your code at every millisecond during the performance profile.
...functions are color-coded to make them easier to distinguish.
...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().
... 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.
AbstractWorker - Web APIs
example as an abstract interface, you won't directly use abstractworker in your code.
... 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.
BaseAudioContext.createBuffer() - Web APIs
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.
...you can also run the code live, or view the source.
CSSStyleSheet.insertRule() - Web APIs
* @param {array} rules accepts an array of json-encoded declarations * @example addstylesheetrules([ ['h2', // also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green', true] // 'true' for !important rules ], ['.myclass', ['background-color', 'yellow'] ] ]); */ function addstylesheetrules (rules) { var styleel = document.createelement('style'); // append <style> element to <...
... (function(sheet_proto){ var originalinsertrule = sheet_proto.insertrule; if (originalinsertrule.length === 2){ // 2 mandatory arguments: (selector, rules) sheet_proto.insertrule = function(selectorandrule){ // first, separate the selector from the rule a: for (var i=0, len=selectorandrule.length, isescaped=0, newcharcode=0; i !== len; ++i) { newcharcode = selectorandrule.charcodeat(i); if (!isescaped && (newcharcode === 123)) { // 123 = "{".charcodeat(0) // secondly, find the last closing bracket var openbracketpos = i, closebracketpos = -1; for (; i !== len; ++i) { newcharcode = selectorandrule.charcodeat(i); if (!isescaped && (newcharcode ==...
...= 125)) { // 125 = "}".charcodeat(0) closebracketpos = i; } isescaped ^= newcharcode===92?1:isescaped; // 92 = "\\".charcodeat(0) } if (closebracketpos === -1) break a; // no closing bracket was found!
... /*else*/ return originalinsertrule.call( this, // the sheet to be changed selectorandrule.substring(0, openbracketpos), // the selector selectorandrule.substring(closebracketpos), // the rule arguments[3] // the insert index ); } // works by if the char code is a backslash, then isescaped // gets flipped (xor-ed by 1), and if it is not a backslash // then isescaped gets xored by itself, zeroing it isescaped ^= newcharcode===92?1:isescaped; // 92 = "\\".charcodeat(0) } // else, there is no unescaped bracket return originalinsertrule.call(this, selectorandrule, "", arguments[2]); }; } })(cssstylesheet.prototype); specifications specification statu...
CacheStorage - Web APIs
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.
... in the second code block, we wait for a fetchevent to fire.
...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.
...async function getdata() { const cacheversion = 1; const cachename = `myapp-${ cacheversion }`; const url = 'https://jsonplaceholder.typicode.com/todos/1'; let cacheddata = await getcacheddata( cachename, url ); if ( cacheddata ) { console.log( 'retrieved cached data' ); return cacheddata; } console.log( 'fetching fresh data' ); const cachestorage = await caches.open( cachename ); await cachestorage.add( url ); cacheddata = await getcacheddata( cachename, url ); await deleteoldcaches( cachename ); return cacheddata; } // get data from the cache.
DedicatedWorkerGlobalScope - Web APIs
dedicatedworkerglobalscope.onmessage is an eventhandler representing the code to be called when the message event is raised.
...from the worker.postmessage method.) dedicatedworkerglobalscope.onmessageerror is an eventhandler representing the code to be called when the messageerror event is raised.
...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.
DirectoryEntrySync - Web APIs
parameter none exceptions this method can raise a fileexception with the following codes: exception description not_found_err the directory does not exist.
... exceptions this method can raise a fileexception with the following codes: exception description encoding_err the path supplied is invalid.
... exceptions this method can raise a fileexception with the following codes: exception description encoding_err the path supplied is invalid.
... 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.
FetchEvent.request - Web APIs
example this code snippet is from the service worker fetch sample (run the fetch sample live).
...if no match is found, the code fetches a response from the network.
... the code also handles exceptions thrown from the serviceworkerglobalscope.fetch operation.
...it will return a normal response object that has the appropriate error code set.
FileException - Web APIs
it extends the fileexception interface described in file writer and adds several new error codes.
...to simplify things a bit, wrap your worker code in a try/catch.
...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.
... other unspecified security error code or situations.
FileReader.readAsDataURL() - Web APIs
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.
...for a full compatibility code you can see our crossbrowser possible solution for image preview.
FileSystemEntrySync - Web APIs
[ 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.
... 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.
... 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.
... 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.
GlobalEventHandlers.onkeypress - Web APIs
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.
... html <label>enter numbers only: <input> </label> javascript function numbersonly(event) { return event.charcode === 0 || /\d/.test(string.fromcharcode(event.charcode)); } const input = document.queryselector('input'); input.onkeypress = numbersonly; // prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; result capture the typing of a hidden word the following javascript function will do something after the user types the word "exit" in any point of a page.
...*/ (function () { const ssecret = /* choose your hidden word...: */ "exit"; let noffset = 0; document.onkeypress = function(opevt) { let oevent = opevt || window.event, nchr = oevent.charcode, snodetype = oevent.target.nodename.touppercase(); if (nchr === 0 || oevent.target.contenteditable.touppercase() === "true" || snodetype === "textarea" || snodetype === "input" && oevent.target.type.touppercase() === "text") { return true; } if (nchr !== ssecret.charcodeat(noffset)) { noffset = nchr === ssecret.charcodeat(0) ?
HTMLImageElement - Web APIs
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).
... 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.
HTMLObjectElement - Web APIs
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.
... the following properties are now obsolete: align, archive, border, code, codebase, codetype, declare, hspace, standby, and vspace.
IDBDatabaseSync - Web APIs
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.
... 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.
... 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.
... 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.key - Web APIs
WebAPIKeyboardEventkey
if the pressed key has a printed representation, the returned value is a non-empty unicode character string containing the printable representation of the key.
... some specialty keyboard keys (such as the extended keys for controlling media on multimedia keyboards) don't generate key codes on windows; instead, they trigger wm_appcommand events.
... these events get mapped to dom keyboard events, and are listed among the "virtual key codes" for windows, even though they aren't actually key codes.
...when they occur, the key's value is checked to see if it's one of the keys the code is interested in, and if it is, it gets processed in some way (possibly by steering a spacecraft, perhaps by changing the selected cell in a spreadsheet).
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.
... example <html> <head> <title>charcode/keycode/which example</title> <script type="text/javascript"> function showkeypress(evt) { alert("onkeypress handler: \n" + "keycode property: " + evt.keycode + "\n" + "which property: " + evt.which + "\n" + "charcode property: " + evt.charcode + "\n" + "character key pressed: " + string.fromcharcode(evt.charcode) + "\n" ); } function keydown(evt) { alert("onkeydown handler: \n" + "keycode property: " + evt.keycode + "\n" + "which property: " + evt.which + "\n" ); } </script> </head> <body onkeypress="showkeypress(event);" onkeydown="keydown(event);" > <p>please press any key.</p> </body> </html> specifications specification status comment document object model...
MediaConfiguration - Web APIs
bitrate: number of bits used to encode one second of the audio file.
... bitrate: number of bits used to encode one second of the video file.
... 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.
... } }; 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.
MediaError - Web APIs
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.
... 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_decode 3 despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting in an error.
... 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.
MediaRecorder.mimeType - Web APIs
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.
...this string may include the codecs parameter, giving details about the codecs and the codec configurations used by the media recorder.
... 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".
MediaRecorder - Web APIs
error fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
...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...
...unction(err) { console.log('the following error occurred: ' + err); }) } this code sample is inspired by the web dictaphone demo.
... some lines have been omitted for brevity; refer to the source for the complete code.
MediaSource.endOfStream() - Web APIs
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.
...their sourcebuffer.updating property is true.) example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) 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); } 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 }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'endofstream()' in that specification.
MediaSource.isTypeSupported() - Web APIs
this may include the codecs parameter to provide added details about the codecs used within the file.
...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.
... example the following snippet is from an example written by nick desaulniers (view the full demo live, or download the source for further investigation.) 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); } 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 }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'istypesupported()' in that specification.
Microdata DOM API - Web APIs
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.
... 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.
... code example in an earlier example, a "http://example.org/animals#cat" item had two "http://example.com/color" values.
... 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.
Using Navigation Timing - Web APIs
the navigation timing api lets you easily obtain detailed and highly accurate timing information to help isolate performance problems with your site's code or resources.
...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.
...the new code looks like this: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; output = "load time: " + loadingtime + " ms<br/>"; output += "navigation type: "; switch(performance.navigation.type) { case performancenavigation.type_navigate: output += "navigation"; break; case performanc...
... 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
once a timer's code has finished running, the duration of time it took to execute is subtracted from its window's timeout budget.
... 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.
... the example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code: // set the name of the hidden property and the change event for visibility var hidden, visibilitychange; if (typeof document.hidden !== "undefined") { // opera 12.10 and firefox 18 and later support hidden = "hidden"; visibilitychange = "visibilitychange"; } else if (typeof document.mshidden !== "undefined") { hidden = "mshidden"; visibilitychange = "msvisibilitychange"; } else if (typeof document.webkithidden !== "undefined") { hidden = "webkithidden"; visibilitychange = "webkitvisibilitychange"; } var videoel...
... document.onvisibilitychange an eventlistener providing the code to be called when the visibilitychange event is fired.
RTCDataChannel: error event - Web APIs
examples // strings for each of the sctp cause codes found in rfc // 4960, section 3.3.10: // https://tools.ietf.org/html/rfc4960#section-3.3.10 const sctpcausecodes = [ "no sctp error", "invalid stream identifier", "missing mandatory parameter", "stale cookie error", "sender is out of resource (i.e., memory)", "unable to resolve address", "unrecognized sctp chunk type received", "invalid mandatory parameter", "unrecognized para...
... 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...
...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.
...*/ } note: since rtcerror is not one of the legacy errors, the value of rtcerror.code is always 0.
RTCPeerConnection.addIceCandidate() - Web APIs
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.
...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.
... examples this code snippet shows how to signal ice candidates across an arbitrary signaling channel.
RTCPeerConnection.onicecandidateerror - Web APIs
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.
RTCRtpReceiver.getCapabilities() static function - Web APIs
the static function rtcrtpreceiver.getcapabilities() returns an rtcrtpcapabilities object describing the codecs and capabilities supported by rtcrtpreceivers on the current device.
... 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.
... 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.
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.
...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.
... 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.
RTCRtpSender.getCapabilities() static function - Web APIs
the static function rtcrtpsender.getcapabilities() returns an rtcrtpcapabilities object describing the codecs and capabilities supported by the rtcrtpsender.
... 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.
... 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.
RTCRtpSender.setParameters() - Web APIs
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.
... encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media.
... operationerror any error condition which occurs that isn't covered by one of the other error codes results in an operationerror.
... 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.
ReadableStreamDefaultReader.read() - Web APIs
(see our simple random stream example for the full code).
... async function* maketextfilelineiterator(fileurl) { const utf8decoder = new textdecoder("utf-8"); let response = await fetch(fileurl); let reader = response.body.getreader(); let {value: chunk, done: readerdone} = await reader.read(); chunk = chunk ?
... utf8decoder.decode(chunk) : ""; let re = /\r\n|\n|\r/gm; let startindex = 0; let result; for (;;) { let result = re.exec(chunk); if (!result) { if (readerdone) { break; } let remainder = chunk.substr(startindex); ({value: chunk, done: readerdone} = await reader.read()); chunk = remainder + (chunk ?
... utf8decoder.decode(chunk) : ""); startindex = re.lastindex = 0; continue; } yield chunk.substring(startindex, result.index); startindex = re.lastindex; } if (startindex < chunk.length) { // last line didn't end in a newline char yield chunk.substr(startindex); } } for await (let line of maketextfilelineiterator(urloffile)) { processline(line); } specifications specification status comment streamsthe definition of 'read()' in that specification.
Screen.availHeight - Web APIs
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.
...that code handles resizing the window based on the available space: window.outerheight = window.screen.availheight; the result is something similar to the below.
Using the Screen Capture API - Web APIs
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.
... 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.
...using await, the following line of code does not get executed until after the promise returned by getdisplaymedia() resolves.
...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> ...
ServiceWorkerContainer.register() - Web APIs
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.
... navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } the following code, if included in example.com/index.html, at the root of a site, would apply to exactly the same pages as the example above.
... 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.
... 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.
Streams API concepts - Web APIs
the reader plus the other processing code that goes along with it is called a consumer.
...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).
...you can use whatever code you like to produce the chunks ready for writing; the writer plus the associated code is called a producer.
...a simple example is a text decoder, where raw bytes are written, and then strings are read.
Using readable streams - Web APIs
you can find the full source code there, as well as links to the examples.
...inside this method, you should include code that sets up the stream functionality, e.g.
... 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.
... note: in order to consume a stream using fetchevent.respondwith(), the enqueued stream contents must be of type uint8array; for example, encoded using textencoder.
SubtleCrypto.digest() - Web APIs
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.
... 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.
...the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const msguint8 = new textencoder().encode(message); // encode as (utf-8) uint8array const hashbuffer = await crypto.subtle.digest('sha-256', msguint8); // hash the message const hasharray = array.from(new uint8array(hashbuffer)); // convert buffer to byte array const hashhex = hasharray.map(b => b.tostring(16).padstart(2, '0')).join(''); // convert bytes to hex string return hashhex; } const digesthex = await digestmessage(text); console.log(digesthex); specifications specification ...
SubtleCrypto.unwrapKey() - Web APIs
see the complete code on github.
...*/ 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.
...see the complete code on github.
...*/ 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.
USVString - Web APIs
WebAPIUSVString
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, (�).
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
these are only available to the javascript code and the vertex shader.
... 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.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().
WebGLRenderingContext.vertexAttribPointer() - Web APIs
if you are using webgl 2, you can specify the index yourself in the vertex shader code and override the default used by the graphics card, e.g.
...if you need to use integers in your vertex shader code, you can either cast the float back to an integer in the vertex shader (e.g.
... default attribute values the vertex shader code may include a number of attributes, but we don't need to specify the values for each attribute.
...however, these functions are great for debugging a webgl context without touching the application code.
WebGL by example - Web APIs
explanations about the examples are found in both the main text and in comments within the code.
... you should read all comments, because more advanced examples could not repeat comments about parts of the code that were previously explained.
... 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.
... textures from code a simple demonstration of procedural texturing with fragment shaders.
Data in WebGL - Web APIs
WebAPIWebGL APIData
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.
... 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.
... <<how to use>> uniforms uniforms are set by the javascript code and are available to both the vertex and fragment shaders.
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
this enormously simplifies and makes far more readable the code dealing with the promises returned by webrtc methods.
... async function enablehold(audiostream) { try { await audiotransceiver.sender.replacetrack(audiostream.getaudiotracks()[0]); audiotransceiver.receiver.track.enabled = false; audiotransceiver.direction = "sendonly"; } catch(err) { /* handle the error */ } } the three lines of code within the try block perform the following steps: replace their outgoing audio track with a mediastreamtrack containing hold music.
... this triggers renegotiation of the rtcpeerconnection by sending it a negotiationneeded event, which your code responds to generating an sdp offer using rtcpeerconnection.createoffer and sending it through the signaling server to the remote peer.
... just like when hold was engaged, this triggers negotiation again, resulting in your code sending a new offer to the remote peer.
WebXR permissions and security - Web APIs
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.
... 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.
... 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.
... 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.
Using the Web Animations API - Web APIs
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.
... 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).
...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.
...in the red queen’s race example, alice and the red queen are running to stay in place (check out the full code on codepen): because small children tire out easily, unlike automaton chess pieces, alice is constantly slowing down.
Web audio spatialization basics - Web APIs
if you just want a simple stereo panning effect, our stereopannernode example (see source code) should give you everything you need.
...see the 3d spatialization demo live (and see the source code also).
... again, you can check out the final demo here, and the final source code is here.
... there is also a codepen demo too.
Web Authentication API - Web APIs
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).
...rts: ["usb", "nfc", "ble"], type: "public-key" }]; getcredentialdefaultargs.publickey.allowcredentials = idlist; return navigator.credentials.get(getcredentialdefaultargs); }) .then((assertion) => { console.log("assertion", assertion); }) .catch((err) => { console.log("error", err); }); mozilla demo website and its source code.
... google demo website and its source code.
... webauthn.org and its client source code and server source code specifications specification status comment web authentication: an api for accessing public key credentials level 1 recommendation initial definition.
Window.content - Web APIs
WebAPIWindowcontent
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.
...the former has been deprecated for a long time, and you should use content in any new code.
... syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none.
... see also working with windows in chrome code when accessing content documents from privileged code, be aware of xpcnativewrappers.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
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.
... syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to call your code.
...a = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { this._cache[url] = data; this._setdata(data); this.dispatchevent(new event("load")); }); } }; when queuemicrotask() isn't available the code below is basically a monkey-patch for queuemicrotask() for modern engines.
WindowOrWorkerGlobalScope - Web APIs
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.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.
WorkerGlobalScope - Web APIs
close is an eventhandler representing the code to be called when the close event is raised.
... 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.
... 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.
WritableStream.WritableStream() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " +...
... decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
... backpressure because of how backpressure is supported in the api, its implementation in code may be less than obvious.
WritableStream - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " +...
... decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
... backpressure because of how backpressure is supported in the api, its implementation in code may be less than obvious.
WritableStreamDefaultWriter - Web APIs
properties writablestreamdefaultwriter.closedread only allows you to write code that responds to an end to the streaming process.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready a...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); lis...
...titem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
HTML in XMLHttpRequest - Web APIs
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).
...otherwise, the file is decoded as utf-8.
...for older browsers, you can even use the xmlhttprequest.responsetext property in association with regular expressions in order to get, for example, the source code of an html element given its id: function gethtml (oxhr, stargetid) { var ropen = new regexp("<(?!\!)\\s*([^\\s>]+)[^>]*\\s+id\\=[\"\']" + stargetid + "[\"\'][^>]*>" ,"i"), ssrc = oxhr.responsetext, aexec = ropen.exec(ssrc); return aexec ?
Using the alert role - Accessibility
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.
...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.
... 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.
...the pseudo code snippet below illustrates this approach: <p id="forminstruction">you must select at least 3 options</p> // when the user tries to submit the form with less than 3 checkboxes selected: document.getelementbyid("forminstruction").setattribute("role", "alert"); example 4: making an element with an alert role visible if an element already has role="alert" and is initially hidden using css, making it visible will cause the alert to fire as if it was just added to the pag...
ARIA: figure role - Accessibility
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.
... 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".
...xamples we could extend the initial example on the page to also identify a paragraph that provides a descriptive label for the figure by referencing its id in aria-labelledby: <div role="figure" aria-labelledby="figure-1"> <img src="diagram.png" alt="diagram showing the four layers of awesome and their relative priority order — music, cats, nature, and ice cream"> <pre><code> let awesome = ['music', 'cats', 'nature', 'ice cream']; </code></pre> <p id="figure-1">figure 1: the four layers of awesome.</p> </div> best practices only use role="figure" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript.
...for example, our above example should be rewritten as follows: <figure> <img src="diagram.png" alt="diagram showing the four layers of awesome and their relative priority order — music, cats, nature, and ice cream"> <pre><code> let awesome = ['music', 'cats', 'nature', 'ice cream']; </code></pre> <figcaption>figure 1: the four layers of awesome.</figcaption> </figure> specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'figure' in that specification.
ARIA: textbox role - Accessibility
<!-- 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 req...
... <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.
... 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.
Architecture - Accessibility
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'.
...if it has text siblings, then it gets exposed as the unicode char for an embedded object, which is '\xfffc' within the parent nshypertextaccessible.
... 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.
...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.
::before (:before) - CSS: Cascading Style Sheets
WebCSS::before
html <ul> <li>buy milk</li> <li>take the dog for a walk</li> <li>exercise</li> <li>write code</li> <li>play music</li> <li>relax</li> </ul> css li { list-style-type: none; position: relative; margin: 2px; padding: 0.5em 0.5em 0.5em 2em; background: lightgrey; font-family: sans-serif; } li.done { background: #ccff99; } li.done::before { content: ''; position: absolute; border-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.
...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.
... <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> css li { padding:0.5em; } li[aria-current='step'] { font-weight:bold; } li[aria-current='step']::after { content: " \21e6"; /* hexadecimal for unicode leftwards white arrow*/ display: inline; } result specifications specification status comment css pseudo-elements level 4the definition of '::before' in that specification.
Detecting CSS animation support - CSS: Cascading Style Sheets
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.
... testing for css animation support this code will check to see if css animation support is available: var animation = false, animationstring = 'animation', keyframeprefix = '', domprefixes = 'webkit moz o ms khtml'.split(' '), pfx = '', elem = document.createelement('div'); if( elem.style.animationname !== undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i < domprefixes.length; i++ ) { if( elem.style[ domprefixes[i] + 'animationname' ] !== undefined ) { pfx = domprefixes[ i ]; animationstring = pfx + 'animation'; keyframeprefix = '-' + pfx.tolowercase() + '-'; animation = true; break; } } } for start...
... 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.
...) }'+ 'to {' + keyframeprefix + 'transform:rotate( 360deg ) }'+ '}'; if( document.stylesheets && document.stylesheets.length ) { document.stylesheets[0].insertrule( keyframes, 0 ); } else { var s = document.createelement( 'style' ); s.innerhtml = keyframes; document.getelementsbytagname( 'head' )[ 0 ].appendchild( s ); } } this code looks at the value of animation; if it's false, we know we need to use our javascript fallback code to perform our animation.
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
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.
... 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.
...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.
overflow-block - CSS: Cascading Style Sheets
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.
... </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.
... </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.
... </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.
overflow-y - CSS: Cascading Style Sheets
mal 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 setting overflow-y behavior html <ul> <li><code>overflow-y: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.
... </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.
... </div> </li> <li><code>overflow-y: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.
... </div> </li> <li><code>overflow-y: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.
word-break - CSS: Cascading Style Sheets
<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.
... <code>word-break: keep-all</code></p> <p class="keepall narrow">this is a long and honorificabilitudinitatibus califragilisticexpialidocious taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉</p> <p>4.
... <code>word-break: break-word</code></p> <p class="breakword narrow">this is a long and honorificabilitudinitatibus califragilisticexpialidocious taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu グレートブリテンおよび北アイルランド連合王国という言葉は本当に長い言葉</p> css .narrow { padding: 10px; border: 1px solid; width: 500px; margin: 0 auto; font-size: 20px; line-height: 1.5; letter-spacing: 1px; } .normal { word-break: normal; } .breakall { word-break: break-all; } .keepall { word-break: keep-all; } .breakword { word-break: break-word; } specifications specification status comment css text module level 3the definition of 'word-break' in that specification...
Live streaming web audio and video - Developer guides
hls can also be decoded using javascript, which means we can support the latest versions of firefox, chrome and internet explorer 10+.
...of course, we then have the issue that we need to encode in three different formats.
...music and speech can be optimized in different ways and opus uses the silk and celt codecs to achieve this.
...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.
Video player styling basics - Developer guides
the example in action you can find the code for the updated, styled example on github, and view it live.
...this has now been changed to use a data-state attribute, which this code already uses to handle its fullscreen implementation.
... 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.
...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.
Separate sites for mobile and desktop - Developer guides
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.
...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.
...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.
Developer guides
localizations and character encodings browsers process text as unicode internally.
...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.
... 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.
HTML attribute reference - HTML: Hypertext Markup Language
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.
... decoding <img> indicates the preferred method to decode the image.
... 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().
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
implementing this requires configuring the server as well as writing code for the web site itself.
... 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.
... starting the download the code that starts the download (say, when the user clicks a "download" button), looks like this: function startdownload() { let imageurl = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2fmdn_logo-only_color.svg?1535749917189"; downloadedimg = new image; downloadedimg.crossorigin = "anonymous"; downloadedimg.addeventlistener("load", imagereceived, false); downloadedimg.src = imageurl; } we're using a hard-coded url here (imageurl), but that could easily come from anywhere.
... receiving and saving the image the code that handles the newly-downloaded image is found in the imagereceived() method: function imagereceived() { let canvas = document.createelement("canvas"); let context = canvas.getcontext("2d"); canvas.width = downloadedimg.width; canvas.height = downloadedimg.height; context.drawimage(downloadedimg, 0, 0); imagebox.appendchild(canvas); try { localstorage.setitem("saved-image-...
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
WebHTMLElementapplet
code this attribute specifies the url of the applet's class file to be loaded and executed.
...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.
... 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.
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
you should be aware of this behavior so your code can respond appropriately in either case.
... <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.
<keygen> - HTML: Hypertext Markup Language
WebHTMLElementkeygen
the value of the pqg parameter is the the base64 encoded, der encoded dss-parms as specified in ietf rfc 3279.
... 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 encoded as an ia5string of length zero.
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
the html <script> element is used to embed executable code or data; this is typically used to embed or refer to javascript code.
... 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.
...in earlier browsers, this identified the scripting language of the embedded or imported (via the src attribute) code.
... module: causes the code to be treated as a javascript module.
lang - HTML: Hypertext Markup Language
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.
...this subtag defines a dialect of the base language from a particular location, and is either 2 letters in allcaps matching a country code, or 3 numbers matching a non-country area.
... to find the correct subtag codes for a language, try the language subtag lookup.
Access-Control-Allow-Origin - HTTP
the access-control-allow-origin response header indicates whether the response can be shared with requesting code from the given origin.
... header type response header forbidden header name no syntax access-control-allow-origin: * access-control-allow-origin: <origin> access-control-allow-origin: null directives * for requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource.
...the "null" value for the acao header should therefore be avoided." examples a response that tells the browser to allow code from any origin to access a resource will include the following: access-control-allow-origin: * a response that tells the browser to allow requesting code from the origin https://developer.mozilla.org to access a resource will include the following: access-control-allow-origin: https://developer.mozilla.org limiting the possible access-control-allow-origin values to a set of allowed origins r...
...equires code on the server side to check the value of the origin request header, compare that to a list of allowed origins, and then if the origin value is in the list, to set the access-control-allow-origin value to the same value as the origin value.
Network Error Logging - HTTP
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.
... 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", "referrer": "https://example.com/previous-page", "sampling_fraction": 1, "server_ip": "", "status_code": 0, "type": "dns.name_not_resolved", "url": "https://example-host.com/" } } the type of the network error may be one of the following pre-defined values from the specification, but browsers can add and send their own error types: dns.unreachable the user's dns server is unreachable dns.name_not_resolved the user's dns server responded but was unable to resolve an ip address for the requested uri.
...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...
A typical HTTP session - HTTP
WebHTTPSession
the server processes the request, sending back its answer, providing a status code and appropriate data.
... 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.
...(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.
...this response code means that the uri of requested resource has been changed.
Enumerability and ownership of properties - JavaScript
some sample code follows which demonstrates how to obtain the missing categories.
... propertyisenumerable hasownproperty hasownproperty – filtered to exclude enumerables using propertyisenumerable hasownproperty enumerable nonenumerable enumerable and nonenumerable not available without extra code not available without extra code in not available without extra code retrieval enumerable 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 getownpropertynames getownpropertysymbols enumerable nonenumerable enumerable and nonenumerable ...
... for..in (excluding symbols) not available without extra code not available without extra code not available without extra code obtaining properties by enumerability/ownership note that this is not the most efficient algorithm for all cases, but useful for a quick demonstration.
Concurrency model and the event loop - JavaScript
javascript has a concurrency model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.
... 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.
... 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.
Working with objects - JavaScript
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.
...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.
...the second form probably best represents the dynamic nature of javascript — but it can make the code hard to read and understand.
...the following code shows how to remove a property.
Classes - JavaScript
they encapsulate data with code to work on that data.
...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.
... 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.
...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.
ReferenceError: assignment to undeclared variable "x" - JavaScript
declared variables are created before any code is executed.
... undeclared variables do not exist until the code assigning to them is executed.
... errors about undeclared variable assignments occur in strict mode code only.
... in non-strict code, they are silently ignored.
Functions - JavaScript
generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function.
...function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.
... '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.
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.
... 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.
Function - JavaScript
this can be seen with the code (function(){}).constructor === function, which returns true.
... function.prototype.tostring() returns a string representing the source code of the function.
...this is different from using eval with code for a function expression.
...= 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(f2()); // 20 while this code works in web browsers, f1() will produce a referenceerror in node.js, as x will not be found.
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
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.
... 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".
... 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 - 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.
... traditionally, the intl api used strings to represent locales, just as unicode does.
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.
Object.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object.
... syntax object.tosource(); obj.tosource(); return value a string representing the source code of the object.
... description the tosource() method returns the following values: for the built-in object object, tosource() returns the following string indicating that the source code is not available: function object() { [native code] } for instances of object, tosource() returns a string representing the source code.
... examples using tosource() the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); calling the tosource() method of thedog displays the javascript source that defines the object: thedog.tosource(); // returns ({name:"gabby", ...
Object.prototype.toString() - JavaScript
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.
... the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); if you call the tostring() method on this custom object, it returns the default value inherited from object: thedog.tostring(); // returns [ob...
...ject object] the following code creates and assigns dogtostring() to override the default tostring() method.
... 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.
Object - JavaScript
other code cannot delete or change its properties.
... object.seal() prevents other code from deleting properties of an object.
...ect() let o = new object(undefined) let o = new object(null) using object to create boolean objects the following examples store boolean objects in o: // equivalent to o = new boolean(true) let o = new object(true) // equivalent to o = new boolean(false) let o = new object(boolean()) object prototypes when altering the behavior of existing object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic.
... for example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.
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.
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.
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).
... 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.
unescape() - JavaScript
… … programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code.
...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 to be decoded.
Object initializer - JavaScript
the following code creates an object with three properties and the keys are "foo", "age" and "baz".
...oftentimes, there are variables in your code that you would like to put into an object.
... you will see code like this: let a = 'foo', b = 42, c = {}; let o = { a: a, b: b, c: c } with ecmascript 2015, there is 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.
Operator precedence - JavaScript
observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.
... code output function echo(name, num) { console.log("evaluating the " + name + " side"); return num; } // notice the division operator (/) console.log(echo("left", 6) / echo("right", 2)); evaluating the left side evaluating the right side 3 function echo(name, num) { console.log("evaluating the " + name + " side"); return num; } // not...
... code output function echo(name, num) { console.log("evaluating the " + name + " side"); return num; } // notice the division operator (/) console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3)); evaluating the left side evaluating the middle side evaluating the right side 1 function echo(name, num) { console.log("evaluating th...
...g the right side 512 function echo(name, num) { console.log("evaluating the " + name + " side"); return num; } // notice the parentheses around the left and middle exponentiation console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2)); evaluating the left side evaluating the middle side evaluating the right side 64 looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative.
JavaScript shells - JavaScript
a javascript shell allows you to quickly test snippets of javascript code without having to reload a web page.
... they are extremely useful for developing and debugging code.
... es6console.com - an open-source javascript console to test ecmascript 2015 code inside the browser.
... execute js - (no longer maintained) - firefox-extension which provides an enhanced javascript-console, where you can comfortably enter and execute arbitrary javascript-code and modify functions.
Privacy, permissions, and information security
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.
...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.
...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.
... <-- diagram and/or code snippet to clarify things--> ...
Add to Home screen - Progressive web apps (PWAs)
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 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.
... note: the code for this section was mostly taken from app install banners/add to home screen by pete lepage.
u1 - SVG: Scalable Vector Graphics
WebSVGAttributeu1
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.
... 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.
u2 - SVG: Scalable Vector Graphics
WebSVGAttributeu2
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.
... 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.
SVG fonts - SVG: Scalable Vector Graphics
mily="super sans" font-weight="bold" 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="300"><!-- outline of exclam.
...glyph --></glyph> <glyph unicode="@"><!-- outline of @ glyph --></glyph> <!-- more glyphs --> </font> we start with the <font> element.
...the most important attribute is unicode.
... it defines the unicode codepoint represented by this glyph.
Subresource Integrity - Web security
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 base64-encoded hash.
... 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.
...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.
Web security
even simple bugs in your code can result in private information being leaked, and bad people are out there trying to find ways to steal data.
... the web security-oriented articles listed here provide information that may help you secure your site and its code from attacks and data theft.
... 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.
... 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.
Using shadow DOM - Web Components
an important aspect of web components is encapsulation — being able to keep the markup structure, style, and behavior hidden and separate from other code on the page so that different parts do not clash, and the code can be kept nice and clean.
...the difference is that none of the code inside a shadow dom can affect anything outside it, allowing for handy encapsulation.
...ld(style); shadow.appendchild(wrapper); wrapper.appendchild(icon); wrapper.appendchild(info); using our custom element once the class is defined, using the element is as simple as defining it, and putting it on the page, as explained in using custom elements: // define the new element customelements.define('popup-info', popupinfo); <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."> internal versus 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 example, take a look at this code from our popup-info-box-external-stylesheet example (see the source code): // apply external styles to the shadow dom const linkelem = document.createelement('link'); linkelem.setattribute('rel', 'stylesheet'); linkelem.setattribute('href', 'style.css'); // attach the created element to the shadow dom shadow.appendchild(linkelem); note that <link> elements do not block paint of the shadow root, so there may be a flash of unstyled content (fouc) while the stylesheet loads.
Caching compiled WebAssembly modules - WebAssembly
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.
...if the wasm module code is updated, or its url changes, you will need to update dbversion.
...url, for next time we want to use it: errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(fetch(url)).then(results => { storeindatabase(db, results.module); return results.instance; }); }) }, note: it is for this kind of usage that webassembly.instantiate() returns both a module and an instance: the module represents the compiled code and can be stored/retrieved in idb or shared between workers via postmessage(); the instance is stateful and contains the callable javascript functions, therefore it cannot be stored/shared.
... 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).
2015 MDN Fellowship Program - Archive of obsolete content
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.
...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.
Testing the Add-on SDK - Archive of obsolete content
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.
... 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.
Working with Events - Archive of obsolete content
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.
... 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.
... 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.
context-menu - Archive of obsolete content
this makes your code easier to maintain, secure, debug and review.
...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.
...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.
self - Archive of obsolete content
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.
...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.
...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.
system - Archive of obsolete content
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.
... var system = require("sdk/system"); system.exit(); parameters code : integer to exit with failure, set this to 1.
core/heritage - Archive of obsolete content
reading or writing such code requires sharp eye and lot's of discipline, mainly due to code fragmentation and lots of machinery being exposed: // defining a simple class function dog(name) { // classes are for creating instances, calling them without `new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate.
...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.
...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.
core/promise - Archive of obsolete content
it makes code easier to read and make changes later: var data = readasync(url).
...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.
net/xhr - Archive of obsolete content
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.
... 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.
remote/child - Archive of obsolete content
usage the sdk/remote/parent module enables sdk code to load modules into child processes.
... 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.
... properties port an event emitter that can be used to send and receive frame specific events to and from code in the main process.
cfx - Archive of obsolete content
cfx test will include a module called "test-mycode.js", but will exclude modules called "test_mycode.js" or "testmycode.js".
... cfx testex this will test all available example code.
...the object encoded by the json becomes the staticargs property of the system module.
Add a Context Menu Item - Archive of obsolete content
when it's clicked, the selection is sent to the main add-on code, which just logs it: var contextmenu = require("sdk/context-menu"); var menuitem = contextmenu.item({ label: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostring();' + ' self.postmessage(text);' + '});', onmessage: function (selectiontext) { console.log(selectiontext); } }); try it: run the ...
... onmessage the onmessage property provides a way for the add-on code to respond to messages from the script attached to the context menu item.
... so: the user clicks the item the content script's click event fires, and the content script retrieves the selected text and sends a message to the add-on the add-on's message event fires, and the add-on code's handler function is passed the selected text, which it logs more options adding an image you can add an image to a context menu item with the image option.
Getting Started (jpm) - Archive of obsolete content
implementing the add-on now you can write the add-on's code.
...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("http://www.mozilla.org/"); } note that "entry point" defaults to "index.js" in jpm, meaning that your main file is "index.js", and it is found directly in your add-on's root.
... the add-on code itself uses two sdk modules, action button and tabs.
Modifying Web Pages Based on URL - Archive of obsolete content
a simple code snippet where content script is supplied as contentscript option and url pattern is given as include option is as follows: // import the page-mod api var pagemod = require("sdk/page-mod"); // create a page-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.inner...
... 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.
...this makes the code easier to maintain, debug, and review.
Bootstrapped extensions - Archive of obsolete content
some code samples are provided.
... 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.
Progress Listeners - Archive of obsolete content
note that if you just want to execute your code each time a page loads, you can use an an easier method, onpageload().
...elated documentation onprogresschange: function(awebprogress, arequest, curself, maxself, curtot, maxtot) {}, onstatuschange: function(awebprogress, arequest, astatus, amessage) {}, onsecuritychange: function(awebprogress, arequest, astate) {} } attach the progress listener to a <browser> or a <tabbrowser> element using addprogresslistener, for example for firefox put the following code in a load listener of a main window: gbrowser.addprogresslistener(mylistener); when used with a browser, the second argument is a mask which determines the type of events that will be received.
...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.
Common Pitfalls - Archive of obsolete content
there are some common pitfalls that should be avoided when writing either extensions or core mozilla code.
... these are the sort of things that super-review should be catching for code that goes into the tree; avoiding these to start with saves super-reviewers a lot of effort.
...or some applications } c++: nsresult rv; nscomptr<nsiioservice> ioserv = do_getservice("@mozilla.org/network/io-service;1"); ns_ensure_success(rv, rv); nscomptr<nsiuri> uriobj; rv = ioserv->newuri(uristring, uricharset, baseuri, getter_addrefs(uriobj)); if (ns_failed(rv)) { // may want to handle ns_error_malformed_uri for // some applications return rv; } or, if the code can include nsnetutil.h: nscomptr<nsiuri> uriobj; nsresult rv = ns_newuri(getter_addrefs(uriobj), uristring, uricharset, baseuri); in all cases the baseuri can be null if the uristring should be treated as an absolute uri and uricharset can be null if there is no clear origin charset for the string (e.g.
Extension Versioning, Update and Compatibility - Archive of obsolete content
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.
... 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.
...the resultant data is der encoded then base 64 encoded for inclusion in the update.rdf as an signature entry.
Listening to events in Firefox extensions - Archive of obsolete content
simple dom events registering for a dom event is done using with code such as the following: function callback(evt) { // do your processing here.
...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.
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
« previousnext » this document was authored by hiroshi shimoda of clear code inc.
... 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.
... 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.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
we now have code that adds one or more buttons to the toolbar palette.
...in order to add your button to the main toolbar on first run, you'll have to use javascript code.
...the toolbar code snippets page has a code sample you can use to do this.
The Box Model - Archive of obsolete content
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.
...the latter are recommended to keep style code in the skin section of the chrome.
Overlay extensions - Archive of obsolete content
this page contains links to documentation for the approach to developing extensions for gecko-based applications which uses: xul overlays to specify the interface apis available to privileged code, such as tabbrowser and javascript modules, to interact with the application and content.
... code snippets sample code for many of the things you'll want to do.
... javascript code modules javascript modules available to extension developers.
Performance best practices in extensions - Archive of obsolete content
use javascript code modules you can create your own javascript code modules incorporating sets of features that are only needed under specific circumstances.
...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.
Updating addons broken by private browsing changes - Archive of obsolete content
if your code refers to any of the following interfaces: ff 15: nsidomstoragemanager ff 16: nsitransferable ff 18: imgicache moziasyncfavicons nsifaviconservice nsiwebbrowserpersist ff 19: nsicontentprefservice nsidownloadmanager nsidownload nsihttpauthmanager nsistricttransportsecurityservice ff 20: nsiprivatebrowsingservice nsirecentbadcertservice furthermore, if your code uses any of these common chrome apis: ff 19: saveurl saveinternal openlinkin ff 20: openbrowserwindow gprivatebrowsingui finally, if y...
...our code watches for any of these observer notifications: private-browsing private-browsing-cancel-vote private-browsing-change-granted private-browsing-transition-complete then your addon will require updating to correctly support the new per-window private browser feature in firefox 20 (and will require updating to work correctly in releases of firefox since the ones listed).
...if your code depends on this interface, it will break.
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
i've been manually writing sample code for my own design prototypes for 4 or 5 years now.
...fortunately, our chief engineer was able to write some code that scraped through the database looking for errors like this which would invalidate our markup.
... while conversion to xhtml and css definitely shaved off development time that would have normally been spent manipulating the code, it didn't come entirely easy or without cost.
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
get the source you need cvs to get the source code.
...you can also see the code online.
...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.
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...
...le_dir}/testprofile" next, start firefox to populate the new profile directory with the rest of the default settings firefox-bin -p testprofile -chrome chrome://tests/content/quit.xul<code> the above process may exit before the profile is completely created.
... in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see 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); ...
Creating a Firefox sidebar extension - Archive of obsolete content
an extension package usually contains a "content" provider, which contains the xul code and application logic.
...see code_snippets/sidebar for more information.
... 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.
Getting Started - Archive of obsolete content
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.
...on every line that references <code>classic.jar we need to make some changes (there are about 5 lines).
...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.
DTrace - Archive of obsolete content
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).
... 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.
Dehydra Function Reference - Archive of obsolete content
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.
... optional: code is an integer parameter that allows warnings to be enabled(-wfoo) and disabled(-wno-) on the gcc commandline.
...it is not possible to define new warnings in dehydra, thus one has to figure out a warning code from an existing warning and hijack it for ulterior purposes.
Style System Overview - Archive of obsolete content
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).
...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).
...code should be merged.
GRE - Archive of obsolete content
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.
...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.
Introducing the Audio API extension - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
...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 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.
popChallengeResponse - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
... resultstring = crypto.popchallengeresponse("challengestring"); argument description "challengestring" a base-64 encoded cmmf popodeckeychallcontent message.
... 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.
Modularization techniques - Archive of obsolete content
introduction the purpose of this document is provide all the information you need to create a new mozilla module or break existing code into a module.
...this sample code should be updated to reflect this, but it gives you a good basic understanding of com from the c++ perspective.
...if your dll contains multiple factories, you'll need to add conditional code to determine which one to return.
Build - Archive of obsolete content
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.
Prism - Archive of obsolete content
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.
... firefox extension: a firefox extension, code-named "refractor", can be used to spin out new prism apps from inside the web browser.
... community blog posts prism forum #prism on irc.mozilla.org goodies bundle library contributing source code in svn bugzilla (for bugs and suggestions) open bugs, enter new bug build documentation related topics xulrunner ...
Remotely debugging Firefox for Metro - Archive of obsolete content
this article explains how to use remote debugging to inspect and code running in the new windows 8 ("metro-style") firefox app, using the developer tools in firefox on the desktop.
... 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 choose this option if you want to debug the browser's own code.
Abc Assembler Tests - Archive of obsolete content
the assembler code can be found in /utils/abcasm.
... * * the original code is [open source virtual machine.].
... * * the initial developer of the original code is * adobe system incorporated.
Tamarin - Archive of obsolete content
tamarin acceptance testing instructions on how to validate changes to the tamarin source code.
... nanojit lir in nanojit, lir is the source language for compilation to machine code.
...this page is a how-to about the changes, and what can be done to adapt source code to the changes.
Venkman - Archive of obsolete content
venkman is the code name for mozilla's javascript debugger.
... venkman internals notes on venkman source code.
... 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...
execute - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
...your code must call the performinstall method to actually execute the file.
initInstall - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
...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"); ...
patch - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
...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.
performInstall - Archive of obsolete content
returns an integer error code.
... for a list of possible values, 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"); ...
resetError - Archive of obsolete content
reseterror resets a saved error code to zero.
...description the reseterror method resets any saved error code to zero.
...example to reset the last error code to zero: reseterror(); ...
Learn XPI Installer Scripting by Example - Archive of obsolete content
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...
... the actual install code used to execute the installation appears in theinstall.js file as follows: if (err==success) { err = performinstall(); logcomment("performinstall() 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 ...
...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.
reserved - Archive of obsolete content
setting this attribute to "true" indicates that the command is reserved for chrome code and is not available for use in the content.
... example here, the command to open a new browser window is reserved: <command id="cmd_newnavigator" oncommand="openbrowserwindow()" reserved="true"/> if the keyboard shortcut for that is accel-t, then this code will not work as expected, as compared to when it is run from web content: document.addeventlistener("keydown", handlekey, true); function handlekey(event) { // listen for the "new tab" shortcut if (event.metakey && (event.key == "t")) { // log a message console.log("intercepted accel-t"); // prevent the default browser action event.preventdefault(); event.stop...
...propagation(); } } currently, this event handler as coded above runs and logs the message, but the default behavior persists.
Writing to Files - Archive of obsolete content
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.
...when writing text files, characters are writing using a chosen character set, encoded automatically.
...the difference is handled internally so you don't need to write any other part of the code differently.
Providing Command-Line Options - Archive of obsolete content
see also: xulrunner:commandline overview the code below is an example of writing a javascript xpcom component to handle command line parameters.
... using the example to use this sample code, save the commandline.js file into the components directory and add the following lines to your chrome.manifest file: component {2991c315-b871-42cd-b33f-bfee4fcbf682} components/commandline.js contract @mozilla.org/commandlinehandler/general-startup;1?type=myapp {2991c315-b871-42cd-b33f-bfee4fcbf682} category command-line-handler m-myapp @mozilla.org/commandlinehandler/general-startup;1?type=mya...
...pp the javascript code const cc = components.classes; const ci = components.interfaces; components.utils.import("resource://gre/modules/xpcomutils.jsm"); components.utils.import("resource://gre/modules/services.jsm"); // changeme: to the chrome uri of your extension or application const chrome_uri = "chrome://myapp/content/"; /** * utility functions */ /** * opens a chrome window.
Filtering - Archive of obsolete content
the code is fairly straightforward.
...in this example, the menulist is hard-coded to contain the items that we know are in the datasource.
...in the previous example, we hard-coded a menulist with the list of countries, but we could also generate this list from the datasource.
Special Condition Tests - Archive of obsolete content
the code above accomplishes the same effect except that it using the parent matching mechanism.
...the end effect is the same output, however, the source code is simpler.
....xulplanet.com/rdf/myneighbourhood"> <template> <rule iscontainer="true"> <menupopup> <menu uri="rdf:*" label="rdf:http://purl.org/dc/elements/1.1/title"/> </menupopup> </rule> <rule> <menupopup> <menuitem uri="rdf:*" label="rdf:http://www.xulplanet.com/rdf/address"/> </menupopup> </rule> </template> </button> the only difference in the code in this example is that the order of the rules has been switched around, the condition check for house has been removed and the iscontainer attribute has been added.
Template Builder Interface - Archive of obsolete content
both types of builder share much of the same code except for how they generate output to be displayed.
...the builder is accessible to unprivileged code, so the rebuild and refresh methods may be called by remote code.
...the composite datasource can only be accessed from privileged code, regardless of what datasources it contains.
Tree Widget Changes - Archive of obsolete content
the column objects are created automatically, so you don't have to write any extra code.
...array syntax to get a column: tree.columns["lastname"]; tree.columns[5]; once you have a column, you can get various properties of it: column.index - the index of the column in displayed order column.id - the id attribute of the column column.element - the treecol element column.x - the x position in the tree of the left edge of the column column.width - the width of the column in c++ code, you can also get the atom attribute of nsitreecolumn which returns an nsiatom for the column, making it fast to do comparisons.
... 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.
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
<handlers> <handler event="keypress" key=" " action="this.checked=!checked"/> </handlers> you can also use the keycode attribute to check for non-printable keys.
...the following alternate syntax can be used when the code in a handler is more complex: <binding id="binding-name"> <handlers> <handler event="event-name"> -- handler code goes here -- </handler> </handlers> </binding> handlers example the following example adds some key handlers to create a very primitive local clipboard: example 1 : source <binding id="clipbox"> <content> <xul:textbox/> </content> <implementation> <fie...
...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.
Adding Properties to XBL-defined Elements - Archive of obsolete content
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.
...onget attribute and onset attribute you can use the onget and onset attributes to have code execute when the property is retrieved or modified.
...this is done in the code inside the setter element.
Additional Install Features - Archive of obsolete content
the following code will make a copy of the file "/bin/grep" and put it in the directory "/main".
...otherwise, the number will be an error code which indicates the type of error that occured.
...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.
Creating Dialogs - Archive of obsolete content
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.
...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.
...y are fruity"/> <radio id="violet" selected="true" label="strawberries because of their colour"/> <radio id="yellow" label="bananas because they are pre-packaged"/> </groupbox> </dialog> the buttons elements can be accessed with the following javascript // the accept button var acceptbutt = document.documentelement.getbutton("accept") more examples more examples in dialogs and prompts (code snippets).
Manifest Files - Archive of obsolete content
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.
...in javascript, it is possible for a web page to override built-in functions with their own code.
...the codebase there has not yet adopted the "manifest" format.
More Wizards - Archive of obsolete content
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.
... wizard example source <?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(); return true;"> <label value="enter the secret code:"/> <textbox id="secretcode" onkeyup="checkcode();"/> </wizardpage> <wizardpage> <label value="that is the correct secret code."/> </wizardpage> </wizard> there is also a...
Tree Box Objects - Archive of obsolete content
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.
...if you are writing code for multiple versions, you should check for this as above.
...in fact, this is what the underlying tree code does when the user double clicks the twisty.
XBL Example - Archive of obsolete content
let's break down the code piece by piece.
...we use similar code as to the method above to set the page number.
... the final code the final code is as follows: example 2 : source <binding id="slideshow"> <content> <xul:vbox flex="1"> <xul:deck xbl:inherits="selectedindex" selectedindex="0" flex="1"> <children/> </xul:deck> <xul:hbox> <xul:button xbl:inherits="label=previoustext" oncommand="parentnode.parentnode.parentnode.page--;"/> <xul:description flex...
XBL Inheritance - Archive of obsolete content
one way to create this is to duplicate the existing xbl code for buttons.
... however, it would be better to simply extend the existing button code.
...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.
tabs - Archive of obsolete content
ArchiveMozillaXULtabs
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.
toolbarbutton - Archive of obsolete content
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.
...this is reverse of the order in which they appear in the xul code.
... oncommand type: script code this event handler is called when the command is activated.
XULRunner 1.9.1 Release Notes - Archive of obsolete content
xulrunner 1.9.1.x is built from the same source code snapshot as firefox 3.5.x.
... because nobody has written that code yet!
... where is the source code?
XULRunner 1.9.2 Release Notes - Archive of obsolete content
xulrunner 1.9.2.x is built from the same source code snapshot as firefox 3.6.x.
...because nobody has written that code yet!
...where is the source code?
XULRunner 1.9 Release Notes - Archive of obsolete content
xulrunner 1.9 is built from the same source code snapshot as firefox 3.
... because nobody has written that code yet!
... where is the source code?
XULRunner 2.0 Release Notes - Archive of obsolete content
xulrunner 2.0.x is built from the same source code snapshot as firefox 4.0.x.
...because nobody has written that code yet!
...where is the source code?
Debugging a XULRunner Application - Archive of obsolete content
add the following code to your xul app: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); // don't specify a window type parameter below if "navigator:browser" // is suitable for your app.
... debuggerserver.addbrowseractors("myxulrunnerappwindowtype"); } debuggerserver.openlistener(6000); for xulrunner version 37+ the code to enable the debugger has changed: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); debuggerserver.addbrowseractors(); debuggerserver.allowchromeprocess = true; } let dbglistener=debuggerserver.createlistener(); dbglistener.portorpath=6000; dbglistener.open(); add the following to your prefs.js: (in recent ffox, edit about:config instead) pref("devtools.debugger.remote-enabled", true); in firefox, go to tools > web developer > connect...
... 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...
MacFAQ - Archive of obsolete content
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.
... taking advantage of the core code "openurl" from "nscommandlineservicemac.cpp", you'll see that it looks for "browser.chromeurl" before defaulting to navigator.xul, and this is called when an xulrunner app is already running, so: create a default preference of "browser.chromeurl" that points to your new "hiddenwindow" as such: "chrome://myxul/content/hiddenwindow.xul" next take the code below and drop it in, to create the hiddenwindow.xul (note: the debug function and nsicommandline try/catch can be removed, all you need is the window.arguments[0]) <?xml version="1.0"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="myxul_hidden" windowtype="myxul:hiddenwindow" title="" width="0" height="0" persist="screenx screeny width height...
Make your xulrunner app match the system locale - Archive of obsolete content
the first step is to get the code we're about to write to run before any of the locale specific resources are loaded.
...the code described lives in the pybridge component's onstartup method which gets called automatically.
...the following is python code to set this preference.
2006-11-17 - Archive of obsolete content
there are also some perl code provided in this link.
... how to access xyz.properties items more detail and code examples are provided in the posting.
... code review requested for smtp swticher no comment is made.
Monitoring plugins - Archive of obsolete content
below are a number of javascript snippets that would be useful to developers trying to use this feature: registration to register for runtime notifications with the observer service you must create a class with an observe method which receives 3 parameters (subject, topic and data) as well as a register method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice (components.interfaces.nsiobserverservice); observerservice.addobserver(this, "experimental-notify-plugin-call", false); observing as discussed above, to specify what you want done when a notification arrives your class must have an observe method, receiving 3 parameters (sub...
... clean up to unregister your class with the observer service - when you no longer want to be listening to runtime notifications - your class must include an unregister method that contains the following code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "experimental-notify-plugin-call"); skeleton observer class below is a skeleton class that you may use to listen to runtime notifications: function pluginobserver() { this.registered = false...
...; //takes care of registering this class with observer services as an observer for plugin runtime notifications } pluginwatcherobserver.prototype = { observe: function(subject, topic, data) { if (topic == "experimental-notify-plugin-call") //in case your class is registered to listen to other topics //this gets executed each time a runtime notification arrives // --your code goes here-- } }, //takes care of registering the observer services for the "experimental-notify-plugin-call" topic register: function() { if (this.registered == false) { //this check prevents double registration -- something you want to avoid!!
NPN_GetValue - Archive of obsolete content
npnvdocumentorigin: the value for this variable is the unicode serialization of the origin converted to nfkc-encoded (normalized) utf-8.
... if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPN_RequestRead - Archive of obsolete content
if unsuccessful, the function returns an error code.
... for possible values, see error codes.
... 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.
NPN_SetValue - Archive of obsolete content
if unsuccessful, the function should return the most relevant npapi error code.
... for possible values, see error codes.
...the browser code reads this parameter as follows (nppvpluginwindowbool as an example): nperror np_export _setvalue(npp npp, nppvariable variable, void *value) { ...
NPN_Version - Archive of obsolete content
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.
... netscape_major pointer to the browser's major version; changes with major code release number.
... note: platform-specific code in the plug-in api files npwin.cpp, npmac.cpp, or npunix.c checks version numbers automatically.
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
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.
...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.
...as you may (or may not) recall, that file tells the application what xul code your extension's interface needs to overlay onto.
-ms-filter - Archive of obsolete content
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.
... code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_h.htm <img style="filter:progid:dximagetransform.microsoft.motionblur(strength=50) progid:dximagetransform.microsoft.basicimage(mirror=1)" src="/workshop/samples/author/dhtml/graphics/cone.jpg" height="80px" width="80px" alt="cone"> the following example shows how to use scripting to set the filter on an image.
... code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_s.htm <body> <p>click the image to start the filter.</p> // call the function.
Processing XML with E4X - Archive of obsolete content
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.
... 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 is no longer necessary, but remains in some legacy code.
ActiveXObject - Archive of obsolete content
for example, for the local intranet zone, you typically need to change a custom setting to "initialize and script activex controls not marked as safe for scripting." to identify members of 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.
Debug - Archive of obsolete content
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.
... 4 async operation status codes contant description value debug.ms_async_op_status_success the asynchronous operation was successful.
... debug.setnonusercodeexceptions determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled.
GetObject - Archive of obsolete content
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.
...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.
...once an object is activated, you reference it in code using the object variable you defined.
VBArray.dimensions - Archive of obsolete content
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.
...the third part is the javascript code that goes in the <body> section to run the other two parts.
VBArray.getItem - Archive of obsolete content
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.
...the third part is the javascript code that goes in the <body> section to run the other two parts.
VBArray.lbound - Archive of obsolete content
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.
...the third part is the javascript code that goes in the <body> section to run the other two parts.
VBArray.toArray - Archive of obsolete content
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.
...the third part is the javascript code that goes in the <body> section to run the other two parts.
VBArray.ubound - Archive of obsolete content
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.
...the third part is the javascript code that goes in the <body> section to run the other two parts.
VBArray - Archive of obsolete content
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.
...the third part is the javascript code that goes in the <body> section to run the other two parts.
ECMAScript 2015 support in Mozilla - Archive of obsolete content
code-named "es.next", "harmony", or "ecmascript 6", the first working draft (based on ecmascript 5.1) was published on july 12, 2011 as "es.next".
...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...
...ng.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 (firefox 50) typed arrays typed arrays are specified as part of ecmascript 2015 and no longer in their own specif...
LiveConnect - Archive of obsolete content
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.
...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).
JavaArray - Archive of obsolete content
summary core object a wrapped java array accessed from within javascript code is a member of the type javaarray.
...when the javaarray is passed back to java, the array is unwrapped and can be used by java code.
... var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); example: instantiating a javaarray in javascript with the newinstance method in javascript 1.4, you can use a javaclass object as the argument for the newinstance method which creates the array, as shown in the following code: var dogs = java.lang.reflect.array.newinstance(java.lang.string, 5); in javascript 1.1, use a class object returned by java.lang.class.forname as the argument for the newinstance method, as shown in the following code: var datatype = java.lang.class.forname("java.lang.string"); var dogs = java.lang.reflect.array.newinstance(datatype, 5); ...
JavaObject - Archive of obsolete content
summary core object the type of a wrapped java object accessed from within javascript code.
...when the javaobject is passed back to java, it is unwrapped and can be used by java code.
... examples example: instantiating a java object in javascript the following code creates the javaobject thestring, which is an instance of the class java.lang.string: var thestring = new packages.java.lang.string("hello, world"); because the string class is in the java package, you can also use the java synonym and omit the packages keyword when you instantiate the class: var thestring = new java.lang.string("hello, world"); example: accessing methods of a java object ...
Sharp variables in JavaScript - Archive of obsolete content
usage to create a sharp variable, simply assign an object to it in a line of code using an equal sign.
...you can use this to create objects in a single line of code that would otherwise take multiple lines of code.
... 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.
Reference - Archive of obsolete content
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.
...--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.
...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).
forEach - Archive of obsolete content
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.
... feel free to alter the text as english is not my mother tongue and i'm more concerned with the code quality that the english grammar ;-s dotnetcarpenter 30 june 2012 <hr> the compatibility section goes to extraordinary lengths in providing a foreach implementation.
... a much more sane approach would be to count on the implementation to throw errors if wrong arguments are provided and implement this in fewer lines of code.
Introduction to game development for the Web - Game development
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.
... 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.
... web workers workers give you the ability to spawn background threads running their own javascript code, to take advantage of modern, multi-core processors.
3D games on the Web - Game development
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 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.
... source code you can find all the source code for this series demos on github.
Desktop gamepad controls - Game development
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.
...this is pure javascript code however too, so can be used in any other project no matter what framework was used.
...here's the code we've prepared in the create() function that is executed once when the new state is created: create() { // ...
Implementing game control mechanisms - Game development
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 code however you want for learning purposes.
Square tilemaps implementation: Scrolling maps - Game development
in the demo code, the starting point is stored at startcol and startrow.
...y map.tsize, // source width map.tsize, // source height math.round(x), // target x math.round(y), // target y map.tsize, // target width map.tsize // target height ); } } } demo our scrolling tilemap implementation demo pulls the above code together to show what an implementation of this map looks like.
... you can take a look at a live demo, and see its source code.
Square tilemaps implementation: Static maps - Game development
for the sake of simplicity, in the example code a plain object has been used.
...drawimage( tileatlas, // image (tile - 1) * map.tsize, // source x 0, // source y map.tsize, // source width map.tsize, // source height c * map.tsize, // target x r * map.tsize, // target y map.tsize, // target width map.tsize // target height ); } } } demo our static tilemap implementation demo pulls the above code together to show what an implementation of this map looks like.
... you can see a live demo and grab the full source code.
Mouse controls - Game development
you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson9.html.
...add the following function to your code, below the previous line you added: function mousemovehandler(e) { var relativex = e.clientx - canvas.offsetleft; if(relativex > 0 && relativex < canvas.width) { paddlex = relativex - paddlewidth/2; } } in this function we first work out a relativex value, which is equal to the horizontal mouse position in the viewport (e.clientx) minus the distance between the left edge of ...
... 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.
Buttons - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson15.html.
... 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.
... 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.
Game over - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson08.html.
...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.
... 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.
Physics - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson05.html.
... final code check the latest code should look like this: var ball; function preload() { game.scale.scalemode = phaser.scalemanager.show_all; game.scale.pagealignhorizontally = true; game.scale.pagealignvertically = true; game.stage.backgroundcolor = '#eee'; game.load.image('ball', 'img/ball.png'); } function create() { game.physics.startsystem(phaser.physics.arcade); ball = ga...
... 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.
Randomizing gameplay - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson16.html.
...add this new line to your code now, and try it out.
... 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!
Scaling - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson02.html.
... 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.
...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.
Win the game - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson12.html.
... add the following new code into your ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); var count_alive = 0; for (i = 0; i < bricks.children.length; i++) { if (bricks.children[i].alive == true) { count_alive++; } } 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.
... 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.
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript, boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops).
... below is some javascript pseudocode (it's not truly executable code) demonstrating this concept.
... /* javascript if statement */ if (boolean conditional) { // code to execute if the conditional is true } if (boolean conditional) { console.log("boolean conditional resolved to true"); } else { console.log("boolean conditional resolved to false"); } /* javascript for loop */ for (control variable; boolean conditional; counter) { // code to execute repeatedly if the conditional is true } for (var i=0; i < 4; i++) { 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.
Entity - MDN Web Docs Glossary: Definitions of Web-related terms
entities are frequently used to display reserved characters (which would otherwise be interpreted as html code), and invisible characters (like non-breaking spaces).
...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.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Identifier - MDN Web Docs Glossary: Definitions of Web-related terms
an identifier is a sequence of characters in the code that identifies a variable, function, or property.
... in javascript, identifiers are case-sensitive and can contain unicode letters, $, _, and digits (0-9), but 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.
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
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.
... error detection and correction error detection and correction are codes that are used to detect and apply corrections to the errors that occur when data is transmitted to the receiver.
...forward error correction is when the receiver uses the error-correcting code which automatically corrects the errors at the transmitter, the calculation is performed before the packet is sent.
Character set - MDN Web Docs Glossary: Definitions of Web-related terms
in earlier times, countries developed their own character sets due to their different languages used, such as kanji jis codes (e.g.
...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.
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.
...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 + depending on the context, the character ' ' is translated to a '+' (like in the percent-encoding version used in an application/x-www-form-urlencoded message), or in '%20' like on urls.
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 ...
CSS and JavaScript accessibility best practices - Learn web development
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).
...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.
Mobile accessibility - Learn web development
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.
...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.
...this occurs because we are using code such as the following: div.onmousedown = function() { initialboxx = div.offsetleft; initialboxy = div.offsettop; movepanel(); } document.onmouseup = stopmove; to enable other forms of control, you need to use different, yet equivalent events — for example, touch events work on touchscreen devices: div.ontouchstart = function(e) { initialboxx = div.offsetleft; initialboxy = div.off...
Backgrounds and borders - Learn web development
you can create a gradient then copy and paste out the source code that generates it.
...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.
... 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).
Creating fancy letterheaded paper - Learn web development
save local copies of the top, bottom and logo images in the same directory as your code files.
... 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.
...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.
CSS values and units - Learn web development
hexadecimal rgb values the next type of color value you are likely to encounter is hexadecimal codes.
...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.
...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.
Beginner's guide to media queries - Learn web development
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.
... add the below code into the bottom of your step1.html css.
... again, add the below code into the bottom of your step1.html css.
Using your new knowledge - Learn web development
alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks.
... 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.
...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.
Styling links - Learn web development
playable code <div class="body-wrapper" style="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 10px 0 0;"> <input id="solution" type="button" value="show solution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlinput = document.queryselector(".html-input"); var cssinput = document.queryselector(".css-input"); var reset = document.getelementbyid("reset"); var htmlcode = htmlinput.value; var csscode = cssinput.value; var output = document.query...
...selector(".output"); var solution = document.getelementbyid("solution"); var styleelem = document.createelement('style'); var headelem = document.queryselector('head'); headelem.appendchild(styleelem); function drawoutput() { output.innerhtml = htmlinput.value; styleelem.textcontent = cssinput.value; } reset.addeventlistener("click", function() { htmlinput.value = htmlcode; cssinput.value = csscode; drawoutput(); }); solution.addeventlistener("click", function() { htmlinput.value = htmlcode; cssinput.value = 'p {\n font-size: 1.2rem;\n font-family: sans-serif;\n line-height: 1.4;\n}\n\na {\n outline: none;\n text-decoration: none;\n padding: 2px 1px 0;\n}\n\na:link {\n color: #265301;\n}\n\na:visited {\n color: #437a16;\n}\n\na:focus {\n border-bottom: 1px solid;\n ...
Typesetting a community school homepage - Learn web development
use a suitable service to generate bulletproof @font-face code for these two fonts.
... 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.
...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.
The HTML5 input types - Learn web development
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).
...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.
... let's look at the code behind the above example, so you can see how its done.
Styling web forms - Learn web development
text" id="name" name="user_name"> </div> <div id="reply"> <label for="mail">reply:</label> <input type="email" id="mail" name="user_email"> </div> <div id="message"> <label for="msg">your message:</label> <textarea id="msg" name="user_message"></textarea> </div> <div class="button"> <button type="submit">send your message</button> </div> </form> add the above code into the body of your html.
...add all the code blocks shown below inside the <style> element, one after another.
...your form should now look like this: note: if your example does not work quite like you expected and you want to check it against our version, you can find it on github — see it running live (also see the source code).
Use JavaScript within a webpage - Learn web development
in this article we're going over the html code you need to make javascript take effect.
...to call javascript code from within html, you need the <script> element.
...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.
Creating hyperlinks - Learn web development
active learning: creating your own example link create an html document using your local code editor and our getting started template.
... for a start, it's easier to scan your code — relative urls are generally shorter than absolute urls, which makes reading code much easier.
... 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.
Marking up a letter - Learn web development
create a new .html file using your text editor or use an online tool such as codepen, jsfiddle, or glitch to complete the tasks.
... 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.
...it's very hard to help someone with a coding problem without seeing their code.
Structuring a page of content - Learn web development
create the example on your local computer, or alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks.
... 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.
...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.
Introduction to HTML - Learn web development
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.
...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.
... 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?
Mozilla splash page - Learn web development
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.
... 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.
...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.
HTML table basics - Learn web development
LearnHTMLTablesBasics
this can result in the code being harder to write, maintain, and debug.
...first the source code: <table> <tr> <td>&nbsp;</td> <td>knocky</td> <td>flor</td> <td>ella</td> <td>juan</td> </tr> <tr> <td>breed</td> <td>jack russell</td> <td>poodle</td> <td>streetdog</td> <td>cocker spaniel</td> </tr> <tr> <td>age</td> <td>16</td> <td>9</td> <td>10</td> <td>5</td> </tr> <tr> <td>owner</td> <td>mother-in-law</td> ...
... save and open your code in a browser to see the improvement.
Assessment: Structuring planet data - Learn web development
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.
... 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.
...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.
Measuring performance - Learn web development
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.
... 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.
React interactivity: Editing, filtering, conditional rendering - Learn web development
copy this block of code into the todo() function, beneath your usestate() hook but above the return statement: const editingtemplate = ( <form classname="stack-small"> <div classname="form-group"> <label classname="todo-label" htmlfor={props.id}> new name for {props.name} </label> <input id={props.id} classname="todo-text" type="text" /> </div> <div classname="btn-group"> <...
...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!
... 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.
Creating our first Vue component - Learn web development
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.
...open the file in your code editor.
...however, we can currently only add one todolist component to the page because the id is hardcoded.
Getting started with Vue - Learn web development
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.
...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.
Focus management with Vue refs - Learn web development
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.
...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.
... 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.
Vue resources - Learn web development
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.
Application cache implementation overview
when aentrystatus is a success code, entry has been found and we are loading it from the cache.
...when aentrystatus is a failure code, entry has not been found, but the url is falling under one of the network or fallback namespaces.
...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.
Browser chrome tests
it currently allows you to run javascript code in the same scope as the main firefox browser window and report results using the same functions as the mochitest test framework.
... writing browser chrome tests browser chrome tests are snippets of javascript code that run in the browser window's global scope.
...you should attempt to reduce the side effects of the testing code and "clean up" after yourself, to avoid influencing other tests.
What to do and what not to do in Bugzilla
resolving bugs as fixed resolve a bug as fixed if the bug has been fixed by a checkin into the mozilla mercurial code repository.
...remote execution of arbitrary code) get the critical severity.
... 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.
Creating reftest-based unit tests
to run all the reftests, go to the directory where you save firefox's source code and run: ./mach reftest if you want to run a particular set of reftests, pass the path as an argument: ./mach reftest path/from/sourcedir/reftest.list and to run a single reftest just pass the path to the test file (not the reference file): ./mach reftest path/from/sourcedir/reftest-name.html there is no reftest equivalent to mach mochitest --keep-open, but temporarily adding the reftest-...
...create a directory (inside firefox's source code tree) and make that your current directory (i.e.
...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 with the following: == foo.html bar.html you are now ready to run the test (but first you must go back to the root of firefox's source code tree): $ ./mach reftest path/to/reftest.list 2>&1 | grep reftest reftest pass: file:///users/ray/mozilla-central/path/to/foo.html $ congratulations!
Debugging OpenGL
for various reasons, debugging opengl related code can be tricky.
... this article provides suggestions for how to improve your efficiency while debugging opengl code in gecko.
...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.
Debugging Table Reflow
reflow the most efficient tool to claim that html-table code is the victim and not the source of layout bugs is a frame reflow debug log.
... the table layout strategy can be visualized by defining in the makefiles the constant debug_table_strategy.if one takes for instance the following table code: <table border width="300"> <colgroup> <col> <col width="50%"> <col width="1*"> <col> </colgroup> <tr> <td style="width:80px">cell 1</td> <td>cell 2</td> <td>cell 3</td> <td>cell 4</td> </tr> </table> rendering: <colgroup><col><col width="50%"><col width="1*"><col></colgroup>cell 1cell 2cell 3cell 4 it will produce the following log at the entrance of assignnonpctcolwidths:...
...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.
Makefiles - Best practices and suggestions
hardcoded values - avoid them like the plague.
... 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.
Experimental features in Firefox
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.
...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.
...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).
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.
... 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.
Multiprocess Firefox
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.
Chrome-only API reference
MozillaGeckoChromeAPI
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.
...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.
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.
Overview of Mozilla embedding APIs
nsstring there are a collection of string classes which support both unicode and ascii strings.
...public return codes ns_succeeded ns_error_failure ns_error_not_implemented public functions the following functions are available from the xpcom dll.
... 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...
Getting from Content to Layout
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.
Getting Started with Chat
if you have something long to post, a code snippet for example, use paste.mozilla.org and paste the generated url in irc instead.
...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.
Hacking with Bonsai
the original navigator code base had large sections that were shared across multiple platforms.
... many times, code checked in would compile or run on a handful of platforms.
...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.
How to Report a Hung Firefox
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.
...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.
DeferredTask.jsm
the deferredtask.jsm javascript code module offers utility routines for a task that will run after a delay.
...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.
...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.
FileUtils.jsm
the fileutils.jsm javascript code module offers utility routines dealing with files.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/fileutils.jsm"); the file constructor if you have a path to a file (or directory) you want to obtain an nsifile for, you can do so using the file constructor, like this: var f = new fileutils.file(mypath); method overview nsifile getfile(string key, array patharray, bool followlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool followlinks); nsifileoutputstream openfileoutputstream(nsifile file, int modeflags); nsifileoutputstream openatomicfileoutputstream(nsifile file, int modeflags); nsifileoutputstream opensafefileoutputstream(nsifile file, int modeflags); void closeatomicfileou...
... see also nsifileoutputstream code snippets and examples ...
OSFile.jsm
os.file is a new api designed for efficient, off-main thread, manipulation of files by privileged javascript code.
... this api is intended to replace, in time, most xpcom-based manipulation of files (nsifile, subsets of nsiioservice, etc.) by javascript code.
...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.
Promise.jsm
the promise.jsm javascript code module implements the promises/a+ proposal as known in april 2013.
...its usage is not suggested for new code.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promise.jsm"); note: a preliminary promise module is also available starting from gecko 17, though it didn't conform to the promises/a+ proposal until gecko 25: components.utils.import("resource://gre/modules/commonjs/promise/core.js"); // gecko 17 to 20 components.utils.import("resource://gre/modules/commonjs/sdk/core/promise.js"); // gecko 21 to 24 this implementation also includes helper functions that are specific to the add-on sdk.
SourceMap.jsm
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.
... chunk: a string snippet of generated js code, another instance of sourcenode, or an array where each member is one of those things.
... chunk: a string snippet of generated js code, another instance of sourcenode, or an array where each member is one of those things.
WebChannel.jsm
the webchannel.jsm javascript code module provides an abstraction that uses the message manager and custom events apis to create a two-way communication channel between chrome and content code for specific origins (using a specific origin passed to the constructor or a lookup with nsipermissionmanager while also ensuring the scheme is https).
... examples setting up a webchannel between chrome code and a webpage chrome code let channel = new webchannel(webchannelid, services.io.newuri("https://mozilla.org", null, null)); // receive messages channel.listen(function (webchannelid, message, sendercontext) { // send messages channel.send({ data: { greeting: true } }, sendercontext); }); webpage code receive messages from an existing webchannel in content code window.addeventlist...
...ener("webchannelmessagetocontent", function(e) { // receive messages console.log(e.detail); }, true); send messages to an existing webchannel in chrome code window.dispatchevent(new window.customevent("webchannelmessagetochrome", { detail: { id: webchannelid, message: { something: true } } })); ...
Encodings for localization files
in general, files in the mozilla repositories are utf-8 encoded.
... installer the windows installer can’t handle utf-8, but only the codepages provided by windows.
... toolkit/installer/windows/install.it a windows codepage.
Localizing XLIFF files for iOS
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.
... in the <file> tag, add the target-language attribute with your locale code as the value (e.g., target-language="xx-xx").
...each <file> tag requires the target-language attribute with your locale code as the value (e.g., target-language="xx-xx").
Localizing with Koala
for the purposes of this tutorial, the locale code that we will use will be called "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...
...the .properties files are used in the javascript code while the application is already running.
Localizing with Mercurial
in mozilla, we use the the mercurial version control system (hg) to manage our source code and localizations.
...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 push to mozilla-hosted repositories, you have to have committer access, and you must edit the file (your-local-hg-root aka the directory you pulled your locale into)/.hg/hgrc (note, this is not your ~/.hgrc) to add these lines (replacing ab-cd with your locale code): [paths] default = https://hg.mozilla.org/l10n-central/ab-cd/ default-push = ssh://hg.mozilla.org/l10n-central/ab-cd/ you’ll also need to tell ssh which account to use for your pushes, too, by editing ~/.ssh/config and adding these lines, where user@host.domain is your account: host hg.mozilla.org user user@host.domain now you can push your work to the repository (and check the res...
Patching a Localization
get the source first, you need to get the source for the localization in question using its two or three character iso language code.
...whenever you see gl in blue text, replace it with the locale code for your language.
... 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.
Localization formats
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.
...ext has very powerful tools to update this site (if you use the actual english strings in msgids, not unique identifier strings like certificate_intro) very established with a large set of powerful tools harder to screw things up because existing tools will not allow localizers to edit the l10n file where they shouldn't separates localizable strings available for localizers for the rest of the code, protecting it from unintended changes disadvantage of gettext .po file needs to be compiled into a .mo file for localizer to see changes using regular diff to see changes to a file is sometimes impossible because the editing tool can save the .po file using a completely different structure or order of entities.
mozilla::MutexAutoLock
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.
...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.
mozilla::MutexAutoUnlock
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.
...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.
DMD
this is good for finding parts of the code that cause high heap churn, e.g.
... 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.
Leak-hunting strategies and tips
(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.
...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.
...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.
Memory Profiler
however, it still relies on developers' wisdom, and sometimes chances, to dig out the problematical code snippet.
...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.
TraceMalloc
tracemalloc has been superseded by dmd and removed from the codebase.
... this documentation is only relevant to older versions of the codebase that still contain it.
...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.
Phishing: a short definition
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.
Localization Use Cases
in all presented examples, we try to show the existing code, explain the problem from the localizers' or developers' perspective, and suggest a solution.
...the javascript code hasn't changed yet, but there's another improvement that can be introduced, which is described below.
... in the javascript code, the developer needs to pass sizeinfo.unit instead of a localized value: function showformatedsize(element, l10nid, size) { // … element.textcontent = document.l10n.get(l10nid, { size: sizeinfo.size, unit: sizeinfo.unit }); } and then use the $unit variable verbatim in the english message: <availablesize "{{ $size }} {{ $unit }} available"> in french, the localizer can then ...
MailNews automated testing
these tests are run against almost every changeset that gets committed to the thunderbird and seamonkey code bases.
... "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.
About NSPR
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.
...nspr20, an effort started in 1996, built on that original idea, though very little is left of the original code.
NSPR Error Handling
this chapter describes the functions for retrieving and setting errors and the error codes set by nspr.
... error type error functions error codes for information on naming conventions for nspr types, functions, and macros, see nspr naming conventions.
... error type prerrorcode error functions pr_seterror pr_seterrortext pr_geterror pr_getoserror pr_geterrortextlength pr_geterrortext error codes error codes defined in prerror.h: pr_out_of_memory_error insufficient memory to perform request.
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 does use pr_seterror to set error numbers defined in error codes.
NSS 3.12.5 release_notes
(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.
... additional documentation in pk11pub.h: the caller of pk11_derencodepublickey should free the returned secitem with a secitem_freeitem(..., pr_true) call.
...sutil.h bug 511227: firefox 3.0.13 fails to compile on freebsd/powerpc bug 511312: nss fails to load softoken, looking for sqlite3.dll bug 511781: add new tls 1.2 cipher suites implemented in windows 7 to ssltap bug 516101: if pk11_importcert fails, it leaves the certificate undiscoverable by cert_pkixverifycert bug 518443: pk11_importandreturnprivatekey leaks an arena bug 518446: pk11_derencodepublickey leaks a certsubjectpublickeyinfo bug 518457: seckey_encodedersubjectpublickeyinfo and pk11_derencodepublickey are duplicate bug 522510: add deprecated comments to key.h and pk11func.h bug 522580: nss uses port_memcmp for comparing secret data.
NSS 3.12.6 release notes
in ssl.h ssl_getimplementedciphers ssl_getnumimplementedciphers ssl_handshakenegotiatedextension new error codes in sslerr.h ssl_error_unsafe_negotiation ssl_error_rx_unexpected_uncompressed_record new types in sslt.h sslextensiontype new environment variables sqlite_for...
... note: the code must be built with trace defined to use this functionality.
... 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
new in nss 3.12.9 removed functions new ssl options new error codes bugs fixed the following bugs have been fixed in nss 3.12.9.
... bug 609068: implement j-pake in freebl bug 607058: crash [@ nss_cms_decoder_work_data] bug 613394: november/december 2010 batch of nss root ca changes bug 610843: need way to recover softoken in child after fork() bug 617492: add pk11_keygenwithtemplate function to pk11wrap (for firefox sync) bug 610162: sha-512 and sha-384 hashes are incorrect for inputs of 512mb or larger when running under windows and other 32-bit platforms (fx 3.6.12 and 4.0b6) bug 518551: vfychain crashes in pkits tests.
... bug 596798: win_rand.c (among others) uses unsafe _snwprintf bug 597622: do not use the sec_error_bad_info_access_location error code for bad crl distribution point urls bug 619268: memory leaks in cert_changecerttrust and cert_savesmimeprofile bug 585518: addtrust qualified ca root serial wrong in certdata.txt trust entry bug 337433: need cert_findcertbynicknameoremailaddrbyusage bug 592939: expired cas in certdata.txt documentation <for a="" class="new " documentation="" href="/en/index.html#documentation" list=...
NSS 3.14.1 release notes
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 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.
NSS 3.15 release notes
in xconst.h cert_encodenameconstraintsextension - matching function for cert_decodenameconstraintsextension, added in nss 3.10.
...please consider using secitem_reallocitemv2 in all future code.
... updated build instructions are available at migration to hg as part of this migration, the source code directory layout has been re-organized.
NSS 3.16.2 release notes
new intel aes assembly code for 32-bit and 64-bit windows, contributed by shay gueron and vlad krasnov of intel.
... 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.
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...
...8: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 websites and code signing trust bits (1024-bit root) cn = netlock expressz (class c) tanusitvanykiado sha1 fingerprint: e3:92:51:2f:0a:cf:f5:05:df:f6:de:06:7f:75:37:e1:65:ea:57:4b turned off websites and code signing trust bits (1024-bit root) bugs fixed in nss 3.16.3 this bugzilla query returns all the bugs fixed in nss 3.16.3: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&t...
NSS 3.23 release notes
this code is not ready for production use.
... the build time environment variable nss_disable_chachapoly was added, which can be used to prevent compilation of the chacha20/poly1305 code.
...an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.44 release notes
new in nss 3.44 new functionality new functions in lib/certdb/cert.h cert_getcertificateder - access the der-encoded form of a certcertificate.
... bugs fixed in nss 3.44 1501542 - implement checkarmsupport for android 1531244 - use __builtin_bswap64 in crypto_primitives.h 1533216 - cert_decodecertpackage() crash with netscape certificate sequences 1533616 - sdb_getattributevaluenolock should make at most one sql query, rather than one for each attribute 1531236 - provide accessor for certcertificate.dercert 1536734 - lib/freebl/crypto_primitives.c assumes a big endian machine 1532384 - in nss test certificates, use @example.com (not @bogus.com) 1538479 - post-handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11...
...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 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() returns error bug 1551041 - fix builds using gcc < 4.3 on big-endian architectures bug 1554659 - add versioning to openbsd builds to fix link time errors using nss bug 1553443 - send session ticket 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 m...
...arked 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://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.45 compatibility nss 3.45 shared libraries are backward compatible with all older nss 3.x shared libraries.
Hashing - sample 1
nss sample code 1: hashing.
... the nss same code below computes the hash of a file and saves it to another file, this illustrates the use of nss message apis.
... /* this source code form is subject to the terms of the mozilla public * license, v.
EncDecMAC using token object - sample 3
encdecmac using token object example: <h2 id="nss_sample_code_3_hashing.">nss sample code 3: enc/dec/mac using token object id.</h2> <p class="summary">computes the hash of a file and saves it to another file, illustrates the use of nss message apis.</p> <pre class="brush: cpp"> /* this source code form is subject to the terms of the mozilla public * license, v.
...: 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...
...es_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; } /* * decrypt */ secstatus decrypt(pk11context *ctx, unsigned char *out, unsigned int *outlen, unsigned int maxout, unsigned char *in, unsigned int inlen) {...
Utilities for nss samples
nss sample code 0: utilities.
... util.h /* this source code form is subject to the terms of the mozilla public * license, v.
...toitem */ extern secstatus filetoitem(secitem *dst, prfiledesc *src); /* * seedfromnoisefile */ extern secstatus seedfromnoisefile(const char *noisefilename); /* * filesize */ extern long filesize(const char* filename); /* * readderfromfile */ extern secstatus readderfromfile(secitem *der, const char *infilename, prbool ascii); #endif /* _util_h */ util.c /* this source code form is subject to the terms of the mozilla public * license, v.
PKCS 12 functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions 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 3.8 and later sec_pkcs12decoderstart mxr 3.2 and later sec_pkcs12decoderupdate mxr 3.2 and later sec_pkcs12decodervalidatebags mxr 3.2 and later sec_pkcs12decoderverify mxr 3.2 and later sec_pkcs12destroyexportcontext mxr 3.2 and later sec_pkcs12enablecipher mxr 3.2 and later sec_pkcs12encode mxr 3.2 and later sec_pkcs12isencryptionallowed mxr 3.2 and later sec_pkcs12setpreferredcipher ...
NSS_Initialize
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.
...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.
...this may be necessary in order to ensure continuous operation and proper shutdown sequence if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, java sunpkcs11 provider.
NSS tools : pk12util
return codes o 0 - no error o 1 - user cancelled o 2 - usage error o 6 - nls init error o 8 - certificate db open error o 9 - key db open error o 10 - file initialization error o 11 - unicode conversion error o 12 - temporary file creation error o 13 - pkcs11 get slot error o 14 - pkcs12 decoder start error o 15 - error read from import file o 16 - pkcs12 decode error o 17 - pkcs12 decoder veri...
...fy error o 18 - pkcs12 decoder validate bags error o 19 - pkcs12 decoder import bags error o 20 - key db conversion version 3 to version 2 error o 21 - cert db conversion version 7 to version 5 error o 22 - cert and key dbs patch error o 23 - get default cert db error o 24 - find cert by nickname error o 25 - create export context error o 26 - pkcs12 add password itegrity error o 27 - cert and key safes creation error o 28 - pkcs12 add cert and key error o 29 - pkcs12 encode error examples importing keys and certificates the most basic usage of pk12util for importing a certificate or key is the pkcs#12 input file (-i) and some way to specify the security database being accessed (either -d for a directory or -h for a token).
...the nss site relates directly to nss code changes and releases.
sslcrt.html
use pr_geterror to obtain the error code.
...use pr_geterror to obtain the error code.
...use pr_geterror to obtain the error code.
NSS tools : pk12util
return codes o 0 - no error o 1 - user cancelled o 2 - usage error o 6 - nls init error o 8 - certificate db open error o 9 - key db open error o 10 - file initialization error o 11 - unicode conversion error o 12 - temporary file creation error o 13 - pkcs11 get slot error o 14 - pkcs12 decoder start error o 15 - error read from import ...
...file o 16 - pkcs12 decode error o 17 - pkcs12 decoder verify error o 18 - pkcs12 decoder validate bags error o 19 - pkcs12 decoder import bags error o 20 - key db conversion version 3 to version 2 error o 21 - cert db conversion version 7 to version 5 error o 22 - cert and key dbs patch error o 23 - get default cert db error o 24 - find cert by nickname error o 25 - create export context error o 26 - pkcs12 add password itegrity error o 27 - cert and key safes creation error o 28 - pkcs12 add cert and key error o 29 - pkcs12 encode error examples importing keys and certificates the most basic usage of pk12util for importing a certificate or key is the pkcs#12 input file (-i) and some way to specify ...
...the nss site relates directly to nss code changes and releases.
Necko walkthrough
this is where it hits necko code.
...then in necko http code (still on the main thread for now): nshttpchannel::asyncopen nshttpchannel::beginconnect() creates nshttpconnectioninfo object for the channel checks if we're proxying or not fires off the dns prefetch request (dispatched to dns thread pool) some other things nshttpchannel::connect might to a speculativeconnect (pre open tcp socket) nshttpchannel::continueconne...
... 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.
Creating JavaScript 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.
... checking in completed tests tests are usually reviewed and pushed just like any other code change.
... it is ok under certain circumstances to push new tests to certain repositories without a code review.
Exact Stack Rooting
} 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.
...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.
...this is not a terribly safe option for embedder code, so only consider this as a very last resort.
SpiderMonkey Internals: Thread Safety
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.
...a single jscontext can run work with code and objects in multiple compartments as long as no other thread is accessing those compartments.
JS::CompileFunction
chars, bytes, or srcbuf is a string containing the source code of the function.
... length is the length of the source code in characters.
... see also the jsapi user guide contains example code using compiled scripts.
JSFunction
the apis js_newfunction, js_definefunction, js_compilefunction, and their unicode equivalents return values of type jsfunction *.
...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 objects) generated from the same source code may share the same jsfunction.
JS_BeginRequest
indicates to the js engine that the calling thread is entering a region of code that may call into the jsapi but does not block.
... 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.
...it is therefore imperative that native code executing within an active request on cx not block, or simply take too long, outside the jsapi.
JS_CompareStrings
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.
JS_CompileFunction
js_compileucfunction is the unicode version of the function.
... body is a string containing the source code of the function.
... length is the length of the source code in characters.
JS_CompileFunctionForPrincipals
body const char * or const jschar * string containing the source code of the function to compile.
...js_compileucfunctionforprincipals is the unicode version of the function.
... body is the string containing the source code of the function.
JS_DecompileFunction
generates the complete source code of a function declaration from a compiled function.
... description js_decompilefunction generates the complete source code of a function declaration from a function's compiled form, fun.
...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.
JS_GetScopeChain
retrieves the scope chain for the javascript code currently running in a given context.
... description js_getscopechain returns the first jsobject on the scope chain for the javascript code currently running in the given context, cx.
... if any code is currently executing in cx, js_getscopechain returns a pointer to the first jsobject on the current scope chain.
JS_GetStringBytes
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.
...instead, you should use js_encodestring, js_getstringencodinglength, js_encodestringtobuffer.
...see also js_encodestring js_encodestringtoutf8 js_getstringencodinglength js_encodestringtobuffer js_comparestrings js_getstringlength js_valuetostring bug 607292 ...
JS_GetStringCharAt
on successful, receives the character code.
... 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.
JS_GetStringLength
return the length, in 16-bit code units, of a javascript string.
... description js_getstringlength reports the length, in 16-bit code units, of the string str.
...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.
JS_LookupProperty
js_lookupucproperty is the unicode version of js_lookupproperty.
...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.
...do not automatically infer and enable other flags by looking at the currently executing bytecode.
JS_THREADSAFE
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.
... 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.
Thread Sanitizer
building firefox getting the source if you don't have a source code repository clone yet, you need to get yourself a clone of mozilla-central.
... 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.
...in our codebase, this is done using the moz_tsan_blacklist macro on the function definition.
A Web PKI x509 certificate primer
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.
... error codes in firefox here are some common errors that might be encountered when working with certificates in firefox.
... error code what it means what can i do sec_error_bad_der a certificate is not properly encoded according to asn.1 (der) encoding re-generate the improperly-encoded certificate sec_error_ca_cert_invalid an end-entity certificate is being used to issue another certificate ensure that any certificate intended to issue certificates has a basic constraints extension with ca: true sec_error_bad_signature a signature on a certificate is improperly formatted or the certificate has been tampered with re-issue the certificate with the bad signature sec_error_cert_bad_access_location the ocsp uri in the authorityinformationaccess extension is improperly formed re-generate the certificate with a well-formed ocsp uri sec_...
Browser security
an important aspect of developing code for any browser, including firefox, as well as any web-oriented project, is its security.
... these articles provide important guides and references to ensuring the code you write is secure, including both design recommendations and testing guidelines.
... secure development guidelinesthe following content will likely see significant revision, though can be used as a reference for security best practices to follow when developing code for mozilla.security and the jar protocolthis article discusses security concerns with the jar: protocol, which only firefox has ever implemented for web content.
Task graph
after a change to the gecko source code is pushed to version-control, jobs for that change appear on treeherder.
... all of this is controlled from within the gecko source code, through a process called task-graph generation.
... the details of task-graph generation are documented in the source code itself, including a some quick recipes for common changes.
Feed content access API
loading the feed and sending it to the parser is done using code similar to this: fetch: function(feedurl) { var httprequest = null; function inforeceived() { var data = httprequest.responsetext; var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var uri = ioservice.newuri(feedurl, null, null); if (data.length) {...
...that code looks like this: feedtestresultlistener.prototype = { handleresult: function(result) { var feed = result.doc; feed.queryinterface(components.interfaces.nsifeed); // open a new window var win = window.open("", "feedtest_window"); var doc = win.document.wrappedjsobject; doc.open(); // write the html header and page title ...
...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.
Places Developer Guide
it provides code samples for many common use-cases, such as crud operations, searching, and observing.
... // you can access a bookmark item's annotations with the <code>nsiannotationservice</code>.
...var startdate = enddate - (7 * 86400 * 1000 * 1000); // one week ago, in microseconds browserhistory.removepagesbytimeframe(startdate, enddate); // remove all pages for a given host var entiredomain = true; // will delete from all hosts from the given domain browserhistory.removepagesfromhost("mozilla.com", true); // remove all history visits browserhistory.removeallpages(); querying history the code sample below queries the browser history for the ten most visited urls in the browser history.
Using the Places history service
this information is called a "visit" in this document and in the code.
... nsibrowserhistory.addpagewithdetails: called by history importing code.
... new code should use nsinavhistoryservice.setpagedetails.
Generating GUIDs
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.
... nsiuuidgenerator a uuid can be generated from privileged mozilla code using nsiuuidgenerator.
... 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.
Building the WebLock UI
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.
...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.
... 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.
Making cross-thread calls using runnables
however, it may be useful for c++ code in the mozilla platform to run tasks on another thread.
... note: javascript code cannot use the techniques described in this article.
...} see also chromeworker using workers in javascript code modules the thread manager ...
How to build a binary XPCOM component using Visual Studio
you could try to use a different vendor's compiler, but you are going to need to build the sdk from source code.
...you can take the code and create implementation h and cpp files.
...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...
Components.utils.schedulePreciseGC
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.
...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.
XPConnect wrappers
this means that when you say window.focus(), you're calling into xpcwrappednative code.
...c++ calls are routed through xpcwrappedjs code into your javascript implementation.
...if you need to make objects or functions defined in chrome code accessible to content, use components.utils.cloneinto or components.utils.exportfunction.
XPCShell Reference
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.
Monitoring HTTP activity
gecko 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.
... creating an http activity observer to observe http activity, you need to implement the nsihttpactivityobserver interface within your code.
...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.
IJSDebugger
you should usually interface with this using the javascript code module instead of directly.
...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 is if you need to debug chrome; due to bug 707237, the javascript code module doesn't work in that case.
imgIContainerObserver
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.
...see also imgidecoderobserver imgicontainer ...
jsdIStackFrame
native code only!
...native code only!
...native code only!
mozIStorageAggregateFunction
if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code.
...if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code.
... sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection.
mozIStorageConnection
lasterror long the last sqlite error code that occurred.
...see mozistorageaggregatefunction for sample code and more details.
...see mozistoragefunction for sample code and more details.
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 why the change failed.
...void oncomplete( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult of the change indicating success or failure reason.
nsIAccessibleDocument
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!
...native code only!
... native code only!getcachedaccessnode obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete.
nsIAppShell
dispatchnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app specific code.
...native event starvation this hint tells the native dispatch code which to favor.
... getnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app specific code.
nsIBrowserSearchService
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().
... if your code requires nsibrowsersearchservice and is executed during startup, you should make sure that this code is executed from the callback to init().
nsIChannelEventSink
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.
...this may happen due to an http 3xx status code.
nsIDOMHTMLSourceElement
the codecs parameter may be specified and might be necessary to specify exactly how the resource is encoded.
... 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.
...the type is specified as "video/ogg", and the source element also specifies that the video file uses the dirac and speex codecs.
nsIDOMParser
these values are automatically determined as defined below, but if you work with domparser from privileged code, you can override the defaults by providing arguments to the domparser constructor or calling parser.init().
... when a domparser is instantiated by calling new domparser(), it inherits the calling code's principal (except that for chrome callers the principal is set to the null principal) and the documenturi and baseuri of the window the constructor came from.
...supposedly, if you want to create objects that some particular set of unprivileged code will be able to access (see discussion in bug 565480).
nsIDownloadProgressListener
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.
... 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.
...rather, only fill in the code for the ones you need, and leave the others blank as shown.
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...
...tputnoformattinginpre = 8192, // outputencodebasicentities=16384, outputencodelatin1entities=32768, // outputencodehtmlentities=65536, outputpersistnbsp=131072 editorapi.outputtostring('text/html', 2); editorapi.outputtostring('text/plain', 4); // output the body tag, body children and the html end tag (</html>).
... methods native code only!init initializes the editor's services.
nsIHttpChannel
requestsucceeded boolean returns true if the http response code indicates success.
...use this attribute to distinguish server error pages from normal pages, instead of comparing the response status manually against the set of valid response codes, if that is required by your application.
... responsestatus unsigned long get the http response code (for example 200).
nsIMsgWindow
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.
nsIProfile
method overview void cloneprofile(in wstring profilename); void createnewprofile(in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir); void deleteprofile(in wstring name, in boolean candeletefiles); void getprofilelist(out unsigned long length, [retval, array, size_is(length)] out wstring profilenames); boolean profileexists(in wstring profilename); void renameprofile(in wstring oldname, in wstring newname); void shutdowncurrentprofile(in unsigned long shu...
...void createnewprofile( in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir ); parameters profilename the name to assign to the new profile.
... langcode the locale to use for the new profile.
nsIPromptService
its methods should be used in privileged code instead of dom window.alert, window.confirm, and other similar functions.
...you should use this method instead of window.alert in chrome code.
... return value true for ok, false for cancel example code alert example alert displays a simple dialog.
nsIProtocolHandler
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).
...for example, privileged code and websites that are same origin as this uri.
...depending on the protocol's implementation, unicode character sequences may or may not be %xx escaped.
nsIPushSubscription
dom/interfaces/push/nsipushservice.idlscriptable includes information needed to send a push message to privileged code.
...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("error creating subscription: " + code); } else { sendsubscriptiontoserver(subscription); } } ); see also nsipushservice nsipushmessage pushsubscription ...
nsIRequestObserver
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.
...void onstoprequest( in nsirequest arequest, in nsisupports acontext, in nsresult astatuscode ); parameters arequest request being observed.
... astatuscode reason for stopping (ns_ok if completed successfully) see also nsistreamlistener ...
nsISOCKSSocketInfo
native code only!
...native code only!
...native code only!
nsIScriptableInputStream
in particular, some bindings may convert the byte values into unicode code points, by assuming the byte values are encoded as iso-latin-1.
... 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.
...excerpt of the stream for this stream article is here, this is only an excerpt so cannot copy paste this code into scratchpad.
nsISessionStore
browser/components/sessionstore/nsisessionstore.idlscriptable provides a means for extensions and other code to store data in association with browser sessions, tabs, and windows.
...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.
nsIStringBundle
you may also use other formatting codes.
... you can only pass unicode strings in.
...you may also use other formatting codes, but can only pass unicode strings in.
nsIStringBundleService
formatstatusmessage() formats a message string from a status code and status arguments.
... wstring formatstatusmessage( in nsresult astatus, in wstring astatusarg ); parameters astatus the status code.
... 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.
nsISupports proxies
xpcom proxies were a technology which allowed code to make asynchronous or synchronous xpcom calls to a different thread on arbitrary xpcom interfaces.
...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.
...they from the majority of javascript code, which is small and can be quickly run.
nsITimer
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!
...native code only!
... native code only!initwithfunccallback initialize a timer to fire after the given millisecond interval.
nsITreeColumn
last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void getidconst([shared] out wstring idconst); native code only!
...native code only!
... methods native code only!getidconst void getidconst( [shared] out wstring idconst ); parameters idconst getnext() get the next column in the nsitreecolumns.
nsIWindowWatcher
this is taken care of both in mozilla and by common embedding code.
... example for example, in a xul application or mozilla extension, if the window object is unavailable (for example, when opening a window from xpcom component code), you might want to use this interface for opening a new window: var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); var win = ww.openwindow(null, "chrome://myextension/content/about.xul", "aboutmyextension", "chrome,centerscreen", null); note: versions of gecko before gecko 2...
...for example the following code will block the system because it will open windows continuously: function mywindowobserver() { this.observe=function(asubject, atopic, adata) { alert("window event: " + atopic) //and this is where the bugs origins because opening this alert will cause a window-open //event and the call of this method again (forever) } } var ww = components.classes["@mozilla.org/embedcomp/window-w...
nsIXmlRpcFault
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.
... methods init() void getdata( in print32 faultcode, in string faultstring ); parameters faultcode tostring() string tostring(); ...
nsIZipReader
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.
... 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.
...then you can copy and paste this code in scratchpad to run it.
NS_StringContainerInit
otherwise, it returns an error code.
...with ns_stringcontainerinit, the coder is required to call ns_stringcontainerfinish when done with the nsstringcontainer object.
...example code nsstringcontainer str; if (ns_succeeded(ns_stringcontainerinit(str))) { // now, |str| can be used with any function taking a nsastring parameter.
Troubleshooting XPCOM components registration
to learn more about enabling chrome errors, see "how can i see errors in my code" in the extension faqs.
... double check your guids in your install.rdf with your sourcecode, and then check them again.
... the dllmain code that msvc 8 (and probably earlier versions too) generates for you doesn't need to be there, you can remove it.
XPCOM category image-sniffing-services
in versions of firefox prior to firefox 3, extensions could add decoders for new image types.
... however, such decoders relied on servers sending correct mime types; images sent with incorrect mime types would not be correctly displayed.
...if mozilla's built-in image code cannot identify an image, then any xpcom components implementing the nsicontentsniffer interface may register under the "image-sniffing-services" category, and will be queried to determine the mime type of the image being downloaded.
nsCOMPtr versus RefPtr
gecko code uses both nscomptr and refptr as smart pointers.
... this basic rule derives from the fact that some of the nscomptr<t> code is factored into the nscomptr_base base class, which stores the underlying mrawptr as an nsisupports*.
...in the future, more base classes might be added to t that would then cause unrelated code to break, which would be very confusing.
XSLT 2.0
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).
... 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).
The Valgrind Test Job
mach valgrind-test see also the general instructions for using valgrind with mozilla code.
... for example, we have a small number of deliberate but inconsequential memory leaks in the codebase that have corresponding suppressions.
... errors in mozilla code should probably be reported in bugs!
Adding items to the Folder Pane
the following code snippet listens for that event: let gnumbersext = { load: function gne_load() { window.removeeventlistener("load", gnumbersext.load, false); let tree = document.getelementbyid("foldertree"); tree.addeventlistener("maprebuild", gnumbersext._insert, false); }, _insert: function gne__insert() { // this function is called when a rebuild occurs } }; window.addeventlistener("l...
...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.
...add_code.js also includes code to accomplish this result.
Building a Thunderbird extension 1: introduction
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.
... 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.
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", 0, 72); } } }; function init() { var notificationservice = components.classes["@mozilla.org/messenger/msgnotificationservice;1"] .getservice(components.interfaces.nsimsgfoldernotificationservice); notificationservice.addlistener(newmaillistener, notificationservice.msgadded); } addeventlistener("load", init, true); have a look to nsimsgdbhdr to get the full list of properties to be modified.
... you can take a look at a working code in the capskiller add-on repository.
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.
...you can see the schema for the attachments table in the code.
... 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"].
Using popup notifications
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.
...the popupnotifications.jsm code module adds a popupid attribute to the notification object's icon element.
Using tab-modal prompts
using tab-modal prompts from chrome code currently, nsiprompt defaults to using window-modal prompts.
... you can force a prompt to be tab-modal using code like this: var thewindow = gbrowser.contentwindow; let prompt = components.classes["@mozilla.org/prompter;1"] .getservice(components.interfaces.nsipromptfactory) .getprompt(thewindow, components.interfaces.nsiprompt); let bag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); bag.setpropertyasbool("allowtabmodal", true); the var "thewindow" is a reference to the dom window.
...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.
Memory Management
memory management if js code creates a structure or an array, that memory will be valid as long as the js object stays alive.
... when binary code hands back a pointer/handle to allocated memory, the js code must make sure to free that memory with the correct allocator.
... closures you also need to be sure to retain references to any javascript code that native code may call back into.
Break on DOM mutation - Firefox Developer Tools
a dom mutation breakpoint pauses the code when the dom node on which you have set the breakpoint is modified.
... when you execute the code, the debugger will pause execution when the dom mutation occurs.
... 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.
Debug worker threads - Firefox Developer Tools
the debugger shows the source code for all running worker threads — web workers, service workers, etc.
...you can open the javascript file for the worker process and set breakpoints and logpoints just as you can with javascript code running on the main thread.
... inspecting worker code for example, see the selected item worker.js below — it is listed in a separate thread in the sources list, but appears in the source pane in the same way as main thread code when selected.
Use watchpoints - Firefox Developer Tools
when debugging javascript code, it can be useful to know when properties on objects are read or modified.
... in a large, complex codebase, it's not always easy to know where in the code a given property is accessed.
... 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.
DevTools API - Firefox Developer Tools
in terms of code, each tool has to provide a tooldefinition object.
...either key or keycode value.
...these views are only available in certain conditions controlled by the webconsole code.
Dominators view - Firefox Developer Tools
however, you can set it instead to "call stack" to see exactly where in your code the objects are being allocated.
... to enable this, you must check the box labeled "record call stacks" before you run the code that allocates the objects.
... example let's see how some simple code is reflected in the dominators view.
Examine and edit HTML - Firefox Developer Tools
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.
...clicking the marker switches to the line of javascript code in the debugger where the custom element got defined.
... whitespace-only text nodes web developers don’t write all their code in just one line of text.
UI Tour - Firefox Developer Tools
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.
...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.
Shader Editor - Firefox Developer Tools
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.
...for example, you can modify the colors: the editor highlights syntax errors in your code: if you hover over the cross shown next to a line containing an error, you'll see more details about the problem: ...
Web Console remoting - Firefox Developer Tools
to see how the debugger is used in the web console code, look in browser/devtools/webconsole/webconsole.js, and search for webconsoleconnectionproxy.
...the default source url for evaluation is "debugger eval code".
... 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.
AudioBufferSourceNode.loopEnd - Web APIs
example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode.
... for a full working example, see this code running live, or view the source.
... 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; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; loopstartcontrol.setattribute('max', math.floor(songlength)); loopendcontrol.setattribute('max', math.floor(songlength)); }, function(e){"error with decoding audio data" + e.err}); } request.send(); } ...
AudioBufferSourceNode.loopStart - Web APIs
example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode.
... for a full working example, see this code running live, or view the source.
... 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; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; loopstartcontrol.setattribute('max', math.floor(songlength)); loopendcontrol.setattribute('max', math.floor(songlength)); }, function(e){"error with decoding audio data" + e.err}); } request.send(); } ...
AudioConfiguration - Web APIs
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.
... bitrate: the number of bits used to encode 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.
AudioProcessingEvent - Web APIs
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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.create...
...scriptprocessor(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}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that w...
AudioWorkletProcessor - Web APIs
the audioworkletprocessor interface of the web audio api represents an audio processing code behind a custom audioworkletnode.
... constructor the audioworkletprocessor and classes that derive from it cannot be instantiated directly from a user-supplied code.
... usage notes deriving classes to define custom audio processing code you have to derive a class from the audioworkletprocessor interface.
BaseAudioContext.createScriptProcessor() - Web APIs
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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.create...
...scriptprocessor(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}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that w...
BaseAudioContext - Web APIs
12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">baseaudiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties baseaudiocontext.audioworklet read only secure context returns the audioworklet object, which can be used to create and manage audionodes in which javascript code implementing the audioworkletprocessor interface are run in the background to process audio data.
...audiobuffers are created using audiocontext.createbuffer or returned by audiocontext.decodeaudiodata when it successfully decodes an audio track.
... baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer.
Beacon API - Web APIs
example code of the interfaces described in this document is included in using the beacon api.
... 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.
...to solve this problem, analytics and diagnostics code will typically make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data.
Using the CSS Painting API - Web APIs
the code to do this looks like so: registerpaint('headerhighlight', class { static get contextoptions() { return { alpha: true }; } /* ctx is the 2d drawing context size is the paintsize, the dimensions (height and width) of the box being painted */ paint(ctx, size) { ctx.fillstyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillrect( 0, size.height / 3, s...
...ize.width * 0.4, size.height * 0.6 ); } }); this code example has two differences from our first example: we've included a second argument, which is the paint size.
... 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.
CanvasPattern.setTransform() - Web APIs
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.
... = 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="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.s...
...troke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener("click", function() { textarea.focus(); }); canvas.addeventlistener("mousemove", function(event){ if(event.region) { alert("ouch, my eye :("); } }); textarea.addeventlistener("input", drawcanvas); window.addeventlistener("load", drawcanvas); specifications canvas hit regions have been removed from ...
CanvasRenderingContext2D.fillText() - Web APIs
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.
CanvasRenderingContext2D.strokeText() - Web APIs
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.
A basic ray-caster - Web APIs
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.
...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.
...=) 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).
Applying styles and colors - Web APIs
this is what happens with the 1.0 width line in the previous example code.
...25 : -25; ctx.lineto(math.pow(i, 1.5) * 2, 75 + dy); } ctx.stroke(); return false; } <table> <tr> <td><canvas id="canvas" width="150" height="150"></canvas></td> <td>change the <code>miterlimit</code> by entering a new value below and clicking the redraw button.<br><br> <form onsubmit="return draw();"> <label>miter limit</label> <input type="number" size="3" id="miterlimit"/> <input type="submit" value="redraw"/> </form> </td> </tr> </table> document.getelementbyid('miterlimit').value = document.getelementbyid('canvas').getcontext('2...
...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).
Drawing text - Web APIs
a textbaseline example edit the code below and see your changes update live in the canvas: ctx.font = '48px serif'; ctx.textbaseline = 'hanging'; ctx.stroketext('hello world', 0, 100); playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="c...
...ode" 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() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', drawcanvas); window.addeventlistener('load', drawcanvas); advanced text measurements in the case you need to obtain m...
... the following code snippet shows how you can measure a text and get its width.
console - Web APIs
WebAPIConsole
for example, given this code: console.log("this is the outer level"); console.group("first group"); console.log("in the first group"); console.group("second group"); console.log("in the second group"); console.warn("still in the second group"); console.groupend(); console.log("back to the first group"); console.groupend(); console.debug("back to the outer level"); the output looks like this: timers you can start a tim...
... for example, given this code: console.time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console: notice that the timer's name is displayed both when the timer is start...
...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
examples autonomous custom element the following code is taken from our popup-info-box-web-component example (see it live also).
...' + 'opacity: 1;' + '}'; // attach the created elements to the shadow dom shadow.appendchild(style); shadow.appendchild(wrapper); wrapper.appendchild(icon); wrapper.appendchild(info); } } // define the new element customelements.define('popup-info', popupinfo); <popup-info img="img/alt.png" text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."> note: constructors for autonomous custom elements must extend htmlelement.
... customized built-in element the following code is taken from our word-count-web-component example (see it live also).
DirectoryReaderSync - Web APIs
example in the following code snippet from html5rocks, we create web workers and pass data from it to the main app.
... console.log(fileentry.name); }); }); }; worker.postmessage({'cmd': 'list'}); the following is worker.js code that gets the contents of the directory.
... 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.
Document.documentURIObject - Web APIs
this only works for privileged (universalxpconnect) scripts, including extension code.
... 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).
... 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')) { ...
Document: keydown event - Web APIs
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.
...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.
...by clicking in it), then try pressing some keys.</p> <p id="log"></p> document.addeventlistener('keydown', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeydown equivalent document.onkeydown = logkey; specifications specification status ui events working draft ...
Document: keyup event - Web APIs
bubbles yes cancelable yes interface keyboardevent event handler property onkeyup the keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
...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.
...by clicking in it), then try pressing some keys.</p> <p id="log"></p> const log = document.getelementbyid('log'); document.addeventlistener('keyup', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeyup equivalent document.onkeyup = logkey; specifications specification status ui events working draft ...
Locating DOM elements using selectors - Web APIs
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.
... 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.
...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.
Element: keydown event - Web APIs
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.
...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 a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keydown', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeydown equivalent input.onkeydown = logkey; specifications specification status ui events working draft ...
Element: keyup event - Web APIs
bubbles yes cancelable yes interface keyboardevent event handler property onkeyup the keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
...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 a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keyup', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeyup equivalent input.onkeyup = logkey; specifications specification status ui events working draft ...
Event.preventDefault() - Web APIs
<code>preventdefault()</code> won't let you check this!<br>"; event.preventdefault(); }, false); html <p>please click on the checkbox control.</p> <form> <label for="id-checkbox">checkbox:</label> <input type="checkbox" id="id-checkbox"/> </form> <div id="output-box"></div> result stopping keystrokes from reaching an edit field the following example demonstrates how invalid text i...
...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.preventdefault(); displaywarning( "please use lowercase letters only." + "\n" + "charcode: " + charcode + "\n" ); } } } the displaywarning() function presents a notification of a problem.
Using the Frame Timing API - Web APIs
this document describes how to use the performanceframetiming interfaces including example code.
... first, perhaps using the tools will save you is a bit too strong but performance tools can certainly help identify code that is not conformant to some expected time threshold.
...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.
Guide to the Fullscreen API - Web APIs
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.
... 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.
Fullscreen API - Web APIs
they must be added by javascript code.
... 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.
GlobalEventHandlers.onanimationend - Web APIs
.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.
... javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen.
... 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 event handlers for the animationstart and animationend events: let box = document.getelementbyid("box"); box.onanimationstart = function(event) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for ...
GlobalEventHandlers.onanimationstart - Web APIs
.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.
... javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen.
... 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 event handlers for the animationstart and animationend events: let box = document.getelementbyid("box"); box.onanimationstart = function(event) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for ...
HTMLImageElement.complete - Web APIs
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.
...this is demonstrated in the code below.
HTMLImageElement.decoding - Web APIs
the decoding property of the htmlimageelement interface represents a hint given to the browser on how it should decode the image.
...possible values are: sync: decode the image synchronously for atomic presentation with other content.
... async: decode the image asynchronously to reduce delay in presenting other content.
HTMLTextAreaElement - Web APIs
textlength read only long: returns the codepoint length of the control's value.
...ld</strong></span> | <span class="intlink" onclick="insertmetachars('&lt;em&gt;','&lt;\/em&gt;');"><em>italic</em></span> | <span class="intlink" onclick="var newurl=prompt('enter the full url for the link');if(newurl){insertmetachars('&lt;a href=\u0022'+newurl+'\u0022&gt;','&lt;\/a&gt;');}else{document.myform.mytxtarea.focus();}">url</span> | <span class="intlink" onclick="insertmetachars('\n&lt;code&gt;\n','\n&lt;\/code&gt;\n');">code</span> | <span class="intlink" onclick="insertmetachars(' :-)');">smile</span> | etc.
...*/ { keycode: 38 }).keycode, // put here the maximum number of characters per line: ncols = 30, // put here the maximum number of lines: nrows = 5, nsels = ofield.selectionstart, nsele = ofield.selectionend, sval = ofield.value, nlen = sval.length, nbackward = nsels >= ncols ?
The HTML DOM API - Web APIs
ed since it causes this article to always load with this example focused and scrolled into view] //namefield.focus(); namefield.addeventlistener("input", event => { const elem = event.target; const valid = elem.value.length != 0; if (valid && sendbutton.disabled) { sendbutton.disabled = false; } else if (!valid && !sendbutton.disabled) { sendbutton.disabled = true; } }); this code uses the document interface's getelementbyid() method to get the dom object representing the <input> elements whose ids are username and sendbutton.
...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.
File drag and drop - Web APIs
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).
...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.
IDBTransactionSync - Web APIs
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.
... 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.
... 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
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 code snippet also shows a best practice for versioning caches used by the service worker.
...the code maps a shorthand identifier for a cache to a specific, versioned cache name.
Keyboard.lock() - Web APIs
WebAPIKeyboardlock
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.
KeyboardEvent() - Web APIs
"code", optional and defaulting to "", of type domstring, that sets the value of keyboardevent.code.
... "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.
LocalFileSystem - Web APIs
example the following is a code snippet that shows how you can request a file system storage.
... 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.
... returns void exceptions this method can raise an fileerror with the following code: exception description encoding_err the syntax of the url was invalid.
MediaCapabilitiesInfo - Web APIs
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?
...all supported audio codecs are reported to be power efficient.
...'' : 'not ') + 'supported, ' + // can the media, as configured, be decoded by the user agent (result.smooth ?
MediaDevices.ondevicechange - Web APIs
: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } h2 { margin-bottom: 4px; } .left { float:left; width: 48%; margin-right: 2% } .right { float:right; width: 48%; margin-left: 2% } .devicelist { border: 1px solid black; list-style-type: none; margin-top: 2px; padding: 6px; } javascript content other code below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail.
...strong>" + device.label + "</strong> (" + direction + ")"; if (type === "audio") { audiolist.appendchild(elem); } else if (type === "video") { videolist.appendchild(elem); } }); }); } updatedevicelist() consists entirely of a call to the function enumeratedevices() on the mediadevices object referenced in the navigator.mediadevices property, as well as the code that's run when the promise returned by enumeratedevices() is fulfilled.
...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.
MediaStream Recording API - Web APIs
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 { // ...
... 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 (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.
Media Capabilities API - Web APIs
'' : 'not ') + 'power efficient.') }) .catch(() => { console.log("decodinginfo error: " + contenttype) }); } media capabilities api concepts and usage there are a myriad of video and audio codecs.
...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.
... media capabilities interfaces mediacapabilities provides information about the decoding abilities of the device, system and browser based on codecs, profile, resolution, and bitrates.
MerchantValidationEvent.complete() - Web APIs
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.
... 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.
MouseEvent.pageX - Web APIs
WebAPIMouseEventpageX
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.
...t.queryselector(".box"); var pagex = document.getelementbyid("x"); var pagey = document.getelementbyid("y"); function updatedisplay(event) { pagex.innertext = event.pagex; pagey.innertext = event.pagey; } box.addeventlistener("mousemove", updatedisplay, false); box.addeventlistener("mouseenter", updatedisplay, false); box.addeventlistener("mouseleave", updatedisplay, false); the javascript code uses addeventlistener() to register the function updatedisplay() as the event handler for the mousemove, mouseenter, and mouseleave events.
... </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".
Navigator.sendBeacon() - Web APIs
the following example shows theoretical analytics code that attempts to submit data to a server with a synchronous xmlhttprequest in an unload handler.
...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.
Node.removeChild() - Web APIs
WebAPINoderemoveChild
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.
...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
WebAPINodeList
nodelist.entries() returns an iterator, allowing code to go through all key/value pairs contained in the collection.
... 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.
OfflineAudioContext.startRendering() - Web APIs
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.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it 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; source.connect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('rendering failed: ...
OfflineAudioContext - Web APIs
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.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it 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; source.connect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('rendering failed: ' + err); // note: the promise should reject when startrendering is cal...
PaymentRequest.show() - Web APIs
those look like this: async/await syntax using await to wait for a promise to be resolved makes it possible to write the code to handle payments particularly cleanly: async function processpayment() { try { const payrequest = new paymentrequest(methoddata, details, options); payrequest.onshippingaddresschange = ev => ev.updatewith(checkaddress(payrequest)); payrequest.onshippingoptionchange = ev => ev.updatewith(checkshipping(payrequest)); const repsonse = await payrequest.show(); await validate...
...response(response); } catch(err) { /* handle the error; aborterror usually means a user cancellation */ } } in this code, the methods checkaddress() and checkshipping(), respectively, check the shipping address and the shipping option changes and supply in response either a paymentdetailsupdate object or a promise to return one; this object contains the fields in the paymentresponse which have been or need to be changed.
... 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.
Using Pointer Events - Web APIs
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.
...the source code is available on github and pull requests and bug reports are welcome.
... convenience functions this example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.
RTCDTMFSender - Web APIs
the rtcdtmfsender interface provides a mechanism for transmitting dtmf codes on a webrtc rtcpeerconnection.
...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.
... 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.
RTCError - Web APIs
WebAPIRTCError
properties in addition to the properties defined by the parent interface, domexception, rtcerror includes the following properties: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred.
... sctpcausecode read only if errordetail is sctp-failure, this property is a long integer specifying the sctp cause code indicating the cause of the failed sctp negotiation.
...this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
RTCErrorEvent.error - Web APIs
additional properties defined by rtcerror are: errordetail read only a domstring specifying the webrtc-specific error code identifying the type of error that occurred.
... sctpcausecode read only if errordetail is sctp-failure, this property is a long integer specifying the sctp cause code indicating the cause of the failed sctp negotiation.
...this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
RTCOutboundRtpStreamStats.pliCount - Web APIs
a pli packet indicates that some amount of encoded video data has been lost for one or more frames.
...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.
...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.
RTCPeerConnection.addStream() - Web APIs
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).
...you can write web compatible code using feature detection instead: // add a track to a stream and the peer connection said stream was added to: stream.addtrack(track); if (pc.addtrack) { pc.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 => se...
...nder.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.
RTCPeerConnection: icecandidate event - Web APIs
this candidate needs to be delivered to the remote peer over the signaling channel your code manages.
...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.
... 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.
RTCPeerConnection: icecandidateerror event - Web APIs
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.
... 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.
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.
...it is included here in order to help you adapt existing code and understand existing samples, which may not be up-to-date yet.
... 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.
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 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.
RTCRtpEncodingParameters - Web APIs
an instance of the webrtc api's rtcrtpencodingparameters dictionary describes a single configuration of a codec for an rtcrtpsender.
...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.
... 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.
RTCRtpSender - Web APIs
the rtcrtpsender interface provides the ability to control and obtain details about how a particular mediastreamtrack is encoded and sent to a remote peer.
...you can also obtain access to an rtcdtmfsender which can be used to send dtmf codes (to simulate the user pressing buttons on a telephone's dial pad) to the remote peer.
... rtcrtpsender.setparameters() applies changes to parameters which configure how the track is encoded and transmitted to the remote peer.
SVGImageElement.decoding - Web APIs
the decoding property of the svgimageelement interface represents a hint given to the browser on how it should decode the image.
...possible values are: sync: decode the image synchronously for atomic presentation with other content.
... async: decode the image asynchronously to reduce delay in presenting other content.
SVGStyleElement - Web APIs
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.
... 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.
... 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.
ScriptProcessorNode.bufferSize - Web APIs
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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscript...
...processor(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}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be mo...
ScriptProcessorNode.onaudioprocess - Web APIs
} 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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.create...
...scriptprocessor(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}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that w...
ScriptProcessorNode - Web APIs
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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscript...
...processor(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}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // the input buffer is the song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be mo...
Sensor APIs - Web APIs
the code example below illustrates these principles.
... if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
... if (event.error.name === 'notallowederror') { // branch to code for requesting permission.
ServiceWorkerContainer - Web APIs
serviceworkercontainer.ready read only provides a way of delaying code execution until a service worker is active.
...if supported, the code registers the service worker and determines if the page is actively controlled by the service worker.
...the code also reports any registration failures.
SharedWorkerGlobalScope - Web APIs
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.
...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.
SourceBuffer - Web APIs
coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out.
...this example was written by nick desaulniers and can be viewed live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var 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); } 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 }); sourcebuffer.appendbuffer(buf); }); } function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); } specifications specification status comment media source extensionsthe definition of 'sourcebuffer'...
SpeechSynthesisErrorEvent.error - Web APIs
the error property of the speechsynthesiserrorevent interface returns an error code indicating what has gone wrong with a speech synthesis attempt.
... syntax myerror = event.error; value a domstring containing an error code.
... possible codes are: canceled a speechsynthesis.cancel method call caused the speechsynthesisutterance to be removed from the queue before it had begun being spoken.
SubtleCrypto.deriveBits() - Web APIs
see the complete code on github.
...see the complete code on github.
...*/ 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.
SubtleCrypto.deriveKey() - Web APIs
see the complete code on github.
...see the complete code on github.
...*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), "pbkdf2", false, ["derivebits", "derivekey"] ); } async function encrypt(plaintext, salt, iv) { let keymaterial = await getkeymaterial(); let key = await window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, { "name": "aes-gcm", "length": 256}, true, [ "encrypt", "decrypt" ] ); return window.crypto.subtle.encrypt( { name: "aes-gcm", ...
TransformStream - Web APIs
this.transform(chunk.valueof(), controller) // hack else if ('tojson' in chunk) this.transform(json.stringify(chunk), controller) break case 'symbol': controller.error("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.
... const tes = { start(){this.encoder = new textencoder()}, transform(chunk, controller) { controller.enqueue(this.encoder.encode(chunk)) } } let _jstes_wm = new weakmap(); /* info holder */ class jstextencoderstream extends transformstream { constructor() { let t = {...tes} super(t) _jstes_wm.set(this, t) } get encoding() {return _jstes_wm.get(this).encoder.encoding} } similarly, textdecoderstream can be written as such: const tes = { start(){ this.decoder = new textdecoder(this.encoding, this.options) }, transform(chunk, controller) { controller.enqueue(this.decoder.decode(chunk)) } } let _jstds_wm = new weakmap(); /* info holder */ class jstextdecoderstream extends transformstream { co...
...nstructor(encoding = 'utf-8', {...options} = {}) { let t = {...tds, encoding, options} super(t) _jstes_wm.set(this, t) } get encoding() {return _jstds_wm.get(this).decoder.encoding} get fatal() {return _jstds_wm.get(this).decoder.fatal} get ignorebom() {return _jstds_wm.get(this).decoder.ignorebom} } chaining multiple readablestreams together this is a useful one, where multiple streams can be conjoined.
URL - Web APIs
WebAPIURL
the url interface is used to parse, construct, normalize, and encode urls.
... url parameter, and an optional base parameter to use as a base if the url parameter is a relative url: const url = new url('../cats', 'http://www.example.com/dogs'); console.log(url.hostname); // "www.example.com" console.log(url.pathname); // "/cats" url properties can be set to construct the url: url.hash = 'tabby'; console.log(url.href); // "http://www.example.com/cats#tabby" urls are encoded according to the rules found in rfc 3986.
... 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.
URLUtilsReadOnly.hash - Web APIs
the hash is not percent encoded.
...ng internethash experimentalchrome no support noedge no support nofirefox full support 38 full support 38 no support 3.5 — 38notes notes before firefox 38, firefox returned the hash percent encoded.
... nowebview android no support nochrome android no support nofirefox android full support 38 full support 38 no support 4 — 38notes notes before firefox 38, firefox returned the hash percent encoded.
URL API - Web APIs
WebAPIURL API
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.
...after executing the code snippet above, the value returned by addr.href is https://someguy@mysite.com/login.
...rlsearchparams object's get() method: let addr = new url("https://mysite.com/login?user=someguy&page=news"); try { loginuser(addr.searchparams.get("user")); gotopage(addr.searchparams.get("page")); } catch(err) { showerrormessage(err); } for example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site.
VideoConfiguration - Web APIs
see our web video codec guide for types which may be supported.
... bitrate: the number of bits used to encode one second of the video file.
... 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.
WebGLRenderingContext.getShaderSource() - Web APIs
the webglrenderingcontext.getshadersource() method of the webgl api returns the source code of a webglshader as a domstring.
... syntax domstring gl.getshadersource(shader); parameters shader a webglshader object to get the source code from.
... return value a domstring containing the source code of the shader.
WebGLRenderingContext.getUniformLocation() - Web APIs
am(shaderprogram); uscalingfactor = gl.getuniformlocation(shaderprogram, "uscalingfactor"); uglobalcolor = gl.getuniformlocation(shaderprogram, "uglobalcolor"); urotationvector = gl.getuniformlocation(shaderprogram, "urotationvector") 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.
... 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.
WebGLRenderingContext.shaderSource() - Web APIs
the webglrenderingcontext.shadersource() method of the webgl api sets the source code of a webglshader.
... syntax void gl.shadersource(shader, source); parameters shader a webglshader object in which to set the source code.
... source a domstring containing the glsl source code to set.
WebGLRenderingContext - Web APIs
webglrenderingcontext.getshadersource() returns the source code of a webglshader as a string.
... webglrenderingcontext.shadersource() sets the source code in a webglshader.
..." + "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.
WebGLShader - Web APIs
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.
... 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.
... examples creating a vertex shader note that there are many other strategies for writing and accessing shader source code strings.
A simple RTCDataChannel sample - Web APIs
<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.
... 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.
... next steps you should try out this example and take a look at the webrtc-simple-datachannel source code, available on github.
Using WebRTC data channels - Web APIs
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 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.
...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.
WebSocket.close() - Web APIs
WebAPIWebSocketclose
syntax websocket.close(); parameters code optional a numeric value indicating the status code explaining why the connection is being closed.
...see the list of status codes of closeevent for permitted values.
... exceptions thrown invalid_access_err an invalid code was specified.
Writing WebSocket client applications - Web APIs
see the code, then try out the example for yourself.
... 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.
...there are assorted types of data packets the client might receive, such as: login handshake message text user list updates the code that interprets these incoming messages might look like this: examplesocket.onmessage = function(event) { var f = document.getelementbyid("chatbox").contentdocument; var text = ""; var msg = json.parse(event.data); var time = new date(msg.date); var timestr = time.tolocaletimestring(); switch(msg.type) { case "id": clientid = msg.id; setusername(); break; c...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
the first and most important thing to understand when considering the code to manage point-of-view and cameras in your application is this: webxr does not have cameras.
...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.
...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.
Fundamentals of WebXR - Web APIs
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.
...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.
...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.
WebXR Device API - Web APIs
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.
...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.
...however, there are issues specific to creating augmented and virtual reality settings that need to be considered when writing your lighting code.
Basic concepts behind Web Audio API - Web APIs
created from raw pcm data (the audio context has methods to decode supported audio formats).
... 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.
...conversely, when an mp3 is decoded, it starts off in interleaved format, but is converted to planar for processing.
Web Audio API best practices - Web APIs
there's no strict right or wrong way when writing creative code.
...an <audio> or <video> element), or you're looking to fetch the file and decode it into a buffer.
...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.
Using IIR filters - Web APIs
you can check out the full demo here on codepen.
... also see the source code on github.
... with that all in mind, let's take a look at the code to create an iir filter with the web audio api.
Using the Web Speech API - Web APIs
chrome support as mentioned earlier, chrome currently supports speech recognition with prefixed properties, therefore at the start of our code we include these lines to feed the right objects to chrome, and any future implementations that might support the features without a prefix: var speechrecognition = speechrecognition || webkitspeechrecognition var speechgrammarlist = speechgrammarlist || webkitspeechgrammarlist var speechrecognitionevent = speechrecognitionevent || webkitspeechrecognitionevent the grammar the next part of our ...
...code defines the grammar we want our app to recognise.
... 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.
Web Workers API - Web APIs
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.
... you can run whatever code you like inside the worker thread, with some exceptions.
... worker represents a running worker thread, allowing you to pass messages to the running worker code.
Window.event - Web APIs
WebAPIWindowevent
the read-only window property event returns the event which is currently being handled by the site's code.
... you should avoid using this property in new code, and should instead use the event passed into the event handler function.
... this property is not universally supported and even when supported introduces potential fragility to your code.
window.postMessage() - Web APIs
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.
... 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.
Worker.prototype.postMessage() - Web APIs
example the following code snippet shows the creation of a worker object using the worker() constructor.
... main thread code: var myworker = new chromeworker(self.path + 'myworker.js'); function handlemessagefromworker(msg) { console.log('incoming message from worker, msg:', msg); switch (msg.data.atopic) { case 'do_sendmainarrbuff': sendmainarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } myworker.addeve...
...); 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...
WritableStream.getWriter() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " +...
... decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " +...
... decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
WritableStreamDefaultWriter.close() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " +...
... decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
WritableStreamDefaultWriter.write() - Web APIs
const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " +...
... decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
notes: this code requires elevated privileges to run; you can only call it from a browser extension or from a xulrunner application.
...r(xhr) { let status = xhr.channel.queryinterface(ci.nsirequest).status; let errtype; if ((status & 0xff0000) === 0x5a0000) { // security module const nsinsserrorsservice = ci.nsinsserrorsservice; let nsserrorsservice = cc['@mozilla.org/nss_errors_service;1'].getservice(nsinsserrorsservice); let errorclass; // geterrorclass will throw a generic ns_error_failure if the error code is // somehow not in the set of covered errors.
...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.
XMLHttpRequest.sendAsBinary() - Web APIs
syntax xmlhttprequest.sendasbinary(binarystring); parameters binarystring a domstring which encodes the binary content to be sent.
... |*| :: 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...
...commented code).
XRSession.onsqueezeend - Web APIs
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.
... 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.
Web APIs
WebAPI
when writing code for the web, there are a large number of web apis 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...
ARIA: img role - Accessibility
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".
...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".
ARIA: button role - Accessibility
see the official wai-aria example code.
... 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.
... 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
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.
...before re-authenticating, encode the data as hidden or encrypted.
... if a form control is required, indicate it both visually and via code.
:nth-child() - CSS: Cascading Style Sheets
detailed example html <h3><code>span:nth-child(2n+1)</code>, without an <code>&lt;em&gt;</code> among the child elements.</h3> <p>children 1, 3, 5, and 7 are selected.</p> <div class="first"> <span>span 1!</span> <span>span 2</span> <span>span 3!</span> <span>span 4</span> <span>span 5!</span> <span>span 6</span> <span>span 7!</span> </div> <br> <h3><code>span:nth-child(2n+1)</code>, with an <code>&lt;em&g...
...t;</code> among the child elements.</h3> <p>children 1, 5, and 7 are selected.<br> 3 is used in the counting because it is a child, but it isn't selected because it isn't a <code>&lt;span&gt;</code>.</p> <div class="second"> <span>span!</span> <span>span</span> <em>this is an `em`.</em> <span>span</span> <span>span!</span> <span>span</span> <span>span!</span> <span>span</span> </div> <br> <h3><code>span:nth-of-type(2n+1)</code>, with an <code>&lt;em&gt;</code> among the child elements.</h3> <p>children 1, 4, 6, and 8 are selected.<br> 3 isn't used in the counting or selected because it is an <code>&lt;em&gt;</code>, not a <code>&lt;span&gt;</code>, and <code>nth-of-type</code> only selects children of that type.
... the <code>&lt;em&gt;</code> is completely skipped over and ignored.</p> <div class="third"> <span>span!</span> <span>span</span> <em>this is an `em`.</em> <span>span!</span> <span>span</span> <span>span!</span> <span>span</span> <span>span!</span> </div> css html { font-family: sans-serif; } span, div em { padding: 5px; border: 1px solid green; display: inline-block; margin-bottom: 3px; } .first span:nth-child(2n+1), .second span:nth-child(2n+1), .third span:nth-of-type(2n+1) { background-color: lime; } result specifications specification status comment selectors level 4the definition of ':nth-child' in that specification.
Coordinate systems - CSS: Cascading Style Sheets
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.
... our main code sets up the event handlers on the inner box by calling addeventlistener() for each of the types mouseenter, mousemove, and mouseleave.
Using feature queries - CSS: Cascading Style Sheets
we can start by creating that floated layout with the following code, which gives us three columns.
... 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.
Variable fonts guide - CSS: Cascading Style Sheets
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.
...example code follows at the end of the guide.
...if a number value supplied is outside the range encoded in the font, the browser should render the font at the closest value allowed.
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
this means that if you write some grid layout code in firefox, it should work in the same way in chrome.
...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.
...i then do my grid code on the <ul>, set my width and min-height on the <li> to auto.
Layout using named grid lines - CSS: Cascading Style Sheets
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.
...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.
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...
all - CSS: Cascading Style Sheets
WebCSSall
the all shorthand css property resets all of an element's properties except unicode-bidi, direction, and css custom properties.
...note that none of these values affect the unicode-bidi and direction properties.
... 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.
direction - CSS: Cascading Style Sheets
WebCSSdirection
the property sets the base text direction of block-level elements and the direction of embeddings created by the unicode-bidi property.
... the direction and unicode-bidi properties are the two only properties which are not affected by the all shorthand property.
... for the direction property to have any effect on inline-level elements, the unicode-bidi property's value must be embed or override.
<length> - CSS: Cascading Style Sheets
WebCSSlength
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.
...: 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...
...ector('.results'); inputelem.addeventlistener('change', () => { inputdiv.style.width = inputelem.value; const result = document.createelement('div'); result.classname = 'result'; result.style.width = inputelem.value; result.innerhtml = `<code>width: ${inputelem.value}</code>`; resultsdiv.appendchild(result); inputelem.value = ''; inputelem.focus(); }) result specifications specification status comment css values and units module level 4the definition of '<length>' in that specification.
place-content - CSS: Cascading Style Sheets
examples placing content in a flex container html <div id="container"> <div class="small">lorem</div> <div class="small">lorem<br/>ipsum</div> <div class="large">lorem</div> <div class="large">lorem<br/>impsum</div> <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 value="baseline">baseline</option> <option value="space-between">space-between</option> <option value="space-around">space-around</option> <option value="space-evenly" selected>space-evenly</option> <option value="stretch">stretch</option> <option value="center">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="safe"...
...>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...
Demos of open web technologies
2d graphics canvas blob sallad: an interactive blob using javascript and canvas (code demos) 3d raycaster processing.js p5js 3d on 2d canvas minipaint: image editor (source code) zen photon garden (source code) multi touch in canvas demo (source code) svg bubblemenu (visual effects and interaction) html transformations using foreignobject (visual effects and transforms) phonetics guide (interactive) 3d objects demo (interactive) blobular (interactive) video embedded in sv...
...g (or use the local download) summer html image map creator (source code) video video 3d animation "mozilla constantly evolving" video 3d animation "floating dance" streaming anime, movie trailer and interview billy's browser firefox flick virtual barber shop transformers movie trailer a scanner darkly movie trailer (with built in controls) events firing and volume control dragable and sizable videos 3d graphics webgl web audio fireworks ioquake3 (source code) escher puzzle (source code) kai 'opua (source code) virtual reality the polar sea (source code) sechelt fly-through (source code) css css zen garden css floating logo "mozilla" paperfold css blockout rubik's cube pure css slides planetarium (source code) loader with blend modes text reveal with c...
...lip-path ambient shadow with custom properties luminiscent vial css-based single page application (source code) transformations impress.js (source code) games ioquake3 (source code) kai 'opua (source code) web apis notifications api html5 notifications (source code) web audio api web audio fireworks oscope.js - javascript oscilloscope html5 web audio showcase (source code) html5 audio visualizer (source code) graphical filter editor and visualizer (source code) file api slide my text - presentation from plain text files web workers web worker fractals photo editor coral generator raytracer hotcold touch typing ...
Media buffering, seeking, and time ranges - Developer guides
note: you can see the timerange code running live on js bin.
...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).
... 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.
Block formatting context - Developer guides
if you use overflow, it is a good idea to comment the code to explain.
... html <section> <div class="box"> <div class="float">i am a floated box!</div> <p>i am content inside the container.</p> </div> </section> <section> <div class="box" style="overflow:auto"> <div class="float">i am a floated box!</div> <p>i am content inside the <code>overflow:auto</code> container.</p> </div> </section> <section> <div class="box" style="display:flow-root"> <div class="float">i am a floated box!</div> <p>i am content inside the <code>display:flow-root</code> container.</p> </div> </section> css section { height:150px; } .box { background-color: rgb(224, 206, 247); border: 5px solid rebeccapurple; } .bo...
... html <section> <div class="float">try to resize this outer float</div> <div class="box"><p>normal</p></div> </section> <section> <div class="float">try to resize this outer float</div> <div class="box" style="display:flow-root"><p><code>display:flow-root</code><p></div> </section> css section { height:150px; } .box { background-color: rgb(224, 206, 247); border: 5px solid rebeccapurple; } .box[style] { background-color: aliceblue; border: 5px solid steelblue; } .float { float: left; overflow: hidden; /* required by resize:both */ resize: both; margin-right:25px; width: 200px;...
Content categories - Developer guides
they are: <a>, <abbr>, <address>, <article>, <aside>, <audio>, <b>,<bdo>, <bdi>, <blockquote>, <br>, <button>, <canvas>, <cite>, <code>, <command>, <data>, <datalist>, <del>, <details>, <dfn>, <div>, <dl>, <em>, <embed>, <fieldset>, <figure>, <footer>, <form>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <header>, <hgroup>, <hr>, <i>, <iframe>, <img>, <input>, <ins>, <kbd>, <keygen>, <label>, <main>, <map>, <mark>, <math>, <menu>, <meter>, <nav>, <noscript>, <object>, <ol>, <output>, <p>, <picture>, <pre>, <progress>, <q>, <ruby>, <s>,...
... 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).
...instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts.
A hybrid approach - Developer guides
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.
...with proper planning, though, the code can still be organized in a maintainable way.
...feel free to check out the source code on github.
Parsing and serializing XML - Developer guides
"error while parsing" : odom.documentelement.nodename); parsing url-addressable resources into dom trees using xmlhttprequest here is sample code that reads and parses a url-addressable xml file into 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 construct...
... if the document is html, the code shown above will return a document.
... you can get html corresponding to the <body> and its descendants with this code: var dochtml = document.documentelement.outerhtml; ...
Printing - Developer guides
open and automatically close a popup window when finished if you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>javascript window close example </title> <script type="text/javascript"> function popuponclick() { my_window = window.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 utilize a hidden <iframe> (see: htmliframeelement), automatically removing it after the user prints its contents.
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
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> <h3>example 1</h3> <p>some text here...</p> <h3>example 2</h3> <p>some text here...</p> <h2>see also</h2> <p>some text here...</p> here is the result of this code: accessibility concerns navigation a common navigation technique for users of screen reading software is jumping from heading to heading to quickly determine the content of the page.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
to make buttons do anything, you have to write javascript code to do the work.
... hidden code 1 <input type="button" value="enabled"> const button = document.queryselector('input'); button.addeventlistener('click', disablebutton); function disablebutton() { button.disabled = true; button.value = 'disabled'; window.settimeout(function() { button.disabled = false; button.value = 'enabled'; }, 2000); } if the disabled attribute isn't specified, the button inherits its...
... hidden code 2 <fieldset> <legend>button group</legend> <input type="button" value="button 1"> <input type="button" value="button 2"> <input type="button" value="button 3"> </fieldset> const button = document.queryselector('input'); const fieldset = document.queryselector('fieldset'); button.addeventlistener('click', disablebutton); function disablebutton() { fieldset.disabled = true; window.s...
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
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.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
... 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).
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
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().
...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.
...in this instance, the string will be text=usertext, where "usertext" is the text entered by the user, encoded to preserve special characters.
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
there are also several deprecated attributes, which you should avoid but may need to know when reading older code.
...2011</time></td> <td><time datetime="2017-04008">april 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th>hoshi nakamura</td> <td>601942</td> <td><time datetime="2012-07-23">july 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </table> the differences that matter here—for the purposes of discussing row and column spans—are in the first few lines of the code above.
...2017-04008">april 8, 2017</time></td> <td>37.00</td> </tr> <tr> <th scope="row">hoshi nakamura</td> <td>601942</td> <td><time datetime="2012-07-23">july 23, 2012</time></td> <td>n/a</td> <td>15.00</td> </tr> </tbody> </table> the differences that matter here—for the purposes of discussing row and column spans—are in the first few lines of the code above.
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementtt
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.
... <p>enter the following at the telnet command prompt: <code>set localecho</code><br /> the telnet client should display: <tt>local echo is on</tt></p> result overriding the default font you can override the browser's default font—if the browser permits you to do so, which it isn't required to do—using css: css tt { font-family: "lucida console", "menlo", "monaco", "courier", monospace; } html <p>enter the following at the t...
...elnet command prompt: <code>set localecho</code><br /> the telnet client should display: <tt>local echo is on</tt></p> result usage notes the <tt> element is, by default, rendered using the browser's default non-proportional font.
Preloading content with rel="preload" - HTML: Hypertext Markup Language
you can see an example of this in our video example (see the full source code, and also the live version): <head> <meta charset="utf-8"> <title>video preload example</title> <link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4"> <link rel="preload" href="sintel-short.webm" as="video" type="video/webm"> </head> <body> <video controls> <source src="sintel-short.mp4" type="video/mp4"> <source src="sintel-short.webm" type="video/webm"> ...
...you can see the full example source code on github (also see it live): <head> <meta charset="utf-8"> <title>web font example</title> <link rel="preload" href="fonts/cicle_fina-webfont.woff2" as="font" type="font/woff2" crossorigin> <link rel="preload" href="fonts/zantroke-webfont.woff2" as="font" type="font/woff2" crossorigin> <link href="style.css" rel="stylesheet"> </head> <body> … </body> not only are we providing t...
... let's look at an example (see it on github — source code, live example): <head> <meta charset="utf-8"> <title>responsive preload example</title> <link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)"> <link rel="preload" href="bg-image-wide.png" as="image" media="(min-width: 601px)"> <link rel="stylesheet" href="main.css"> </head> <body> <header> <h1>my site</h1> </header> <script> var mediaquerylist = window.matchmedia...
Access-Control-Allow-Credentials - HTTP
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.
... when a request's credentials mode (request.credentials) is include, browsers will only expose the response to frontend javascript code if the access-control-allow-credentials value is true.
...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.
CSP: base-uri - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: default-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: form-action - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: img-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: navigate-to - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: prefetch-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 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.
CSP: script-src-attr - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: script-src-elem - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: style-src-attr - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
CSP: style-src-elem - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
... 'report-sample' requires a sample of the violating code to be included in the violation report.
DELETE - HTTP
WebHTTPMethodsDELETE
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.
POST - HTTP
WebHTTPMethodsPOST
in 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.
... request has body yes successful response has body yes safe no idempotent no cacheable only if freshness information is included allowed in html forms yes syntax post /test example a simple form using the default application/x-www-form-urlencoded content type: post /test http/1.1 host: foo.example content-type: application/x-www-form-urlencoded content-length: 27 field1=value1&field2=value2 a form using the multipart/form-data content type: post /test http/1.1 host: foo.example content-type: multipart/form-data;boundary="boundary" --boundary content-disposition: form-data; name="field1" value1 --boundary content-disposition: form-d...
404 Not Found - HTTP
WebHTTPStatus404
the http 404 not found client error response code indicates that the server can't find the requested resource.
... a 404 status code does not indicate whether the resource is temporarily or permanently missing.
...apache servers can be configured using an .htaccess file and a code snippet like the following example.
406 Not Acceptable - HTTP
WebHTTPStatus406
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.
...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.
500 Internal Server Error - HTTP
WebHTTPStatus500
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.
...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.
Keyed collections - JavaScript
the following code shows some basic operations with a map.
... for more information and example code, see also "why weakmap?" on the weakmap reference page.
... the following code shows some basic operations with a set.
constructor - JavaScript
if your class is a base class, the default constructor is empty: constructor() {} if your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided: constructor(...args) { super(...args); } that enables code like this to work: class validationerror extends error { printcustomermessage() { return `validation failed :-( (details: ${this.message})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.name); // this is error instead of validationerror!
...for example: class validationerror extends error { constructor(message) { super(message); // call parent class constructor this.name = 'validationerror'; this.code = '42'; } printcustomermessage() { return `validation failed :-( (details: ${this.message}, code: ${this.code})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.name); // now this is validationerror!
... examples using the constructor method this code snippet is taken from the classes sample (live demo).
SyntaxError: missing ) after condition - JavaScript
in any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs.
...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.
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.
... 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.
SyntaxError: unterminated string literal - JavaScript
examples multiple lines you can't split a string across multiple lines like this in javascript: var longstring = 'this is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.'; // syntaxerror: unterminated string literal instead, use the + operator, a backslash, or template literals.
... the + operator variant looks like this: var longstring = 'this is a very long string which needs ' + 'to wrap across multiple lines because ' + 'otherwise my code is unreadable.'; or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line.
...that form looks 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.`; ...
JavaScript error reference - JavaScript
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.
... error: permission denied to access property "x"internalerror: too much recursionrangeerror: argument is not a valid code pointrangeerror: invalid array lengthrangeerror: invalid daterangeerror: precision is out of rangerangeerror: radix must be an integerrangeerror: repeat count must be less than infinityrangeerror: repeat count must be non-negativereferenceerror: "x" is not definedreferenceerror: assignment to undeclared variable "x"referenceerror: can't access lexical declaration "x" before initializationreferenc...
...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
1 : arguments.callee(n - 1) * n; }); however, this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing, etc., but even the best code is suboptimal due to checks that would not otherwise be necessary.) the other major issue is that the recursive call will get a different this value, e.g.: var global = this; var sillyfunction = function(recursed) { if (!recursed) { return arguments.callee(true); } if (this !== global) { alert('this is: ' + this); } else { alert('this is the global'); } } sillyf...
...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.
...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.
The arguments object - JavaScript
description note: if you're writing es6 compatible code, then rest parameters should be preferred.
... 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.
Array.prototype.forEach() - JavaScript
example code let ratings = [5, 4, 5]; let sum = 0; let sumfunction = async function (a, b) { return a + b } ratings.foreach(async function(rating) { sum = await sumfunction(sum, rating) }) console.log(sum) // naively expected output: 14 // actual output: 0 examples no operation for uninitialized values (sparse arrays) const arraysparse = [1,3,,7] let numcallbackruns = 0 arraysparse.foreach((elem...
... 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...
... an object copy function the following code creates a copy of a given object.
AsyncFunction - JavaScript
it can be obtained with the following code: object.getprototypeof(async function(){}).constructor syntax new asyncfunction([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ...
...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.
... this is different from using eval with code for an async function expression.
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.
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.
Error.prototype.toSource() - JavaScript
the tosource() method returns code that could eval to the same error.
... syntax e.tosource() return value a string containing the source code of the error.
... examples using tosource calling the tosource method of an error instance (including nativeerrors) will return a string containing the source code of the error.
Error - JavaScript
urierror creates an instance representing an error that occurs when encodeuri() or decodeuri() are passed invalid parameters.
... this results in cleaner and more consistent error handling code.
...otherwise, old versions of babel and other transpilers will not correctly handle the following code without additional configuration.
GeneratorFunction - JavaScript
it could be obtained by evaluating the following code.
...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.
... this is different from using eval with code for a generator function expression.
Intl.Collator.prototype.resolvedOptions() - JavaScript
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.
... collation the value requested using the unicode extension key "co", if it is supported for locale, or "default".
... numeric casefirst the values requested for these properties in the options argument or using the unicode extension keys "kn" and "kf" or filled in as defaults.
Intl.DisplayNames() constructor - JavaScript
the following unicode extension key is allowed: nu the numbering system to be used.
... "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.
Intl.Locale() constructor - JavaScript
the intl.locale constructor is a standard built-in property of the intl object that represents a unicode locale identifier.
... syntax new intl.locale(tag [, options]) parameters tag the unicode locale identifier string.
...keys are unicode locale tags, values are valid unicode tag values.
Intl.Locale.prototype.collation - JavaScript
below is a table with the available collation types, taken from the unicode collation specification.
... direct binary code point order (used in hindi) ducet the default unicode collation element table order emoji recommended ordering for emoji characters eor european ordering rules gb2312 pinyin ordering for latin, gb2312han charset ordering for cjk characters (used in chinese) phonebk phonebook style ordering (such as in german) phonetic phoneti...
... adding a collation type via the locale string in the unicode locale string spec, collation types are locale key "extension subtags".
Intl.Locale.prototype.language - JavaScript
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.
... 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.
Intl.Locale.prototype.numberingSystem - JavaScript
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.
... modern tamil decimal digits telu telugu digits thai thai digits tirh tirhuta digits tibt tibetan digits traditio traditional numerals — may be algorithmic vaii vai digits wara warang citi digits wcho wancho digits examples setting the numberingsystem value via the locale string in the unicode locale string spec, the values that numberingsystem represents correspond to the key nu.
Intl.Locale.prototype.toString() - JavaScript
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.
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 () {} ...
... // 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, // new string() function string() { [native code] },false,test // 'test' changing the constructor of a f...
... 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.
Promise() constructor - JavaScript
the executor is custom code that ties an outcome to a promise.
... 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 callback is defined within the executor code.
handler.construct() - JavaScript
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() {}, { construct: function(target, argumentslist, newtarget) { return 1; } }); new p(); // typeerror is thrown the following code improperly initializes the proxy.
RegExp.prototype.dotAll - JavaScript
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.
Symbol.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the object.
... 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.
SyntaxError() constructor - JavaScript
the syntaxerror constructor creates a new error object that represents an error when trying to interpret syntactically invalid code.
... syntax new syntaxerror([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 catching a syntaxerror try { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e instanceof syntaxerror); // true console.error(e.message); // hello console...
....error(e.name); // syntaxerror console.error(e.filename); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
SyntaxError - JavaScript
the syntaxerror object represents an error when trying to interpret syntactically invalid code.
... it is thrown when the javascript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.
...s', 10); } catch (e) { console.error(e instanceof syntaxerror); // true console.error(e.message); // hello console.error(e.name); // syntaxerror console.error(e.filename); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } specifications specification ecmascript (ecma-262)the definition of 'syntaxerror' in that specification.
URIError() constructor - JavaScript
the name of the file containing the code that caused the exception.
...the line number of the code that caused the exception.
... examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating an urierror try { throw new urierror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "hello" console.log(e.name) // "urierror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log...
WebAssembly.CompileError() constructor - JavaScript
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.
...tch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.LinkError() constructor - JavaScript
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.
...; } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that specification.
WebAssembly.Module() constructor - JavaScript
a webassembly.module() constructor creates a new module object containing stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.
... the webassembly.module() constructor function can be called to synchronously compile given webassembly binary code.
... new webassembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile.
WebAssembly.RuntimeError() constructor - JavaScript
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.
...tch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly.runtimeerror constructor' in that specification.
WebAssembly.compile() - JavaScript
the webassembly.compile() function compiles webassembly binary code into a webassembly.module object.
... 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.
... 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().
Standard built-in objects - JavaScript
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.
... 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).
instanceof - JavaScript
note for mozilla developers: in code using xpcom, instanceof has special effect: obj instanceof xpcominterface (e.g.
... 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).
...instanceof object // returns true, same case as above mynonobj instanceof object // returns false, prototype is end of prototype chain (null) mystring instanceof date // returns false mydate instanceof date // returns true mydate instanceof object // returns true mydate instanceof string // returns false demonstrating that mycar is of type car and type object the following code creates an object type car and an instance of that object type, mycar.
yield - JavaScript
once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called.
... between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to generator.prototype.next(), generators offer enormous power and control.
... examples using yield the following code is the declaration of an example generator function.
break - JavaScript
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.
... 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.
... 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.
if...else - JavaScript
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.
...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.
label - JavaScript
in strict mode code, you can't use "let" as a label name.
... 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.
... 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.
try...catch - JavaScript
for example, when the exception occurs in the following code, control transfers to the catch-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.
...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.
Template literals (Template strings) - JavaScript
let str = string.raw`hi\n${2+3}!`; // "hi\n5!" str.length; // 6 array.from(str).join(','); // "h,i,\,n,5,!" tagged templates and escape sequences es2016 behavior as of ecmascript 2016, tagged templates conform to the rules of the following escape sequences: unicode escapes started by "\u", for example \u00a9 unicode code point escapes indicated by "\u{}", for example \u{2f804} hexadecimal escapes started by "\x", for example \xa9 octal literal escapes started by "\0o" and followed by one or more digits, for example \0o251 this means that a tagged template like the following is problematic, because, per ecmascript grammar, a parser looks for valid unico...
...de escape sequences, but finds malformed syntax: latex`\unicode` // throws in older ecmascript versions (es2016 and earlier) // syntaxerror: malformed unicode character escape sequence es2018 revision of illegal escape sequences tagged templates should allow the embedding of languages (for example dsls, or latex), where other escapes sequences are common.
...they will show up as undefined element in the “cooked” array: function latex(str) { return { "cooked": str[0], "raw": str.raw[0] } } latex`\unicode` // { cooked: undefined, raw: "\\unicode" } note that the escape sequence restriction is only dropped from tagged templates—not from untagged template literals: let bad = `bad escape sequence: \unicode`; specifications specification ecmascript (ecma-262)the definition of 'template literals' in that specification.
JavaScript typed arrays - JavaScript
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.
...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.
...this can be done using array.from(), or using the following code where array.from() is unsupported.
Autoplay guide for media and Web Audio APIs - Web media technologies
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.
... 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.
...checking for undefined prevents this code from failing with an error on older versions of web browsers.
Lazy loading - Web Performance
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.
... 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.
Navigation and resource timings - Web Performance
compression to get the compression savings percentage, we divide the transfersize by the decodedbodysize, and subtract that from 100%.
... 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.
...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.
Progressive web app structure - Progressive web apps (PWAs)
you can <a href="https://github.com/mdn/pwa-examples/blob/master/js13kpwa">fork js13kpwa on github</a> to check its source code.</p> <button id="notifications">request dummy notifications</button> <section id="content"> // content inserted in here </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com">andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a>.</p> </footer> </body> </html> the <head> section contains some basic info like title, d...
...].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...
... { 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.
Introduction to progressive web apps - Progressive web apps (PWAs)
an example application in this series of articles we will examine the source code of a super simple website that lists information about games submitted to the a-frame category in the js13kgames 2017 competition.
... you can see this app in action online, and the source code is available on github.
... we'll be examining this code carefully over the course of this series of articles.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
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.
... 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.
... feel free to explore the rest of the examples in the service worker cookbook if you want to know how they are handled — the full source code is available on github.
Progressive web apps (PWAs)
sw-precache — a node module to generate service worker code that will precache specific resources.
... 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: everything you need to know collection of resources, codelabs and tools you need to build pwas by the team at pwafire.org setting up your progressive web app development environment ...
Getting started - SVG: Scalable Vector Graphics
take a look at the following code.
... <svg version="1.1" baseprofile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="red" /> <circle cx="150" cy="100" r="80" fill="green" /> <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">svg</text> </svg> copy the code and paste it in a file demo1.svg.
...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.
Using templates and slots - Web Components
the following set of code snippets show how to use <slot> together with <template> and some javascript to: create a <element-details> element with named slots in its shadow root design the <element-details> element in such a way that, when used in documents, it is rendered from composing the element’s content together with content from its shadow root—that is, pieces of the element’s content are used to fill in ...
...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>...
Web Components
web components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.
... concepts and usage as developers, we all know that reusing code as much as possible is a good idea.
... 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.
XPath snippets - XPath
this article provides some xpath code snippets—simple examples of how to a few simple utility functions based on standard interfaces from the dom level 3 xpath specification that expose xpath functionality to javascript code.
... the snippets are functions you can use in the real world in your own code.
... example: javascript code with the custom evaluatexpath() utility function // display the last names of all people in the doc var results = evaluatexpath(people, "//person/@last-name"); for (var i in results) alert("person #" + i + " has the last name " + results[i].value); // get the 2nd person node results = evaluatexpath(people, "/people/person[2]"); // get all the person nodes that have addresses in denver resul...
Communicating With Other Scripts - Archive of obsolete content
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.
... in the main add-on code, we have a page-mod that attaches the content script "talk.js" to the right page: var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "http://my-domain.org/listen.html", contentscriptfile: data.url("talk.js") }); the "talk.js" content script uses window.postmessage() to send the message to the page: // content-script (talk.js) window.postmessage("message from ...
Interacting with page scripts - Archive of obsolete content
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.
... in the main add-on code, we have a page-mod that attaches the content script "talk.js" to the right page: var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "http://my-domain.org/listen.html", contentscriptfile: data.url("talk.js") }); the "talk.js" content script uses window.postmessage() to send the message to the page: // talk.js window.postmessage("message from content script", "http://my-doma...
SDK API Lifecycle - Archive of obsolete content
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.
...the sdk team will track usage of deprecated modules on addons.mozilla.org and support developers migrating their code.
querystring - Archive of obsolete content
escape(query) the escape function used by stringify to encodes a string safely matching rfc 3986 for application/x-www-form-urlencoded.
... unescape(query) the unescape function used by parse to decode a string safely.
tabs - Archive of obsolete content
in particular, your code might not work with multiprocess firefox.
... contentscript string,array a string or an array of strings of code to be evaluated in the context.
url - Archive of obsolete content
if base64 is true, the data property is encoded using base-64 encoding.
...if the uri given to the constructor contains base64 parameter, this string is decoded.
content/loader - Archive of obsolete content
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.
... example: the following code creates a wrapper on a hidden frame that reloads a web page in the frame every time the contenturl property is changed: var hiddenframes = require("sdk/frame/hidden-frame"); var { loader } = require("sdk/content/content"); var pageloader = loader.compose({ constructor: function pageloader(options) { options = options || {}; if (options.contenturl) this.contenturl = options.contenturl; this.on('propertychange', this._o...
content/mod - Archive of obsolete content
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.
... 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); // ...
content/symbiont - Archive of obsolete content
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.
...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.
content/worker - Archive of obsolete content
it exports the worker trait, which enables content scripts and the add-on code to exchange messages using the port or postmessage apis.
...but unlike "web workers," these workers run in the same process as web content and browser chrome, so code within workers can block the ui.
dev/panel - Archive of obsolete content
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.
... in the main add-on code: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { class } = require("sdk/core/heritage"); const mypanel = class({ extends: panel, label: "my panel", tooltip: "my new devtool's panel", icon: "./my-icon.png", url: "./my-panel.html", onready: function() { this.postmessage("message from the add-on"); } }); // export the constructor exports.mypanel = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: {...
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"); emit(proc.stdin, 'end'); using child_process in non-jpm extensions // import sdk stuff const commonjs_uri = 'resource://gre/modules/commonjs'; const { require } = cu.import(commonjs_uri + '/toolkit/require.js', {}); var child_process = require('sdk/system/child_process'); // use it in the same way as in the example above ...
test/assert - Archive of obsolete content
throws(block, error, message) assert that a block of code throws the expected exception.
...) { assert.throws(function() { throw new anothererror("custom message"); }, /custom message/, "test throwing a specific exception"); } exports["test exception message 3 expected to fail"] = function(assert) { assert.throws(function() { throw new myerror("another message"); }, /custom message/, "test throwing a specific message"); } parameters block : block the block of code to test.
ui/button/toggle - Archive of obsolete content
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()).
...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.
jpm - Archive of obsolete content
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.
...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".
Displaying annotations - Archive of obsolete content
updating main.js first, initialize an array to hold workers associated with the matcher's content scripts: var matchers = []; in the main function, add the code to create the matcher: var matcher = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('matcher.js')], onattach: function(worker) { if(simplestorage.storage.annotations) { worker.postmessage(simplestorage.storage.annotations); } worker.port.on('show', function(data) { a...
... 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.
Overview - Archive of obsolete content
it identifies page elements which are eligible for annotation, highlights them on mouseover, and tells the main add-on code when the user clicks a highlighted element.
...when the user moves the mouse over an annotated element the matcher tells the main add-on code, which displays the annotation panel.
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...
... updating main.js here's the code to create the panel, which can go in the main function.
Listening for Load and Unload - Archive of obsolete content
you can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main().
... exports.main() your add-on's main.js code is executed as soon as it is loaded.
Logging - Archive of obsolete content
because dom objects aren't available to the main add-on code, the sdk provides its own global console object with most of the same methods as the dom console, including methods to log error, warning, or informational messages.
... console in content scripts you can use the console in content scripts as well as in your main add-on code.
Downloading Files - Archive of obsolete content
var privacy = privatebrowsingutils.privacycontextfromwindow(urlsourcewindow); var hardcodedusername = "ericjung"; var hardcodedpassword = "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, savepasswor...
...d, 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 should implement that as well.
Examples and demos from articles - Archive of obsolete content
for a full compatibility code, see also our crossbrowser possible solution for image preview.
...[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.
JavaScript Debugger Service - Archive of obsolete content
next, we add code to the various hooks.
... learning more a quick and dirty introduction by lei venkman javascript debugger source code firebug service source code jsd architecture (old) ...
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.
... post data to window code to post data to an existing or new window/tab ...
Post data to window - Archive of obsolete content
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.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 ...
Running applications - Archive of obsolete content
this page describes how to run other programs from your chrome javascript code, using mozilla xpcom interfaces.
... var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); file.initwithpath("c:\\myapp.exe"); file.launch(); references nsiprocess nsilocalfile if you need to launch an executable bundled in your xpi, see code snippets:file i/o#getting your extension's folder.
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.
... void viewsource(aobject); methods viewsource opens a viewer to the source code for some document or uri.
xml:base support in old browsers - Archive of obsolete content
before using this code, check if your browser has native support for node.baseuri.
... note however, that this code is not based on a thorough examination of the specs related to forming base uris and could well have a number of errors.
Communication between HTML and your extension - Archive of obsolete content
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.
... // you can use it to make your code executed on certain pages only.
Custom about: URLs - Archive of obsolete content
this change is reflected in the code below.
... this code will work for all versions of firefox 4 and up.
Jetpack Processes - Archive of obsolete content
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.
...sample code for example code, check out the unit tests.
Offering a context menu for form controls - Archive of obsolete content
<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.
...indow.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.istargetaformcontrol(anode)) this.shoulddisplay = true; }; }, false); this code, which is run when the window is opened up, works by replacing the settarget() routine for the prototype of nscontextmenu with one that forces the context menu to display if the target of the menu is a form control.
Useful Mozilla Community Sites - Archive of obsolete content
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.
User Notifications and Alerts - Archive of obsolete content
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.
...you'll have to code around this using tab events in order to know when to re-display your alert.
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 ...
...ng service ghostzilla browser archived version of ghostzilla site from 2005 homebase desktop operating environment for internet computers no longer available hp printer assistant printer utility hall of fame page mentions that this used an embedded version of mozilla at some point but i can't find reference to current status (may still be using mozilla code?) icebrowser java browser sdk uses mozilla rhino --eol'ed in 2009 (jin'sync) office app launcher download page last updated on 12/21/06 kylix compiler and integrated development environment borland discontinued this product.
No Proxy For configuration - Archive of obsolete content
david baron has pointed out that the original pac code in the "classic" tree is written in c++.
... the relevant code lives in nsprotocolproxyservice.cpp.
Using content preferences - Archive of obsolete content
this permits code running within chrome (in other words: extensions and the browser itself, not web sites) to locally save preferences on a per-site basis.
... 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.
Bonsai - Archive of obsolete content
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").
... bonsai source code the source code to the bonsai tool itself is also available, check out the information available at the bonsai project page.
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
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").
...in fact, all win32 api functions dealing with character strings can be added an 'a' to the end to avoid unicode cast errors.
Conclusion - Archive of obsolete content
tinderbox actually keeps track of more than one codebase.
... in particular, it tracks both the main mozilla codebase (the trunk) and a stable branch.
Making a Mozilla installation modifiable - Archive of obsolete content
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.
...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.
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
-image: url("chrome://tinderstatus/content/tb-testfailed.png"); } statusbarpanel#tinderbox-status[status="busted"] { list-style-image: url("chrome://tinderstatus/content/tb-busted.png"); } then we need to create two files in the directory, one called contents.rdf which contains information for the chrome registry about the component being installed and one called install.js that contains the code to install the component.
...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( "...
Dehydra Frequently Asked Questions - Archive of obsolete content
development version of dehydra should work with gcc 4.5 on any c++ codebase.
...where can i find js code for real-life analyses for dehydra?
Dehydra Object Reference - Archive of obsolete content
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.
...code can be annotated with arbitrary user attributes: __attribute__((user("customstring"))).
Dehydra - Archive of obsolete content
dehydra was a lightweight, scriptable, general purpose static analysis tool capable of application-specific analyses of c++ code.
...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.
Content states and the style system - Archive of obsolete content
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.
...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
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.
...if the type of the data is "application/x-unknown-content-type" (another magic type), this is where nsunknowndecoder would be instantiated.
Creating a Help Content Pack - Archive of obsolete content
(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.
...for example, the following code uses a datasource outside the content pack you have created to include the article in a table of contents: <rdf:li> <rdf:description nc:panelid="toc" nc:datasources="chrome://help/locale/help-toc.rdf chrome://foo/locale/help/glossary.rdf"/> </rdf:li> each of the different data source types (toc, index, gl...
Helper Apps (and a bit of Save As) - Archive of obsolete content
decides whether the data should be content-decoded (based on some not-so-great heuristics).
...checks happen in onstartrequest, in the helper app dialog, and as a last ditch in the launching code.
Hidden prefs - Archive of obsolete content
address book "get map" button pref ("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.
importUserCertificates - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
...the response is base-64 encoded.
JavaScript crypto - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
... web sites which use ssl clientauth login could use the following code to refresh the page on token insertions and removals: <!doctype html> <p>...
Jetpack Snippets - Archive of obsolete content
bits of code that may come in handy.
...using firebug lite in a slidebar jetpack.future.import("slidebar");jetpack.slidebar.append({ html: <html><head></head><body> <p>some slidbar you want to debug</p> <a href="javascript:console.log('hello!')">test</a> <script><![cdata[ //firebug lite bookmarklet code: var firebug=document.createelement('script'); firebug.setattribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); document.body.appendchild(firebug); (function(){if(window.firebug.version){firebug.init();}else{settimeout(arguments.callee);}})();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebug onselect: ...
statusBar - Archive of obsolete content
you can find the complete sourcecode in the status-bar-panel.js file in your jetpack repository.
...syntax jetpack.statusbar.append(options); possible options are: url width (string/length) the width of the panel-item html (string) the html code which will be used inside the item onload (event) this event fires when the item was appended.
Microsummary XML grammar reference - Archive of obsolete content
uments is: http://www.mozilla.org/microsummaries/0.1 all elements in a microsummary generator document should be in this namespace except the descendants of the <template> element, which should be in the xslt namespace: http://www.w3.org/1999/xsl/transform the <generator> element the <generator> element is the root tag for all microsummary generators, and should contain the remainder of the xml code describing the generator.
...only relevant for generators dynamically created by firefox code and extensions.
Mozilla Application Framework - Archive of obsolete content
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.
... 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.
Overview of how downloads work - Archive of obsolete content
are all part of the second codepath.
... this document describes both codepaths (see below for the second one).
Porting NSPR to Unix Platforms - Archive of obsolete content
pthreads nspr has relatively orthogonal source code in the thread management, thread synchronization, and i/o area.
...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.
Priority Content - Archive of obsolete content
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.
...they are dependant on some code that cannot be integrated in the page.
Frequently Asked Questions - Archive of obsolete content
why does mozilla show source code/gibberish instead of svg?
... if source code is displayed without a gray area at the top, or if you just see gibberish, then the problem is server misconfiguration.
open - Archive of obsolete content
valid file types are text, binary and unicode.
...unicode indicates ucs-2 files.
File object - Archive of obsolete content
currently "ascii" (ascii), "binary" (utf-8) or "unicode" (ucs-2).
...url is uri-encoded.
Table Layout Regression Tests - Archive of obsolete content
subject overview changes in layout, parser and content code can have unintended side effects, also known as regressions.
... adding new regression tests once you have checked in the code: please add your testcase for the bug to the regression tests.
Tamarin Acceptance Test Template - Archive of obsolete content
* * the original code is [open source virtual machine.].
... * * the initial developer of the original code is * adobe system incorporated.
Running Tamarin acceptance tests - Archive of obsolete content
ill print a period (.) for each test run regardless of results, then print the test run summary when finished --ascargs= : additional arguments to pass to asc.jar --vmargs= : additional arguments to pass to avmshell --random : run tests in random order --timeout : max time for testrun --verify : run a verify pass instead of running abcs --verifyonly : run a -dverifyonly pass: only checks test exitcode (only works with debugger vms) testing the android shell the instructions above apply to running tests on an android device as well, but with a few differences.
...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...
Tamarin mercurial commit hook - Archive of obsolete content
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.
Treehydra Manual - Archive of obsolete content
instead of representing code in "easy" form like dehydra, treehydra relies on gimple, the gcc internals "middle-end" intermediate representation.
...for now, the best way to learn gimple is to look at existing code as there is little newbie documentation to be had.
URIs and URLs - Archive of obsolete content
an escaped character is encoded as a character triplet, consisting of the percent character "%" followed by the two hexadecimal digits representing the octet code.
...likewise, a uri must be separated into its components before the escaped characters within those components can be safely decoded.
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
however, since it affects the portability of code, it was deemed prudent to include a short memo describing the issue.
... original document information author: larryh@netscape.com, wan teh chang last updated date: december 1, 2004 this note is about writing win16-portable code that uses nspr threads, probably not interesting to today's developers ...
Venkman Internals - Archive of obsolete content
notes on venkman source code.
... venkman-msg.js localization code, reads venkman.properties from a subdirectory of "locale" and injects variables.
Video presentations - Archive of obsolete content
mozilla is actively working to produce video presentations that can help you learn how the mozilla codebase works and how to take advantage of its technology in your own applications and extensions.
... architecture these presentations provide an architectural overview of the codebase.
Event Handlers - Archive of obsolete content
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.
... key events support the charcode and keycode attributes.
Windows stub installer - Archive of obsolete content
where does the windows stub installer code reside?
... 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?
copy - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
dirCreate - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
dirRemove - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
dirRename - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
execute - Archive of obsolete content
(ignored on mac os) returns an integer error code.
... for a list of possible values, see return codes.
macAlias - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
move - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
remove - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
rename - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
windowsRegisterServer - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
windowsShortcut - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
addDirectory - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
addFile - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
deleteRegisteredFile - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
gestalt - Archive of obsolete content
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.
...the format depends on the select code specified in the selector parameter.
logComment - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
registerChrome - Archive of obsolete content
returns an integer error code.
... for a list of possible values, see return codes.
Methods - Archive of obsolete content
getlasterror returns the most recent non-zero error code.
... reseterror resets a saved error code to zero.
dir - Archive of obsolete content
ArchiveMozillaXULAttributedir
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.
...this is reverse of the order in which they appear in the xul code.
oncommand - Archive of obsolete content
« xul reference home oncommand type: script code this event handler is called when the command is activated.
... example 1: in-line code <button label="click me" oncommand="alert('hi')"/> example 2: function with source argument <button label="click me" oncommand="dosomeprocessing(event.target)"/> and here is the definition of the function: function dosomeprocessing(source) { alert("source: " + source); return true; } see also command element ...
Deprecated and defunct markup - Archive of obsolete content
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.
How to implement a custom XUL query processor component - Archive of obsolete content
a few explanatory notes: we are using a the getbindingfor rather than getbindingobjectfor to simplify the code.
... we are not handling any datasources, but instead hard code the datasource in the component.
Extensions - Archive of obsolete content
the code above will append the new item at the end of the context menu.
... 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.
OpenClose - Archive of obsolete content
a simple example: somemenu.open = true; this single line of code will open a menu referenced by the variable 'somemenu'.
...when an menu item is selected, it fires a command event so that code may be used to perform an action.
Panels - Archive of obsolete content
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.
...naturally, this function would also include code to start the search operation.
PopupEvents - Archive of obsolete content
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.
...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.
Additional Template Attributes - Archive of obsolete content
you might also use these attributes just to make the code clearer when using very complex queries.
...this may make the code clearer as to its function.
Static Content - Archive of obsolete content
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.
...the result will be a xul display that looks just like the code above, except that the template and its content is hidden.
Template and Tree Listeners - Archive of obsolete content
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.
...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.
Things I've tried to do with XUL - Archive of obsolete content
(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.
...from my reading of the code, just height="0" should work, but it doesn't seem to.
Adding Style Sheets - Archive of obsolete content
some of the styles in the code above have been removed.
...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.
Broadcasters and Observers - Archive of obsolete content
this is a useful way to simplify the amount of code you need to write.
... 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.
Creating a Window - Archive of obsolete content
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.
... the extension developer's extension contains an xul editor that allows you to type in xul code and see the results in real-time from within mozilla!
Creating a Wizard - Archive of obsolete content
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.
Creating an Installer - Archive of obsolete content
the second argument is a result code.
...if the result is non-zero, an error occured and the value is an error code.
Introduction - Archive of obsolete content
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.
...mozilla applications such as firefox provide an extension manager which allows packages to be installed without having to write a lot of complex code.
Modifying the Default Skin - Archive of obsolete content
(although the underlying code for mozilla calls them skins and the user interface calls them themes, they're both referring to the same thing).
... 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.
XPCOM Examples - Archive of obsolete content
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.
... code snippets http://kb.mozillazine.org/category:xpcom_example_code next, we'll look at how to create trees.
Using Remote XUL - Archive of obsolete content
for that we need to add javascript code.
...</window> the code to load the urls is simple.
XUL Changes for Firefox 1.5 - Archive of obsolete content
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.
...this has been fixed in firefox 1.5 and all code depending on this non zero-based behaviour should be changed.
XUL Coding Style Guidelines - Archive of obsolete content
javascript code shall be moved out of xul.
...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.
button - Archive of obsolete content
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.
...this is reverse of the order in which they appear in the xul code.
image - Archive of obsolete content
ArchiveMozillaXULimage
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.
menulist - Archive of obsolete content
the command event may be used to execute code when the menulist selection changes.
... oncommand type: script code this event handler is called when the command is activated.
preference - Archive of obsolete content
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.
... int an integer string a string unichar a unicode string wstring a localized string.
scale - Archive of obsolete content
ArchiveMozillaXULscale
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.
...this is reverse of the order in which they appear in the xul code.
tree - Archive of obsolete content
ArchiveMozillaXULtree
onselect type: script code this event is sent to a tree when a row is selected, or whenever the selection changes.
...ee.view.getcellvalue(i, column) == 'true') arr.push(i); } return arr; } to get the text value for a specific column (for example column 'age') from the currently focused row in the tree: var t = document.getelementbyid('mytree'); document.title = t.view.getcelltext(t.currentindex,t.columns.getnamedcolumn('age')); to select the checkbox and display the cell's text value, you can use code like the following.
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...
...ge> <wizardpage> <label value="that is the correct secret code."/> </wizardpage> </wizard> attributes activetitlebarcolor type: color string specify background color of the window's titlebar when it is active (foreground).
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
because nobody has written that code yet!
... where is the source code?
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
because nobody has written that code yet!
... where is the source code?
XULRunner FAQ - Archive of obsolete content
because nobody has written that code yet!
... where is the source code?
XULRunner Hall of Fame - Archive of obsolete content
build instructions komodo edit a multi-language code development tool.
...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.
Windows and menus in XULRunner - Archive of obsolete content
building on the simple window code, here is what xul menus and toolbars look like: <?xml version="1.0"?> <?xml-stylesheet href="chrome://basicapp/skin/main.css" type="text/css"?> <!doctype window system "chrome://basicapp/locale/main.dtd"> <window id="main" title="&title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="main.js"/> <toolbox> <menubar id="menubar"> <menu i...
...we could hard-code the images in the xul file itself, but css is a better practice.
XUL Explorer - Archive of obsolete content
it has a list of code snippets (small fragments of xul or javascript) that can be quickly inserted into the editor.
... installs latest version: install (windows): xulexplorer-1.0a1pre.en-us.win32.exe 6.6mb install (mac): xulexplorer-1.0a1pre.en-us.mac.dmg 9.3mb install (linux): xulexplorer-1.0a1pre.en-us.linux-i686.tar.bz2 8.4mb contributing source code in svn bugzilla (for bugs and suggestions) open bugs, enter new bug blog posts xul explorer - updated (1.0a1pre) xul explorer 0.4 xul explorer 0.3 xul explorer 0.2 exploring xul ...
calICalendarViewController - Archive of obsolete content
interface code [scriptable, uuid(1f783898-f4c2-4b2d-972e-360e0de38237)] interface calicalendarviewcontroller : nsisupports { void createnewevent (in calicalendar acalendar, in calidatetime astarttime, in calidatetime aendtime); void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); void deleteoccurrence ...
... related interfaces calicalendarview calidecoratedview example code var myviewcontroller = { queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.calicalendarviewcontroller) && !aiid.equals(components.interfaces.nsisupports)) { throw components.results.ns_error_no_interface; } return this; }, createnewevent: function (acalendar, astarttime, aendtime) { // if we're given both ...
calIFileType - Archive of obsolete content
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.
...related interfaces caliimporter caliexporter example code see calhtmlexport.js.
xbDesignMode.js - Archive of obsolete content
* * the original code is netscape cross browser design mode code.
... * * the initial developer of the original code is * netscape communications corporation.
2006-11-03 - Archive of obsolete content
there are some code example given and also further discussion on lastmodifieddate.
... 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
discussions violation of smtp protocol in thunderbird hector reports two bugs: thunderbird ignores the smtp protocol state machine by ignoring the 501 response codes.
...guenter has provided some sample code using the 'mailto:' method.
2006-11-03 - Archive of obsolete content
piling using cygwin on win32 he gets the following error no such file or directory1: /cygdrive/c/mozilla/mail/config/mozconfig client.mk:339: /cygdrive/c/mozilla/.mozconfig.mk: no such file or directory he claims that the file ".mozconfig" exists in /cygdrive/c/mozilla/mail/config/mozconfig the disable-crypto cause problem originally posted on november 2nd: gxk is building minimo using the code base from sept.
... 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.
2006-11-24 - Archive of obsolete content
luke is migrating all of his code to compile with vc8 and is having some problems.
..."component returned failure code: 0x80570016 (ns_error_xpc_gs_returned_failure) [nsijscid.getservice]" nsresult: "0x80570016 (ns_error_xpc_gs_returned_failure)" location: "js frame :: chrome://modzilla/content/js/pkg_zillacom.js :: <top_level> :: line 1202" data: no] he is running xulrunner v1.8.0.4.
2006-09-22 - Archive of obsolete content
summary: mozilla.dev.i18n - feb 2nd - sep 22nd, 2006 announcements testing a dummy greek bon echo nsis installer bug #69230: accelerators should not be affected by keyboard group/level proposal of code changes for l10n in firefox 3 discussions thai language support: how can we add thai as an official localized build?
... thai issue for 2.0 timeframe arabic support & uniscribe: details nstextframe: re-design and impact on i18n native unicode converter editing and selection: should editing and selection operate on grapheme clusters?
2006-10-13 - Archive of obsolete content
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.
2006-11-10 - Archive of obsolete content
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.
2006-12-01 - Archive of obsolete content
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.
2006-11-24 - Archive of obsolete content
a user writes that the licensing incompatibilities between gpl and mpl would prevent java code to be added in mozilla.
... frank hecker writes: the possibility of having a gpl-only mozilla code would cause problems such as people who want to distribute mozilla based products with: non-gpl compatible extensions free proprietary extensions such as flash player using trademarks such as logos ...
NPN_DestroyStream - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPN_GetAuthenticationInfo - Archive of obsolete content
if unsuccessful, the function returns an error code.
... for possible values, see error codes.
NPN_GetURL - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPN_GetURLNotify - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPN_GetValueForURL - Archive of obsolete content
if unsuccessful, the function returns an error code.
... for possible values, see error codes.
NPN NewStream - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPN_PostURL - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPN_PostURLNotify - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPN_SetValueForURL - Archive of obsolete content
if unsuccessful, the function returns an error code.
... for possible values, see error codes.
NPP_Destroy - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NPP_DestroyStream - Archive of obsolete content
if unsuccessful, the plug-in should return an error code.
... for possible values, see error codes.
NPP_GetValue - Archive of obsolete content
if unsuccessful, the function returns an error code.
... for possible values, see error codes.
NPP_New - Archive of obsolete content
if unsuccessful, the function returns an error code.
... for possible values, see error codes.
NPP_SetValue - Archive of obsolete content
if unsuccessful, the function should return the most relevant npapi error code.
... for possible values, see error codes.
NPP_SetWindow - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
NP_GetValue - Archive of obsolete content
if unsuccessful, the function returns an error code.
... for possible values, see error codes.
NP_Initialize - Archive of obsolete content
if unsuccessful, the plug-in is not loaded and the function returns an error code.
... for possible values, see error codes.
Samples and Test Cases - Archive of obsolete content
npapi plugin samples collections of npapi plugin samples can be found in the seamonkey source code at /modules/plugin/sdk/samples.
...however, even if one cannot build the samples they can still be very valuable as code references.
Plugins - Archive of obsolete content
there are also some code generation tools that may be helpful.
... writing a plugin for mac os x learn how to write a plugin for mac os x; a template xcode project is provided.
Building a Theme - Archive of obsolete content
if you were to install an extension it would be 2 (see install manifests#type for other type codes).
... 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, "/"!
Using the W3C DOM - Archive of obsolete content
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.
... spanel.textcontent == 'string') { spanel.textcontent = 'some gall'; } else if (typeof spanel.innertext == 'string') { spanel.innertext = 'some gall'; // if neither are supported, use other dom methods } else { while (spanel.firstchild) { spanel.removechild(spanel.firstchild); } spanel.appendchild(document.createtextnode('some gall')); } </script> </body> the first part of the code gets a reference to the element.
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
to xul / chrome code).
...this can be useful for adapting application skins and other chrome code depending on the user's operating system version.
-moz-windows-theme - Archive of obsolete content
to xul / chrome code).
... 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.
New in JavaScript 1.3 - Archive of obsolete content
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).
...ototype.getutcminutes() date.prototype.getutcseconds() date.prototype.getutcmilliseconds() date.prototype.toutcstring() date.prototype.setutcfullyear() date.prototype.setutcmonth() date.prototype.setutcdate() date.prototype.setutchours() date.prototype.setutcminutes() date.prototype.setutcseconds() date.prototype.setutcmilliseconds() other new features strict equality operators unicode support a javascript console was introduced.
New in JavaScript 1.8.5 - Archive of obsolete content
bug 492849 object.seal() prevents other code from deleting properties of an object.
...bug 492845 object.freeze() freezes an object: other code can't delete or change any properties.
New in JavaScript 1.8 - Archive of obsolete content
your code ...
... 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.
handler.enumerate() - Archive of obsolete content
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.
JSException - Archive of obsolete content
lass jsexception extends runtimeexception java.lang.object | +----java.lang.throwable | +----java.lang.exception | +----java.lang.runtimeexception | +----netscape.javascript.jsexception description jsexception is an exception which is thrown when javascript code returns an error.
... source the string containing the javascript code being evaluated.
JSObject - Archive of obsolete content
when the jsobject is passed back to javascript, the object is unwrapped and can be used by javascript code.
...the expression is a string of javascript source code which will be evaluated in the context given by "this".
background-size - Archive of obsolete content
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.
Building Mozilla XForms - Archive of obsolete content
the following table gives you an overview of which version you want to build: firefox version gecko/toolkit version source code notes status firefox 2.0 gecko 1.8.1 cvs, branch mozilla_1_8_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 fir...
...firefox 3.5 and up: get the source code if you want to build xforms for firefox up to 3.0, you already have the required source code, it's part of your cvs checkout.
XForms Custom Controls - Archive of obsolete content
so you can always refer to our source code to get some great examples of how xforms controls can be written.
...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.
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 ...
... partial 330557; 11.9.7 serialization as multipart/form-data supported 11.9.8 serialization as application/x-www-form-urlencoded supported 11.10 replacing data with the submission response partial @replace with value of 'text' not supported 11.11 integration with soap supported g.
Archive of obsolete content
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.
... table reflow internals key: tamarin tracing build documentation the following instructions are for obtaining and building the tamarin tracing source code.
Game monetization - Game development
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.
2D collision detection - Game development
} rect code <div id="cr-stage"></div> <p>move the rectangle with arrow keys.
... playable code <div id="cr-stage"></div> <p>move the circle with arrow keys.
3D collision detection - Game development
in javascript: function ispointinsidesphere(point, sphere) { // we are using multiplications because is faster than calling math.pow var distance = math.sqrt((point.x - sphere.x) * (point.x - sphere.x) + (point.y - sphere.y) * (point.y - sphere.y) + (point.z - sphere.z) * (point.z - sphere.z)); return distance < sphere.radius; } the code above features a square root, which can be expensive to calculate.
... 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
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.
...this can be a more pleasant working environment if you are not someone who likes to code.
WebVR — Virtual Reality for the Web - Game development
for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof hmdvrdevice) { ghmd = devices[i]; break; } } if (ghmd) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof positionsensorvrdevice && devices[i].hardwareunitid === ghmd.hardwareunitid) { gpositionsensor = devices[i]; break; } } } }); this code will loop through the available devices and assign proper sensors to the headsets — the first devices array contains the connected devices, and a check is done to find the hmdvrdevice, and assign it to the ghmd variable — using this you can set up the scene, getting the eye parameters, setting the field of view, etc.
...for example, the below code outputs position information on the screen: function setview() { var posstate = gpositionsensor.getstate(); if(posstate.hasposition) { pospara.textcontent = 'position: x' + roundtotwo(posstate.position.x) + " y" + roundtotwo(posstate.position.y) + " z" + roundtotwo(posstate.position.z); xpos = -posstate.position.x * wid...
Tools for game development - Game development
emscripten an llvm to javascript compiler; with emscripten, you can compile c++ and other languages that can compile to llvm bytecode into high-performance javascript.
... gecko profiler the gecko profiler extension lets you profile your code to help figure out where your performance issues are so that you can make your game run at top speed.
Animations and tweens - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson14.html.
... 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.
Bounce off the walls - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson06.html.
... 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.
Player paddle and controls - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson07.html.
... 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?
The score - Game development
you can find the source code as it should look after completing this lesson at gamedev-phaser-content-kit/demos/lesson11.html.
... 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?
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.
... learn more list of http response codes advice for beginners on avoiding 404 errors ...
502 - MDN Web Docs Glossary: Definitions of Web-related terms
an http error code meaning "bad gateway".
... learn more list of http response codes ...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
advantages of data abstraction helps the user to avoid writing low level code.
... avoids code duplication and increases reusability.
Cipher - MDN Web Docs Glossary: Definitions of Web-related terms
in cryptography, a cipher is an algorithm that can encode cleartext to make it unreadable, and to decode it back.
... they also are classified according to how their keys are handled: symmetric key algorithms use the same key to encode and decode a message.
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.
... a typical cipher suite looks like ecdhe_rsa_with_aes_128_gcm_sha256 or ecdhe-rsa-aes128-gcm-sha256, indicating: ecdhe (elliptic curve diffie-hellman ephemeral) for key exchange rsa for authentication aes-128 as the cipher, with galois/counter mode (gcm) as the block cipher mode of operation sha-256 as the hash-based message authentication code (hmac) learn more mozilla recommended cipher suite choices for tls ...
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.
... learn more general knowledge condition on wikipedia control flow on mdn learn about it making decisions in your code — conditionals control flow and error handling in javascript on mdn ...
Cross-site scripting - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
cryptography, or cryptology, is the science that studies how to encode and transmit messages securely.
... cryptography designs and studies algorithms used to encode and decode messages in an insecure environment, and their applications.
Git - MDN Web Docs Glossary: Definitions of Web-related terms
git is a free, open-source, distributed source code management (scm) system.
... it facilitates handling code bases with distributed development teams.
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
houdini gives developers access to the css object model (cssom), enabling developers to write code the browser can parse as css.
...houdini code doesn't wait for that first rendering cycle to be complete.
Idempotent - MDN Web Docs Glossary: Definitions of Web-related terms
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.
...row, the client gets the same results: get /pagex http/1.1 get /pagex http/1.1 get /pagex http/1.1 get /pagex http/1.1 post /add_row http/1.1 is not idempotent; if it is called several times, it adds several rows: post /add_row http/1.1 post /add_row http/1.1 -> adds a 2nd row post /add_row http/1.1 -> adds a 3rd row delete /idx/delete http/1.1 is idempotent, even if the returned status code may change between requests: delete /idx/delete http/1.1 -> returns 200 if idx exists delete /idx/delete http/1.1 -> returns 404 as it just got deleted delete /idx/delete http/1.1 -> returns 404 learn more general knowledge definition of idempotent in the http specification.
SCM - MDN Web Docs Glossary: Definitions of Web-related terms
scm (source control management) is a system for managing source code.
...a programmer can modify source code files without being afraid of editing out useful stuff, because a scm keeps track of how the source code has changed and who made the changes.
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
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.
TLD - MDN Web Docs Glossary: Definitions of Web-related terms
iana today distinguishes the following groups of top-level domains: country-code top-level domains (cctld) two-character domains established for countries or territories.
... internationalized country code top-level domains (idn cctld) cctlds in non-latin character sets (e.g., arabic or chinese).
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
each unit capable of executing code is called a thread.
... the main thread is the one used by the browser to handle user events, render and paint the display, and to run the majority of the code that comprises a typical web page or app.
UTF-8 - MDN Web Docs Glossary: Definitions of Web-related terms
utf-8 is backward-compatible with ascii and can represent any standard unicode character.
... learn more general knowledge utf-8 on wikipedia faq about utf-8 on unicode website ...
WebIDL - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Whitespace - MDN Web Docs Glossary: Definitions of Web-related terms
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
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.
... 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.
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
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.
minification - MDN Web Docs Glossary: Definitions of Web-related terms
minification can include the removal of code comments, white space, and unused code, as well as the shortening of variable and function names.
... 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.
Assessment: Accessibility troubleshooting - Learn web development
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.
...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.
What is accessibility? - Learn web development
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.
...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.
A cool-looking box - Learn web development
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.
...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.
Cascade and inheritance - Learn web development
playing with code really is the best way to get to grips with html and css.
... 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.
Fundamental CSS comprehension - Learn web development
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.
...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.
Pseudo-classes and pseudo-elements - Learn web development
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-element-name note: some early pseudo-elements used the single colon syntax, so you may sometimes see this in code or examples.
Floats - Learn web development
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.
Supporting older browsers - Learn web development
there are cases, however, when the fallback code will need to include something that the new browsers will also interpret.
...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.
What is CSS? - Learn web development
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 means that the code has been written to turn the instruction in our css file into something that can be output to the screen.
How do you make sure your website works properly? - Learn web development
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!
How much does it cost to do something on the Web? - Learn web development
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.
What software do I need to build a website? - Learn web development
third-party editors often come with extra features, including syntax coloring, auto-completion, collapsible sections, and code search.
... here is a short list of editors: operating system built-in editor third-party editor windows notepad notepad++ 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 edito...
Basic native form controls - Learn web development
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).
... button buttons that have no automatic effect but can be customized using javascript code.
HTML forms in legacy browsers - Learn web development
if the code breaks, the content and the basic functionalities must remain accessible and usable.
...test your code with legacy browsers to see how they actually perform.
How to structure a web form - Learn web development
he html <head>: <link href="payment-form.css" rel="stylesheet"> next, create your form by adding the outer <form> element: <form> </form> inside the <form> tags, add a heading and paragraph to inform users how required fields are marked: <h1>payment form</h1> <p>required fields are followed by <strong><abbr title="required">*</abbr></strong>.</p> next we'll add a larger section of code into the form, below our previous entry.
...add this code to your form: <section> <h2>contact information</h2> <fieldset> <legend>title</legend> <ul> <li> <label for="title_1"> <input type="radio" id="title_1" name="title" value="k" > king </label> </li> <li> <label for="title_2"> <input type="radio" id="title_2" name="title" value="q"> ...
How the Web works - Learn web development
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.
...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.
Use HTML to solve common problems - Learn web development
LearnHTMLHowto
how to create a list of items with html how to stress or emphasize content how to indicate that text is important how to display computer code with html how to annotate images and graphics how to mark abbreviations and make them understandable how to add quotations and citations to web pages how to define terms with html hyperlinks one of the main reasons for html is making navigation easy with hyperlinks, which can be used in many different ways: how to create a hyperlink how to create a table of contents with html image...
...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.
Asynchronous JavaScript - Learn web development
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.
... 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.
Client-side web APIs - Learn web development
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?
JavaScript — Dynamic client-side scripting - Learn web development
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.
...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.
JavaScript performance - Learn web development
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.
Multimedia: video - Learn web development
if not, there are online tools, such as ffmpeg (discussed in section below), that encode, decode, convert, and perform other optimization functions.
... <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.
Server-side website programming first steps - Learn web development
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.
... assessments this "first steps" module doesn't have any assessment because we haven't yet shown you any code.
Ember resources and troubleshooting - Learn web development
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.
...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.
Routing in Ember - Learn web development
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.
React resources - Learn web development
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.
Adding a new todo form: Vue events, methods, and models - Learn web development
however, we can't update our list of items without manually changing our code!
...however, the exact event and attribute combination varies depending on input types and will take more code than just using the v-model shortcut.
Understanding client-side web development tools - Learn web development
in this article we'll introduce the case study, set up our development environment, and set up our code transformation tools.
...we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process.
Embedding API for Accessibility
be aware that in debug builds, this can cause a great number of assertions (bug 71598) to use prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_true /* or pr_false */); prefs->setintpref("int.pref.name", newvalue); prefs->setcharpref("string.pref.name", newcharstarvalue); to manually add a pref to your settings, add a line like the following to your prefs.js: user_pref("accessibility.browsew...
... 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
oming can be controlled via hotkeys ctrl+plus and ctrl+minus the prefs are at preferences, appearances, fonts there is also a hidden pref line that can be added to prefs.js, if you just want to change the minimum font size for a certain font: user_pref("font.minimum-size.x-western", newfontsizeinpoints); 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 4.2 configure font family.
...unforutunately, some are hard coded.
Theme concepts
for example, the following code, from the dynamic theme example defines the content for the day and night elements of the dynamic theme: const themes = { 'day': { images: { theme_frame: 'sun.jpg', }, colors: { frame: '#cf723f', tab_background_text: '#111', } }, 'night': { images: { theme_frame: 'moon.jpg', }, colors: { frame: '#000', tab_background_text: '#fff', ...
... } } }; the theme.theme object is then passed to theme.update() to change the header theme, as in this code snippet from the same example: function settheme(theme) { if (currenttheme === theme) { // no point in changing the theme if it has already been set.
Chrome registration
this allows translators to plug in a different chrome package to translate an application without altering the rest of the source code.
... 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.
Continuous Integration
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.
... builds b - normal build jobs; these jobs perform compilation and some compiled-code tests (e.g., 'make check').
Creating a Login Manager storage module
you should start with the existing code if you want to implement that in your extension.
... sample javascript implementation the following code snippet is a javascript component that implements a dummy nsiloginmanagerstorage interface.
Debugging a hang on OS X (Archived)
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.
... 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).
Simple SeaMonkey build
oconf213 glibc-static libstdc++-static yasm wireless-tools-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.
Simple Sunbird build
buntu linux: sudo apt-get build-dep sunbird sudo apt-get install mercurial libasound2-dev libcurl4-openssl-dev libnotify-dev libiw-dev autoconf2.13 cvs fedora linux: sudo yum groupinstall 'development tools' 'development libraries' 'gnome software development' sudo yum install mercurial autoconf213 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.
Callgraph
the callgraph project is intended to produce a complete callgraph covering c and c++ code within mozilla.
...for instance, given the c++ code: int foo() { return good(); } int good() { return evil() ?
Interface Compatibility
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.
SVG Guidelines
these rules are based on some real examples seen in mozilla's code.
...however, there are some utilities that cover parts of this document: mostly complete command line tool: https://github.com/svg/svgo alternatives to svgo: https://github.com/razrfalcon/svgcleaner https://github.com/scour-project/scour gui for command line tool (use with "prettify code" and "remove <title>" options on): https://jakearchibald.github.io/svgomg/ good alternative to svgo/svgomg: https://petercollingridge.appspot.com/svg-editor fixes the excessive number precision: https://simon.html5.org/tools/js/svg-optimizer/ converts inline styles to svg attributes: https://www.w3.org/wiki/svgtidy raphaeljs has a couple of utilities that may be useful: raphael.js ...
Frame script environment
atob() base64 decode.
... btoa() base64 encode.
Limitations of frame scripts
you can change this default in the code you use to register the about: uri.
... 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.
Frame script environment
atob() base64 decode.
... btoa() base64 encode.
Frame script loading and lifetime
this line of code loads a frame script into the currently selected tab.
... your add-on is upgraded, and the new code loads new frame scripts.
Process scripts
when you need to run code in the content process in order to access web content, then you should use frame scripts.
...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) { ...
Chrome-only CSS reference
MozillaGeckoChromeCSS
this page lists css properties that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg.
...it only works in chrome code, and only on mac os x.:-moz-lwthemethe :-moz-lwtheme pseudo-class matches in chrome documents when the root element's lightweightthemes attribute is true and a theme is selected.:-moz-lwtheme-brighttextthe :-moz-lwtheme-brighttext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweight theme with a bright text color is selected.:-moz-lwtheme-darktextthe :-moz-lwtheme-darktext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweigh...
Extending a Protocol
we will try to compile our code as we go, noting what we need to do along the way.
... defining echoparent.h like before, create ./dom/ipc/echoparent.h, and code it as follows - the inline comments describe what's going on.
Implementing Download Resuming
the front-end code can then notify the user of this, and offer to resume the download.
... 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.
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.
AsyncShutdown.jsm
// 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.
Dict.jsm
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.
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.
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.
FxAccountsOAuthClient.jsm
first and only argument is an object that has "state" and "code" properties.
...parameters 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(); ...
FxAccountsProfileClient.jsm
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 of the error fxaccountsprofileclienterror code number status code of the request errno number error number error string error description message string error message ...
Geometry.jsm
the geometry.jsm javascript code module provides routines for performing common geometry operations on points and rectangles.
...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.
Http.jsm
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.
...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.
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.
JavaScript OS.Constants
using os.constants from the main thread to initialize os.constants for use in the main thread, add the following snippet to your code: components.classes["@mozilla.org/net/osfileconstantsservice;1"].
...useful, for instance, to access the platform code from javascript in conjunction with js-ctypes.
Log.jsm
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.
PromiseUtils.jsm
the promiseutils.jsm javascript code module offers some useful functions related to dom promise.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promiseutils.jsm"); method overview deferred defer(); methods defer() creates a new pending promise and provides methods to resolve or reject this promise.
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.
Task.jsm
the task.jsm javascript code module implements a subset of task.js to make sequential, asynchronous operations simple, using the power of javascript's yield operator.
... to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/task.jsm"); introduction for an introduction to tasks, you may start from the task.js documentation, keeping in mind that only the core subset is implemented in this module.
openLocationLastURL.jsm
(bug 953124) the openlocationlasturl.jsm javascript code module lets you set and retrieve the url most recently opened using the "open location" option in the file menu.
... to use this, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/openlocationlasturl.jsm"); once you've imported the module, you can then use the openlocationlasturl object it exports.
L10n Checks
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.
...you pass the path to the xpi file (optionally) followed by the locale codes of the locales you want to compare.
Mozilla Content Localized in Your Language
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.
... 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.
Localizing extension metadata on addons.mozilla.org
localization codes amo offers 33 localizations, including english.
... here is a list of the codes: arabic (ar), catalan (ca), czech (cs), danish (da), german (de), greek (el), basque (eu), spanish (es-es), farsi (fa), finnish (fi), french (fr), gaeilge (ga-ie), hebrew (he), hungarian (hu), indonesian (id), italian (it), japanese (ja), korean (ko), mongolian (mn), dutch (nl), polish (pl), brazilian portuguese (pt-br), european portuguese (pt-pt), romanian (ro), russian (ru), slovakian (sk), albanian (sq), swedish (sv-se), ukrainian (uk), vietnamese (vi), chinese (zh-cn) and taiwanese (zh-tw).
Localization sign-off reviews
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.
Setting up the infrastructure
by default the script looks for gettext calls in *thtml or *.php files, so you may need to adjust that to your code.
... review your code following the web applications localizability guidelines.
Web Localizability
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.
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.
GC and CC logs
the way to set environment variables depends on the test harness, or you can modify the code in nscyclecollector to set that directly.
... to set the environment variable, find the buildbrowserenv method in the python file for the test suite you are interested in, and add something like this code to the file: browserenv["moz_cc_log_directory"] = os.environ["moz_upload_dir"] browserenv["moz_cc_log_shutdown"] = "1" analyzing gc and cc logs there are numerous scripts that analyze gc and cc logs on github.
JS::PerfMeasurement
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.
Power profiling overview
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.
...with stack traces that clearly pinpoint specific parts of the code as being responsible.
Refcount tracing and balancing
this results in slower code, but at least you get some data about where the leaks might be occurring from.
...more likely, it indicates that one addref() is cancelled by another release() somewhere else in the code.
dtrace
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.
A brief guide to Mozilla preferences
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.
...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.
javascript.options.showInConsole
the preference javascript.options.showinconsole controls whether errors or warnings in chrome code are shown in the error console.
... type:boolean default value: false (true in debug builds) exists by default: yes application support:firefox 1.0 status: active introduction:2002-02-26 bugs: bug 125181 bug 337875 values false only errors and warnings from content code are shown.
Preferences
using preferences from application code firefox 6 introduced static functions for accessing preferences efficiently from within application code.
... examples code snippets preference-related code snippets.
Crash reporting
this system is combination of projects: google breakpad client and server libraries mozilla-specific crash reporting user interface and bootstrap code socorro collection and reporting server where did my crash get submitted?
... see also understanding crash reports a guide to searching crash reports crash-stats crash pings (telemetry) and crash reports (socorro/crash stats) building firefox with debug symbols environment variables affecting crash reporting in-code documentation crash reporter crash manager crash ping ...
JSHydra
jshydra is a static analysis tool that is capable of performing analysis of general javascript code.
... it is inspired by the dehydra and treehydra tools, which can perform similar tasks in c++ code.
Leak And Bloat Tests
provide a consistent number from build to build where no source code has changed.
...code locations the files specific to leak and bloat testing are be stored in: http://mxr.mozilla.org/comm-central/source/mailnews/test/performance these files consist of: overlays (used to provide the hooks for the javascript): bloat/bloataddroverlay.xul bloat/bloatcomposeoverlay.xul bloat/bloatmainoverlay.xul javascript files (used to drive the tests): bloat/bloataddroverlay.js bloat/bloatcomp...
NSPR's Position On Abrupt Thread Termination
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.
...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).
I/O Functions
for sample code that illustrates basic i/o operations, see introduction to nspr.
...for example, the following lines of code are equivalent: rv = pr_pushiolayer(stack, pr_top_io_layer, my_layer); rv = pr_pushiolayer(stack, pr_getlayersidentity(stack), my_layer); pr_getuniqueidentity pr_getnameforidentity pr_getlayersidentity pr_getidentitieslayer pr_getdefaultiomethods pr_createiolayerstub pr_pushiolayer pr_popiolayer ...
PR_NewTCPSocket
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
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_Seek
the error code can then be retrieved with pr_geterror.
...new code should use pr_seek64 so that it can handle files larger than 2 gb.
PR_Seek64
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.
Threads
for an overview of the nspr threading model and sample code that illustrates its use, see introduction to nspr.
... pr_getcurrentthread returns the current thread object for the currently running code.
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 ...
Deprecated SSL functions
the mozilla cross reference (mxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code replacement in nss 3.2 ssl_enable mxr ssl_optionset ssl_enablecipher mxr ssl_cipherprefsetdefault ssl_enabledefault mxr ssl_optionsetdefault ssl_redohandshake mxr ssl_rehandshake ssl_setpolicy mxr ssl_cipherpolicyset ...
HTTP delegation
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.
...please read the source code documentation to learn how to use this api synchronously or asynchronously.
HTTP delegation
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.
...please read the source code documentation to learn how to use this api synchronously or asynchronously.
4.3 Release Notes
libpkix: an rfc 3280 compliant certificate path validation library (see pkixverify) pk11token.needslogin method (see needslogin) support hmacsha256, hmacsha384, and hmacsha512 (see hmactest.java) support for all nss 3.12 initialization options (see initializationvalues) new ssl error codes (see http://mxr.mozilla.org/security/sour...util/sslerrs.h) ssl_error_unsupported_extension_alert ssl_error_certificate_unobtainable_alert ssl_error_unrecognized_name_alert ssl_error_bad_cert_status_response_alert ssl_error_bad_cert_hash_value_alert new tls cipher suites (see http://mxr.mozilla.org/security/sour...sslsocket.java): tls_rsa_with_camellia_128_cbc_s...
...we provide the jss4.jar in case you do not want to obtain your own jce code signing certificate.
NSS Memory allocation
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.
...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.
NSS_3.12.2_release_notes.html
bug 450427: add comodo ecc certification authority certificate to nss bug 450536: remove obsolete xp_mac code bug 451024: certutil.exe crashes with segmentation fault inside pr_cleanup bug 451927: security/coreconf/winnt6.0.mk has invalid defines bug 452751: slot leak in pk11_findslotsbynames bug 452865: remove obsolete linker 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 de...
... 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.
NSS 3.14.2 release notes
note: the new assembly code requires gnu as version 2.19 or newer.
...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).
NSS 3.17.3 release notes
notable changes in nss 3.17.3 the quickder decoder now decodes lengths robustly (cve-2014-1569).
...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
notable changes in nss 3.17.4 bug 1084986: if an ssl/tls connection fails, because client and server don't have any common protocol version enabled, nss has been changed to report error code ssl_error_unsupported_version (instead of reporting ssl_error_no_cypher_overlap).
... bug 1119983: fixed interoperability of nss server code with a libressl client.
NSS 3.17 release notes
nss 3.17 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_rtm/src/ new in nss 3.17 new functionality when using ecdhe, the tls server code may be configured to generate a fresh ephemeral ecdh key for each handshake, by setting the ssl_reuse_server_ecdhe_key socket option to pr_false.
...this option does not affect the tls client code, which always generates a fresh ephemeral ecdh key for each handshake.
NSS 3.18.1 release notes
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.
NSS 3.21 release notes
ckm_tls_mac - computes tls finished mac in secoidt.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 - configuration to enable the tls extended master secret extension (rfc 7627) ssl_preinfo_version - used with sslpreliminarychannelinfo to indicate that a tls version has been selected ssl_preinfo_cipher_suite - used with sslpreliminarychannelinfo to indicate that a tls cipher suite has been selected ssl_preinfo_all - used with sslpreliminarychannelinfo to indicate that all preliminary information has been set notable changes in nss 3.21 nss now builds with elliptic curve ciphers enabled by default (bug 1205688) nss now builds with warnings as errors ...
NSS 3.24 release notes
additional csps are zeroed in the code.
... remove most code related to ssl v2, including the ability to actively send a sslv2-compatible client hello.
NSS 3.28 release notes
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).
... the certificate validation code contains checks to no longer trust certificates that are issued by old wosign and startcom cas, after october 21, 2016.
NSS 3.55 release notes
with this function, a given slot can be queried with a der-encoded certificate, providing performance and usability improvements over other mechanisms.
... bug 1649633 - add pk11_findcertinslot to search a given slot for a der-encoded certificate.
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.
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.
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.
...see https://bugzilla.mozilla.org/show_bug.cgi?id=490238 how to download the samples: hg clone https://hg.mozilla.org/projects/nss; cd nss; hg update samples_branch samples list: sample code 1: hashing sample code 2: init nss database sample code 3: encrypt/decrypt and mac using token sample code 4: encrypt/decrypt and mac using session objects sample code 5: encrypt/decrypt/mac output public key as a csr sample code 6: encrypt/decrypt/mac generating a pkcs#11 csr common code used by these samples: sample code 0: utilities thanks are due to shailendra jain, mozilla community member, who is the principal author of these samples.
Notes on TLS - SSL 3.0 Intolerant Servers
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.
...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.
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
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 public key is sent to the server base-64-der-encoded with an (optional) signed challenge.
Migration to HG
however, below is a brief summary that shows how to checkout the source code and build both nspr and nss: mkdir workarea cd workarea hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss cd nss # set use_64=1 on 64 bit architectures # 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, ...
...the first releases using the new code layout will be nspr 4.10 and nss 3.15 ...
NSS tools : vfychain
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.
...the nss site relates directly to nss code changes and releases.
NSS reference
sec_pkcs12createexportcontext sec_pkcs12createpasswordprivsafe sec_pkcs12createunencryptedsafe sec_pkcs12addcertandkey sec_pkcs12addpasswordintegrity sec_pkcs12enablecipher sec_pkcs12encode sec_pkcs12destroyexportcontext sec_pkcs12decoderstart sec_pkcs12decoderimportbags sec_pkcs12decoderupdate sec_pkcs12decoderfinish sec_pkcs12decodervalidatebags sec_pkcs12decoderverify sec_pkcs12decodergetcerts sec_pkcs12decodersettargettokencas sec_pkcs12decoderiterateinit sec_pkcs12decoderiteratenext sec_pkcs12isencryptionallowed sec_pkcs12setpreferredcipher nspr functions a smal...
... error codes based on "nss and ssl error codes" in the ssl reference.
SSL functions
the mozilla cross reference (dxr) link for each function provides access to the function definition, prototype definition, and source code references.
... function name/documentation source code nss versions nss_getclientauthdata mxr 3.2 and later nss_setdomesticpolicy mxr 3.2 and later nss_setexportpolicy mxr 3.2 and later nss_setfrancepolicy mxr 3.2 and later nssssl_versioncheck mxr 3.2.1 and later ssl_authcertificate mxr 3.2 and later ssl_authcertificatehook mxr 3.2 and later ssl_badcerthook mxr 3.2 and later ssl_certdbhandleset mxr 3.2 and later ssl_canbypass mxr 3.11.7 and later ssl_cipherpolicyget mxr 3.2 and later ssl_cipherpolicyset mxr 3.2 and later ssl_cip...
NSS Tools
the links for each tool take you to the source code, documentation, plans, and related links for each tool.
... source, documentation, tasks/plans signtool 1.3 create digitally-signed jar archives containing files and/or code.
NSS Tools certutil
in each category position use zero or more of the following attribute codes: p prohibited (explicitly distrusted) p trusted peer c valid ca t trusted ca to issue client certificates (implies c) c trusted ca to issue server certificates (ssl only) (implies c) u certificate can be used for authentication or signing w send warning (use with other attributes to include a warning when the certificate is used ...
...in that context) the attribute codes for the categories are separated by commas, and the entire set of attributes enclosed by quotation marks.
NSS Tools pk12util
error codes pk12util can return the following values: 0 - no error 1 - user cancelled 2 - usage error 6 - nls init error 8 - certificate db open error 9 - key db open error 10 - file initialization error 11 - unicode conversion error 12 - temporary file creation error 13 - pkcs11 get slot error 14 - pkcs12 decoder start error 15 - error read from import file 16 - pkcs12 decode error 17 - pkcs12 decoder v...
...erify error 18 - pkcs12 decoder validate bags error 19 - pkcs12 decoder import bags error 20 - key db conversion version 3 to version 2 error 21 - cert db conversion version 7 to version 5 error 22 - cert and key dbs patch error 23 - get default cert db error 24 - find cert by nickname error 25 - create export context error 26 - pkcs12 add password itegrity error 27 - cert and key safes creation error 28 - pkcs12 add cert and key error 29 - pkcs12 encode error ...
NSS tools : signver
MozillaProjectsNSStoolssignver
synopsis signtool -a | -v -d directory [-a] [-i input_file] [-o output_file] [-s signature_file] [-v] description the signature verification tool, signver, is a simple command-line utility that unpacks a base-64-encoded pkcs#7 signed object and verifies the digital signature using standard cryptographic techniques.
...the nss site relates directly to nss code changes and releases.
NSS tools : vfychain
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 ...
...the nss site relates directly to nss code changes and releases.
Renaming With Pork
this describes how to use pork to rewrite source code.
...pork does not yet have a ui, but it is also build-system agnostic and scales to large codebases.
Small Footprint
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.
... 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.
Rhino license
mpl/gpl license the majority of the source code for rhino is available under a mpl 1.1/gpl 2.0 license.
... * * 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.
Rhino optimization
also, you must use this optimization level if your code uses continuation objects.
...the bytecode compiler runs fastest in this mode, but the generated byte code is less efficient.
The JavaScript Runtime
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.
Rhino scopes and contexts
remember to put the exit() call in a finally block if you're executing code that could throw an exception.
...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.
Shumway
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.
FOSS
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.
Future directions
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.
Statistics API
the browser preference javascript.options.mem.notify controls emission of json encoded gc stats to an observer interface.
...in between slices, other browser code is allowed to run.
JS::GetDeflatedUTF8StringLength
this article covers features introduced in spidermonkey 38 returns the length of the char buffer required to encode given string as utf8.
... description js::getdeflatedutf8stringlength returns the length of the char buffer required to encode s as utf8.
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.
... 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.
JS::Value
jsval is deprecated; new code should use js::value.
...these confusing semantics led to this method being removed from the jsapi in more recent releases, but older code might still use it.
JSClass.flags
js_executescript and similar apis set the global object for the code they execute.
...this is recommended for all new code that needs custom marking.
JSClass
instead, all the native code is in jspropertyops (property getters and setters) and jsnatives or jsfastnatives (methods).
... the code for such a class is simple: /* spidermonkey 38 */ static jsclass robot_class = { "robot", /* name */ 0 /* flags */ }; /* spidermonkey 31 or older */ static jsclass robot_class = { "robot", /* name */ 0, /* flags */ js_propertystub, js_propertystub, js_propertystub, js_propertystub, js_enumeratestub, js_resolvestub, js_convertstub, null, jsclass_no_optional_members }; to expose this class to scripts, and to attach methods and properties to it, use js_initclass.
JSDeletePropertyOp
this is either a string (unicode property identifier) or an integer (element index).
...this will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a typeerror in strict mode code.
JSGetObjectOps
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.
...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.
JSNative
in particular, apis such as js_initclass and js_definefunctions create custom methods on javascript objects that are implemented as jsnative callbacks provided by the application, written in c/c++ code.
... the term "native" here refers to c/c++ code as opposed to javascript code.
JSRuntime
all javascript code and most jsapi calls run within a jscontext.
... sample code to set up and tear down a jsruntime and a jscontext is at jsapi user guide.
JSSecurityCallbacks.contentSecurityPolicyAllows
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).
JS_CStringsAreUTF8
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.
...enabling this option also causes js_getstringbytes and js_encodecharacters to produce utf-8 strings instead of latin-1.
JS_CompileScript
js_compileucscript is the unicode version of the function.
... see also the jsapi user guide contains example code using compiled scripts.
JS_CompileUTF8File
compile a script, reading the source code from a file.
... see also the jsapi user guide contains example code using compiled scripts.
JS_CompileUTF8FileHandle
compile a script, reading the source code from a stdio file.
... see also the jsapi user guide contains example code using compiled scripts.
JS_DefineProperty
js_defineucproperty is the unicode version of the function.
... 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.
JS_FS
(or index, if jsprop_index is present in flags) symbol a member name of js::symbolcode the javascript symbol for the function.
... selfhostedname const char * the function's name in self-hosted javascript code.
JS_FlushCaches
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.
JS_GetParent
such an object should not be passed to any other jsapi function that could expose it to script code.
...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.
JS_GetSecurityCallbacks
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.
...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.
JS_InternString
get an interned string - a jsstring that is protected from gc and automatically shared with other code that needs a jsstring with the same value.
...js_internucstring and js_internucstringn are the unicode versions of the function.
JS_IsExceptionPending
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.
...code that might throw js exception ...
JS_NewObject
if the context is not currently executing any code, we use js_getglobalobject to find a global object associated with the context.
...however, although javascript code can freely redefine constructors, the ecmascript standard requires us in certain cases to use the original constructors' prototypes.
JS_NewScriptObject
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.
... 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 spidermonkey do not have script objects allocated for them; such scripts are not accessible via jsapi.) see also the jsapi user guide contains example code using compiled scripts.
JS_PSGS
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.
JS_SaveFrameChain
after a call to js_saveframechain, it looks as if there is no code running on cx.
...js_saveframechain deals with cx not having any code running on it.
JS_SetFunctionCallback
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).
...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.
JS_SetOptions
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_anonfunfix jsoption_jit obsolete since jsapi 11 added in spidermonkey 1.8.1 enables the jit compilation of code in the context.
JS_malloc
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.
JSDBGAPI
breakpoints js_settrap js_gettrapopcode js_cleartrap js_clearscripttraps js_clearalltraps js_handletrap js_setinterrupt js_clearinterrupt watchpoints js_setwatchpoint js_clearwatchpoint js_clearwatchpointsforobject js_clearallwatchpoints inspecting the stack js_pctolinenumber js_linenumbertopc js_getfunctionscript js_getfunctionnative js_getfunctionfastnative js_getscriptprincipals typedef jsstackframe js_frameiterator js_getframescript js_getframepc js_getscriptedcaller js_stackframeprincipals js_evalframeprincipals js_getframeannotation js_setframeannotation js_getframeprincipalarray js_isnativeframe js_getframeobject js_getframescopechain js_getframecallobje...
...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
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.
...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).
Using RAII classes in Mozilla
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.
...the static analys runtime assertions are often better at catching bugs in code that a developer is currently working on than static analysis, which he might not think to run.
Exploitable crashes
these crashes are almost always exploitable to run arbitrary code.
...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.
Handling Mozilla Security Bugs
note that the focus of this new structure is restricted solely to addressing actual security vulnerabilities arising from problems in mozilla code.
... 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.
Using the Places favicon service
this allows efficient caching, since the default favicon will probably be cached in its decoded form by the image library.
...however, since the uri will be different from the default favicon, the decoded image will not be cached by the image library.
The Publicity Stream API
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.
...possible error codes include: denied - if the user does not log in correctly permissiondenied - if the site is not allowed to access the publicity stream networkerror - if the publicity server is unreachable for_apps is a json list of apps that this store has (each represented as its origin url), so that stream events not relating to applications in a given presentation context can be excluded from ...
XML Extras
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".
... help at the code level, contributing code patches for bug fixes or feature completion.
Accessing the Windows Registry Using XPCOM
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.
...the following skeleton code will allow you to determine which interface to use: if ("@mozilla.org/windows-registry-key;1" in components.classes) { // firefox 1.5 or newer } else if ("@mozilla.org/winhooks;1" in components.classes) { // seamonkey or other older non-toolkit application } else if ("@mozilla.org/browser/shell-service;1" in components.classes) { var wss = components.classes["@mozilla.org/browser/shell-ser...
How To Pass an XPCOM Object to a New Window
a more useful example is available in the source code: toolkit/components/help/content/contexthelp.js#61 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.
...to access the xpcom object from the window's code, you can access the window.arguments[] array, as shown in the example below: components.utils.reporterror(string(window.arguments[0])); this will produce output similar to "[xpconnect wrapped nsimyxpcomobject]".
Components.utils.isXrayWrapper
when privileged javascript in gecko accesses objects belonging to less-privileged code (such as untrusted web content), it does so, by default, with "xray vision": a mechanism that filters out certain changes to the objects that could cause them to behave in unexpected ways.
... for example, privileged code using an xray to a dom object sees only the original, native version of the dom object.
JavaXPCOM
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.
Using components
any of the below can be accessed by components.blah (ie: components.issuccesscode) utils=[object nsxpccomponents_utils] interfaces=[object nsxpccomponents_interfaces] classes=[object nsxpccomponents_classes] results=[object nsxpccomponents_results] issuccesscode=function issuccesscode() { [native code] } constructor=[object nsxpccomponents_constructor] queryinterface=function queryinterface() { [native code] } interfacesbyid=[object nsxpccomponents_interfacesbyid] classesbyid=...
...[object nsxpccomponents_classesbyid] stack=js frame :: scratchpad/4 :: cdump :: line 8 manager=[xpconnect wrapped nsicomponentmanager] id=[object nsxpccomponents_id] exception=[object nsxpccomponents_exception] reporterror=function reporterror() { [native code] } cancreatewrapper=function cancreatewrapper() { [native code] } cancallmethod=function cancallmethod() { [native code] } cangetproperty=function cangetproperty() { [native code] } cansetproperty=function cansetproperty() { [native code] } ...
Profiling XPCShell
but sometimes, venkman gives too much noise (because it also profiles chrome code).
...you can just call the code you want to test.
XPCshell Test Manifest Expressions
note that it currently seems like neither this list nor the one on the official docs is exhaustive, so if 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.
NS_GetMemoryManager
otherwise, it returns an error code.
...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.
NS_InitXPCOM2
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.
NS_InitXPCOM3
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.
NS_NewLocalFile
otherwise, it returns an error code.
... 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.
Core XPCOM functions
nce of nsilocalfile that provides a platform independent representation of a file path.ns_reallocreallocates a block of memory using the xpcom memory manager.ns_shutdownxpcomthe ns_shutdownxpcom function terminates use of xpcom in the calling process.nsresultthe 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.
NS ConvertASCIItoUTF16 external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
NS ConvertUTF16toUTF8 external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
NS ConvertUTF8toUTF16 external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
NS LossyConvertUTF16toASCII external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
PromiseFlatCString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
PromiseFlatString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsACString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsAString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsAutoString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsCAutoString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsCStringContainer (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult aerrorcode pruint32 aradix ...
nsCString external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsDependentCString external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsDependentCSubstring external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsDependentString external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsDependentSubstring external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult aerrorcode pruint32 aradix ...
nsLiteralCString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsLiteralString (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsStringContainer (External)
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
nsString external
@param aerrorcode pointer to contain result code.
... @param aradix must be 10 or 16 parameters nsresult* aerrorcode pruint32 aradix ...
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.
...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.
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.
... result long one of the error code values listed under constants on this page.
mozIStorageFunction
if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code.
... sample code both of the following code samples assume that the variable dbconn is an opened mozistorageconnection.
mozIStorageService
the sqlite code uses a simple string comparison to see if there is already a connection.
...the sqlite code uses a simple string comparison to see if there is already a connection.
nsIAccessNode
native code only!
...native code only!
nsIAsyncInputStream
any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close().
...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.
nsIAsyncOutputStream
any successful status code passed to this method is treated as ns_base_stream_closed, which has an effect equivalent to nsiinputstream.close().
...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.
nsICancelable
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.
nsIConsoleService
note: see the code samples below for how to call getmessagearray.
... acategory — a string indicating what kind of code caused the error message.
nsIContentPrefService
provides a way for extensions and browser code to save preferences for specific websites.
...also useful for testing the database creation and migration code.
nsICryptoHMAC
acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string.
...this can be either binary data or base 64 encoded.
nsIDNSRecord
inherits from: nsisupports last changed in gecko 1.7 method overview prnetaddr getnextaddr(in pruint16 aport); native code 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.
nsIDOMGeoPositionAddress
countrycode obsolete since gecko 11 domstring removed in firefox 11, since it isn't defined in the specification; use country instead.
... postalcode domstring the postal or zip code.
nsIDOMProgressEvent
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.
... it still is usable from native c++ code.
nsIDOMXPathException
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.
nsIDataSignatureVerifier
asignature the signature of the data, base64 encoded.
... apublickey the public part of the key used for signing, der encoded then base64 encoded.
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 often correlates to whether other code (for example, firefox, xulrunner) was compiled with debug defined.
nsIDirectoryServiceProvider2
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).
nsIDocumentLoader
void fireonlocationchange(in nsiwebprogress awebprogress, in nsirequest arequest, in nsiuri auri); obsolete since gecko 1.8 void fireonstatuschange(in nsiwebprogress awebprogress, in nsirequest arequest, in nsresult astatus, in wstring amessage); obsolete since gecko 1.8 void getcontentviewercontainer(in nsisupports adocumentid, out nsicontentviewercontainer aresult); native code only!
...gress arequest auri fireonstatuschange() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void fireonstatuschange( in nsiwebprogress awebprogress, in nsirequest arequest, in nsresult astatus, in wstring amessage ); parameters awebprogress arequest astatus amessage native code only!getcontentviewercontainer obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0)this feature is obsolete.
nsIDragSession
native code only!
... boolean isdataflavorsupported( in string adataflavor ); parameters adataflavor a string representing the mime type of the data to be matched, such as "text/unicode".
nsIEditorSpellCheck
typically, this is an iso language code, such as "en-us".
...typically, this is an iso language code such as "en-us".
nsIEventTarget
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!
...native code only!postevent obsolete since gecko 1.9 (firefox 3)this feature is obsolete.
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.
... return value true if data from urls with the specified extension and encoding should be decoded prior to saving the file or delivering it to a helper application; otherwise false.
nsIFeedContainer
common atom and rss fields are normalized, including some namespaced extensions such as "dc:subject" and "content:encoded".
...this string is parsable by javascript and mail code.
nsIFeedEntry
this comes from the atom:content and/or content:encoded fields.
...this date is parsable by both javascript (via date.parse()) and mail code.
nsIFilePicker
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 your code is a component and window is not defined, you can get one using nsiwindowmediator.
nsIHttpServer
* * @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.
... */ void registererrorhandler(in unsigned long code, in nsihttprequesthandler handler); /** * maps all requests to paths beneath path to the corresponding file beneath * dir.
nsIJetpack
evalscript() this asynchronously sends code to the jetpack process for evaluation.
... the code will be evaluated using at least javascript 1.8.1.
nsILocale
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.
nsIMsgIdentity
void copy(in nsimsgidentity identity); parameters identity getunicharattribute() getter for unicode attributes.
... astring getunicharattribute(in string name); parameters name setunicharattribute() setter for unicode attributes.
nsINavHistoryObserver
if your code only cares about whole entries being deleted instead of individual visits, you can simply act only when awholeentry is true.
...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.
nsIObserver
example the following code is an implementation of nsiobserver that is registered to receive notifications for the "mytopicid" topic.
...see code snippets:preferences - using preference observers for an example.
nsIRequest
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.
nsIScreenManager
introduced gecko 0.9.5 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) implemented by: @mozilla.org/gfx/screenmanager;1 as a service: var screenmanager = components.classes["@mozilla.org/gfx/screenmanager;1"] .getservice(components.interfaces.nsiscreenmanager); method overview nsiscreen screenfornativewidget( in voidptr nativewidget ); native code only!
... methods native code only!screenfornativewidget returns the nsiscreen instance for the native widget pointer.
nsISelection2
nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results); void getrangesforintervalcomarray(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results); native code only!
... 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.
nsISound
inherits from: nsisupports last changed in gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6) warning: this interface should not be used to play custom sounds in modern code.
... warning: this method should not be used in modern code.
nsISpeculativeConnect
netwerk/base/public/nsispeculativeconnect.idlscriptable lets non-networking code provide hints to the networking layer that an http connection attempt to a particular site is likely to happen soon; this lets the networking layer begin setting up tcp and, if appropriate, ssl handshakes to save time when the connection is actually opened later.
...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.
nsIStreamConverter
netwerk/streamconv/public/nsistreamconverter.idlscriptable provides an interface to implement when you have code that converts data from one type to another.
... inherits from: nsistreamlistener last changed in gecko 1.7 suppose you had code that converted plain text into html.
nsIThreadManager
last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview nsithread getthreadfromprthread(in prthread prthread); native code only!
... methods native code only!getthreadfromprthread given a prthread, this method returns the corresponding nsithread.
nsITransport
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).
nsITransportEventSink
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.
nsIURL
components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice) .newuri("http://developer.mozilla.org", null, null); try { var myurl = myuri.queryinterface(components.interfaces.nsiurl); } catch(e) { // the uri is not an url } or using instanceof: if (myuri instanceof components.interfaces.nsiurl) { // your code here } method overview autf8string getcommonbasespec(in nsiuri auritocompare); autf8string getrelativespec(in nsiuri auritocompare); attributes attribute type description directory autf8string directory portion of a url.
...autf8string getrelativespec( in nsiuri auritocompare ); parameters auritocompare a uri to compare with return value the common uri portion see also code snippets:uri parsing nsistandardurl ...
nsIUUIDGenerator
its from: nsisupports last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) implemented by @mozilla.org/uuid-generator; as a service: var uuidgenerator = components.classes["@mozilla.org/uuid-generator;1"] .getservice(components.interfaces.nsiuuidgenerator); method overview nsidptr generateuuid(); void generateuuidinplace(in nsnonconstidptr id); native code only!
...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.
nsIVersionComparator
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.
...hen version, then a==b is bigger than 0, then a > b example function compareversions(a,b) { var x = services.vc.compare(a,b); if(x == 0) return a + "==" + b; else if(x > 0) return a + ">" + b; return a + "<" + b; } dump(compareversions("1.0pre", "1.0")); example - compare current browser version this example here uses nsixulappinfo component to get the version of the browser that the code is running in.
nsIWebBrowserChrome
void exitmodaleventloop( in nsresult astatus ); parameters astatus the result code to return from showasmodal().
...return value note: the function error code returned by this corresponds to the status value specified in exitmodaleventloop.
nsIWebContentHandlerRegistrar
examples register a webmail service as mailto handler the following code aims to add "outlook.com live mail" to list of webservice handlers.
...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...
nsIXFormsNSInstanceElement
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.
...related interfaces nsixformsmodelelement example code none.
nsIXFormsNSModelElement
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 code none.
nsIXMLHttpRequest
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.
... example code this is a simple example code for opening a simple http request from a xul application (like a mozilla extension) without using observers: var req = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('post', "http://www.foo.bar:8080/nietzsche.do", true); req.send('your=data&and=more&stuff=here'); example 2 var {cu: utils, cc: classes, ci: instances} =...
nsIXULBrowserWindow
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.
nsIXULSortService
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.
nsIXULTemplateBuilder
native code only!init called to initialize a xul content builder on a particular root element.
... native code only!createcontents invoked lazily by a xul element that needs its child content built.
nsIXULWindow
method overview void addchildwindow(in nsixulwindow achild); void applychromeflags(); native code only!
... native code only!applychromeflags back-door method to force application of chrome flags at a particular time.
nsIXmlRpcClient
responsestatus readonly unsigned long the most recent http status code returned from this server.
... responsestring readonly unsigned long the most recent http status code returned from this server.
nsIZipWriter
example adding a comment to a zip file var zipwriter = components.constructor("@mozilla.org/zipwriter;1", "nsizipwriter"); var zipw = new zipwriter(); zipw.open(myzipfilepath, pr_rdwr | pr_create_file | pr_truncate); zipw.comment = "this is a comment."; zipw.close(); pr_rdwr and friends are constants that are not in any interface (see bug 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.
XPCOM Interface Reference
iaccessibleapplicationiaccessiblecomponentiaccessibleeditabletextiaccessiblehyperlinkiaccessiblehypertextiaccessibleimageiaccessiblerelationiaccessibletableiaccessibletable2iaccessibletablecelliaccessibletextiaccessiblevalueidispatchijsdebuggeramiinstallcallbackamiinstalltriggeramiwebinstallinfoamiwebinstalllisteneramiwebinstallpromptamiwebinstallerimgicacheimgicontainerimgicontainerobserverimgidecoderimgidecoderobserverimgiencoderimgiloaderimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolorcallbackmozispellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletionca...
...lproxyservicensiproxyinfonsipushmessagensipushservicensipushsubscriptionnsiradiointerfacelayernsirandomgeneratornsirequestnsirequestobservernsiresumablechannelnsirunnablensishentrynsishistorynsishistorylistenernsisockssocketinfonsisslerrorlistenernsisslsocketcontrolnsiscreennsiscreenmanagernsiscripterrornsiscripterror2nsiscriptableionsiscriptableinputstreamnsiscriptableunescapehtmlnsiscriptableunicodeconverternsiscrollablensisearchenginensisearchsubmissionnsisecuritycheckedcomponentnsiseekablestreamnsiselectionnsiselection2nsiselection3nsiselectioncontrollernsiselectionimageservicensiselectionprivatensiserversocketnsiserversocketlistenernsiservicemanagernsisessionstartupnsisessionstorensisimpleenumeratornsismsdatabaseservicensismsrequestmanagernsismsservicensisocketprovidernsisocketproviderser...
NS_CStringContainerInit
otherwise, it returns an error code.
...with ns_cstringcontainerinit, the coder is required to call ns_cstringcontainerfinish when done with the nscstringcontainer object.
NS_CStringCutData
otherwise, it returns an error code.
... 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.
NS_CStringInsertData
otherwise, it returns an error code.
... 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.
NS_StringAppendData
otherwise, it returns an error code.
... 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.
NS_StringCopy
otherwise, it returns an error code.
... 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.
NS_StringCutData
otherwise, it returns an error code.
... 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.
NS_StringInsertData
otherwise, it returns an error code.
... 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.
NS_StringSetData
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_StringSetDataRange
otherwise, it returns an error code.
... example code // replace all occurances of |matchval| with |newval| void replacesubstring(nsastring& str, const nsastring& matchval, const nsastring& newval) { const prunichar* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_stringgetdata(str, &sp); ml = ns_stringgetdata(matchval, &mp); nl = ns_stringgetdata(newval, &np); for (const prunichar* iter = sp; iter <= sp + sl - ml; ++iter) { if (memcmp(iter, mp, ml) == 0) { pruint32 offset = iter - sp; ns_stringsetdatarange(str, offset, ml, np, nl); sl = ns_stringgetdata(str, &sp); iter = sp + offset + nl - 1; } } } history this function was frozen for mozilla 1.7.
The Thread Manager
only c++ code may use the thread manager and xpcom thread.
... nsithread the nsithread interface encapsulates an operating system thread, providing easy cross-platform access to multithreading in your code.
XPCOM Thread Synchronization
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.
... } old usage note: this is deprecated code that is shown only to compare with approved code.
Using nsIDirectoryService
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.
...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
this code is tested, but barely, and i am by no means an expert on this area.
...zachlipton 22:52, 18 july 2006 (pdt) the code on this page will work with applications using toolkit 1.8 and below such as firefox 2.0.0.x and thunderbird 2.0.0.x.
Mozilla technologies
tent access apifirefox 2 and thunderbird 2 introduce a series of interfaces that make it easy for extension authors to access rss and atom feeds.life after xul: building firefox interfaces with htmlthis page gathers technical solutions to common problems encountered by teams shipping html-based interfaces inside firefox.morkmork is a database file format invented by david mccusker for the mozilla code since the original netscape database information was proprietary and could not be released open source.
...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.
Address book sync client design
* * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the error (if any).
... * * atransactionid - the id for this particular request * astatus - status code for the sync request * amsg - a text string describing the error (if any).
Creating a gloda message query
see gloda examples for more code samples.
...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.
Events
there are a lot of events that can be fired in mail code.
...others are internal to gecko or other parts of mozilla application code.
Filelink Providers
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.
... saving the preferences is handled automatically by the dialog code.
MailNews Protocols
the message search code also has protocol-specific code to handle searching on the server, or local mailbox.
... the search code also knows what the different search capabilities of the various protocols are.
Mail and RDF
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.
Mail composition back end
included in this functionality is the code to copy the messages to the appropriate locations after delivery (i.e.
...if message creation fails, the nsimsgsend operation will return an ns_failed() return code.
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...
...operty.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 (propertystring == "testproperty") { dump("recieved integer test property fired on folder " + folder.prettyname + " with values " + oldvalue + " and " + newvalue + "\n"); } // set up the folder listener to point to the above function var folderlistener = { onitemadded: function(parent, item, viewstring) {}, onitemremoved: function(parent, item, viewstring) {}, onitemproper...
Main Windows
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.
Building a Thunderbird extension 6: Adding JavaScript
in this step we will create a small piece of javascript code that inserts the current date into our statusbar widget.
...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.
Demo Addon
it is a handy library that keeps your code cleaner and simpler.
... 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), }); //...
Get Thunderbird version
(version 3.0b3pre was the first build to include steel.) var versionchecker = components.classes["@mozilla.org/xpcom/version-comparator;1"].getservice(components.interfaces.nsiversioncomparator); if (versionchecker.compare(application.version, "3.0b4") >= 0) // code for >= 3.0b4 else // code for < 3.0b4 for versions prior to 3.0b3pre, you can use something like this: var version; if ( "@mozilla.org/xre/app-info;1" in components.classes ) version = components.classes["@mozilla.org/xre/app-info; 1"].getservice(components.interfaces.nsixulappinfo).version; else version = components.classes["@mozilla.org/preferences-service; 1"].getservice(components.interfaces.nsiprefbranch)...
....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 ...
Thunderbird extensions
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.
... 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 the Mozilla source server
the nightly debug builds are now also source indexed so that by following a couple of simple steps you can also have the source code served to you for debugging without a local build what you'll need windbg or visual studio (note: express editions will not work, but windbg is a free download) a nightly build that was created after april 15, 2008; go to the /pub/firefox/nightly/latest-mozilla-central/ folder and grab the installer for builds predating the switch to mercurial, you'll need cvs.exe, added to your path (the cvs.exe from mozillabuild has problems, use this one instead) note: do not use the cvs from mozillabuild, it will not work!
... now, when you click on a frame in the "calls" window, windbg will prompt you about running cvs to download the associated source code.
Virtualenv
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.
... on mac os x, you will need xcode to use virtualenv.
Declaring types
{ fieldn: typen } ] example for example, to support the c tm structure using js-ctypes, you would use the following code: const struct_tm = new ctypes.structtype("tm", [ { "tm_sec": ctypes.int }, { "tm_min": ctypes.int }, { "tm_hour": ctypes.int }, { "tm_mday": ctypes.int }, { "tm_mon": ctypes.int }, { "tm_year": ctypes.int }, { "tm_wday...
...the equivalent c code looks like this: typedef struct userrecord { char *name; int id; // assuming int is 32-bit here } userrecord; typedef userrecordptr *userrecord; ...
ctypes
javascript characters 16-bit c unicode characters are handled by js-ctypes using the jschar type.
...these are unicode characters.
js-ctypes
js-ctypes allows application and extension code to call back and forth to native code written in c.
... note: js-ctypes is only available from chrome code; that is, ctypes is not available to websites, only application and extension code.
PKCS #11 Netscape Trust Objects - Network Security Services
examples of purposes are: email, code signing, authenticating a server.
... cka_trust_code_signing ck_trust level of trust for code signing purpose.
Drawing and Event Handling - Plugins
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 code shows the specific data passed through this method for each platform: #ifdef xp_mac typedef eventrecord npevent; #elif defined(xp_win) typedef struct _npevent { int16 event; int16 wparam; int32 lparam; } npevent; #elif defined(xp_unix) typedef xevent npevent; #else typedef void npevent; #endif /* xp_mac */ int16 npp_handleevent(npp instance, npevent* event); on mac os, when...
Streams - Plugins
for streams that are not inherently seekable and not initially in mode np_seek: npn_requestread returns the error code nperr_stream_not_seekable.
... 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.
Version, UI, and Status Information - Plugins
the browser and plug-in api major version numbers represent code release numbers, and their minor version numbers represent point release numbers.
... 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.
Gecko Plugin API Reference - Plugins
scripting plugins how the dom handles scripting threading model security model what's in the plugin code?
... 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 ...
Pretty-print a minified file - Firefox Developer Tools
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.
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 +...
... 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 eyedropper esc esc esc move by 1 pixel arrow keys arrow keys arrow keys ...
Aggregate view - Firefox Developer Tools
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.
...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.
Memory - Firefox Developer Tools
it then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory.
... 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.
Inspecting web sockets - Firefox Developer Tools
only requests with the 101 status code (websocket protocol handshake) are visible, which indicates that the server is switching to a web socket connection.
... 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.
Network request details - Firefox Developer Tools
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.
... 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.
Work with animations - Firefox Developer Tools
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.
...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.
Performance - Firefox Developer Tools
le in more detail: the waterfall shows the different operations the browser was performing, such as executing layout, javascript, repaints, and garbage collection the call tree shows the javascript functions in which the browser spent most of its time the flame chart shows the javascript call stack over the course of the recording the allocations view shows the heap allocations made by your code over the course of the recording.
... allocations see the allocations made by your code over the course of the recording.
Settings - Firefox Developer Tools
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.
... 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.
Rich output - Firefox Developer Tools
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.
...ption: "morning pages", datecreated: 1552404478137 } ​ 1: object { status: "in progress", description: "refactor styles", datecreated: 1552404493169 } ​ 2: object { status: "to do", description: "create feedback form", datecreated: 1552404512630 } ​ 3: object { status: "to do", description: "normalize table", datecreated: 1552404533790 } ​ length: 4 ​ <prototype>: array [] debugger eval code:1:9 undefined highlighting and inspecting dom nodes if you hover the mouse over any dom element in the console output, it's highlighted on the page: in the screenshot above you'll also see a blue "target" icon next to the node in the console output: click it to switch to the inspector with that node selected.
about:debugging (before Firefox 68) - Firefox Developer Tools
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.
...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.
about:debugging - Firefox Developer Tools
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.
... other information about the extension is displayed: location the location of the extension's source code on your local system.
AbstractRange - Web APIs
if we wish to instead copy the text "an interesting thing..." from the <section>'s heading (an <h2> element) through the end of the letters "ve" in the <em> within the paragraph below it, the following code would work: let r = document.createrange(); let startnode = document.queryselector("section h2").childnodes[0]; r.setstart(startnode, 11); let endnode = document.queryselector("#entry1 p em").childnodes[0]; r.setend(endnode, 2); let fragment = r.clonecontents(); here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the dom hierarchy,...
...the code to do that looks like the following: let paranode = document.queryselector("p"); let paratextnode = paranode.childnodes[1]; let range = document.createrange(); range.setstart(paratextnode, 6); range.setend(paratextnode, paratextnode.length-1); let fragment = range.clonecontents(); document.body.appendchild(fragment); first we get references to the paragraph node itelf as well as to the secon...
Animation.onremove - Web APIs
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacestate);...
... }); here we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves.
Animation.persist() - Web APIs
WebAPIAnimationpersist
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacestate); }); here we have a <d...
...iv> element, and an event listener that fires the event handler code whenever the mouse moves.
Animation.replaceState - Web APIs
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacestate);...
... }); here we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves.
Attr - Web APIs
WebAPIAttr
you should revise your code accordingly.
...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.
AudioBuffer - Web APIs
the audiobuffer interface represents a short audio asset residing in memory, created from an audio file using the audiocontext.decodeaudiodata() method, or from raw data using audiocontext.createbuffer().
...you can find the full source code at our webaudio-examples repository; a running live version is also available.
AudioBufferSourceNode.loop - Web APIs
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.
... you can run the full example live (or view the source.) 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.playbackRate - Web APIs
example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track, and put it into an audiobuffersourcenode.
...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 - Web APIs
you can also run the code live, or view the source.
...// 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.
AudioContext.getOutputTimestamp() - Web APIs
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).
AudioWorkletGlobalScope - Web APIs
the audioworkletglobalscope interface of the web audio api represents a global execution context for user-supplied code, which defines custom audioworkletprocessor-derived classes.
... each baseaudiocontext has a single audioworklet available under the audioworklet property, which runs its code in a single audioworkletglobalscope.
AuthenticatorAttestationResponse.attestationObject - Web APIs
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.
... id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationobj = newcredentialinfo.response.attestationobject; // this will be a cbor encoded arraybuffer // do something with the response // (sending it back to the relying party server maybe?) }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'attestationobject' in that specification.
AuthenticatorResponse.clientDataJSON - Web APIs
challenge the base64url encoded version of the cryptographic challenge sent from the relying party's server.
... examples function arraybuffertostr(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 co...
BaseAudioContext.createBufferSource() - Web APIs
audiobuffers are created using baseaudiocontext.createbuffer or returned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track.
... note: you can also run the code live, or view the source.
BaseAudioContext.createConvolver() - Web APIs
for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
... // 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(); ...
BaseAudioContext.createDynamicsCompressor() - Web APIs
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).
BaseAudioContext.createWaveShaper() - Web APIs
for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
...we found the below distortion curve code on stack overflow.
BasicCardRequest - Web APIs
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.
...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.
Using the Beacon API - Web APIs
this code snippet is for the global context: function worker_send(url, data) { // create the worker object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworker.postmessage([url, data]); // set up a message handler to receive the success/fail message from the worker myworker.onmessage = function(event) { var msg = event.data; // log work...
...er'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(url, data); postmessage(status ?
BlobEvent.BlobEvent() - Web APIs
syntax blobevent = new blobevent({data: aspecificblob}[, timecode]); arguments the blobevent() constructor also inherits arguments from event().
... timecode optional a domhighrestimestamp to be used in initializing the blob event.
BlobEvent - Web APIs
WebAPIBlobEvent
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.
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
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.
...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...
CSSStyleValue.parse() - Web APIs
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.
CanvasRenderingContext2D.drawWindow() - Web APIs
if you're writing chrome code, you probably want windowglobalparent.drawsnapshot from the parent process.
... drawwindow_async_decode_images 0x10 do not synchronously decode images - draw what we have.
CanvasRenderingContext2D.miterLimit - Web APIs
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.beginpath(); ctx.moveto(0,0); ctx.linewidth = 15; ctx.lineto(100, 100); ctx.stroke();</textarea> var canvas = document.getelementbyi...
...d("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener("click", function() { textarea.focus(); }) textarea.addeventlistener("input", drawcanvas); window.addeventlistener("load", drawcanvas); screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.miterlimit' in that specification.
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.fillrect(10, 10, 30, 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(); c...
...tx.rect(10, 10, 30, 30); ctx.scrollpathintoview();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener("click", function() { textarea.focus(); }) textarea.addeventlistener("input", drawcanvas); window.addeventlistener("load", drawcanvas); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2...
Compositing example - Web APIs
the output looks like this: compositing example this code sets up the global values used by the rest of the program.
...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
see compositing examples for the code of the following examples.
...n drawstar(ctx, r) { ctx.save(); ctx.beginpath(); ctx.moveto(r, 0); for (var i = 0; i < 9; i++) { ctx.rotate(math.pi / 5); if (i % 2 === 0) { ctx.lineto((r / 0.525731) * 0.200811, 0); } else { ctx.lineto(r, 0); } } ctx.closepath(); ctx.fill(); ctx.restore(); } <canvas id="canvas" width="150" height="150"></canvas> draw(); in the first few lines of code, we draw a black rectangle the size of the canvas as a backdrop, then translate the origin to the center.
CloseEvent.initCloseEvent() - Web APIs
syntax event.initmouseevent(type, canbubble, cancelable, wasclean, reasoncode, reason); parameters type the string to set the event's type to.
... reasoncode the reason of the close.
ConstantSourceNode - Web APIs
nnode2 = context.creategain(); gainnode3 = context.creategain(); gainnode2.gain.value = gainnode3.gain.value = 0.5; volumeslidercontrol.value = gainnode2.gain.value; constantnode = context.createconstantsource(); constantnode.connect(gainnode2.gain); constantnode.connect(gainnode3.gain); constantnode.start(); gainnode2.connect(context.destination); gainnode3.connect(context.destination); this code starts by creating the gain nodes and setting them and the volume control that will adjust their value all to 0.5.
... 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.
ConvolverNode - Web APIs
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; } ...
DOMPointReadOnly() - Web APIs
the dompointreadonly() constructor returns a new dompointreadonly object representing a point in 2d or 3d space, optionally with perspective, whose values cannot be altered by script code.
... examples the following code demonstrates creating both 2d and 3d points.
DataTransfer.types - Web APIs
the formats are unicode strings giving the type or format of the data, generally given by a mime type.
...items[" + i + "].kind = " + ev.datatransfer.items[i].kind + " ; type = " + ev.datatransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples of <code>datatransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">drag item 1 to the drop zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">drag item 2 to the drop zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</...
Document: keypress event - Web APIs
interface keyboardevent bubbles yes cancelable yes default action varies: keypress event; launch text composition system; blur and focus events; domactivate event; other event examples addeventlistener keypress example this example logs the keyboardevent.code value whenever you press a key.
... <p>press inside this iframe first to focus it, then try pressing keys on the keyboard.</p> <p id="log"></p> const log = document.getelementbyid('log'); document.addeventlistener('keypress', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeypress equivalent document.onkeypress = logkey; specifications specification status ui events working draft ...
Document.requestStorageAccess() - Web APIs
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).
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
currently this method is only implemented in firefox, and only available to chrome code.
... 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.
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
currently this method is only implemented in firefox, and only available to chrome code.
...ript content var output = document.getelementbyid("output"); if (document.nodesfrompoint) { var nodes = document.nodesfrompoint(30, 20); for(var i = 0; i < nodes.length; i++) { output.textcontent += nodes[i].localname; if (i < nodes.length - 1) { output.textcontent += " < "; } } } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code>document.nodesfrompoint()</code>" + "</span>"; } specifications not part of any specification at present.
Introduction to the DOM - Web APIs
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.
... 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.
DynamicsCompressorNode.attack - Web APIs
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).
DynamicsCompressorNode.knee - Web APIs
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).
DynamicsCompressorNode.ratio - Web APIs
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).
DynamicsCompressorNode.release - Web APIs
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).
DynamicsCompressorNode.threshold - Web APIs
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).
DynamicsCompressorNode - Web APIs
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).
EXT_shader_texture_lod - Web APIs
glsl built-in functions the following new functions can be used in glsl shader code, if this extension is enabled: vec4 texture2dlodext(sampler2d sampler, vec2 coord, float lod) vec4 texture2dprojlodext(sampler2d sampler, vec3 coord, float lod) vec4 texture2dprojlodext(sampler2d sampler, vec4 coord, float lod) vec4 texturecubelodext(samplercube sampler, vec3 coord, float lod) vec4 texture2dgradext(sampler2d sampler, vec2 p, vec2 dpdx, vec2 dpdy) vec4 texture2dprojgradext(sample...
...r2d 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)); } </script> specifications specification status comment ext_shader_texture_lodthe definition...
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
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.
... 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.
Element: fullscreenchange event - Web APIs
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.
Element.getElementsByClassName() - Web APIs
however the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed.
... 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'); while (matches.length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation).
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
as a result, the document contents are replaced with a display of the page's entire source code.
... 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.
Element.insertAdjacentText() - Web APIs
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.
... polyfill you can polyfill the insertadjacenttext() method in internet explorer 5.5 (maybe earlier) and higher with the following code: if (!element.prototype.insertadjacenttext) element.prototype.insertadjacenttext = function(type, txt){ this.insertadjacenthtml( type, (txt+'') // convert to string .replace(/&/g, '&amp;') // embed ampersand symbols .replace(/</g, '&lt;') // embed less-than symbols ) } specification specification status comment domthe definit...
Element: keypress event - Web APIs
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.code}`; } onkeypress equivalent input.onkeypress = logkey; specifications specification status ui events working draft ...
Element.requestFullscreen() - Web APIs
to learn when other code has toggled full-screen mode on and off, you should establish listeners for the fullscreenchange event on the document.
... you can see this example in action or view or remix the code on glitch.
Encoding API - Web APIs
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.
Event - Web APIs
WebAPIEvent
many dom elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them.
... 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.
ExtendableEvent - Web APIs
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 code snippet also shows a best practice for versioning caches used by the service worker.
FetchEvent.preloadResponse - Web APIs
example this code snippet is from the navigation preload page.
...if no match is found, the code checks for a preloaded response.
FileEntrySync - Web APIs
returns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist.
... returns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist.
FileSystemDirectoryEntry.getDirectory() - Web APIs
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.
... 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).
FileSystemDirectoryEntry.getFile() - Web APIs
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.
... 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).
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.
... to ensure your code will work in both chrome and other browsers, you can include code similar to the following: var filesystemdirectoryentry = window.filesystemdirectoryentry || window.directoryentry; var filesystementry = window.filesystementry || window.entry; limitations in firefox next, let's look at limitations of the firefox implementation of the api.
FontFace - Web APIs
WebAPIFontFace
fontface.unicoderange a cssomstring that retrieves or sets the range of unicode codepoints encompassing the font.
... it is equivalent to the unicode-range descriptor.
FontFaceSet.load() - Web APIs
WebAPIFontFaceSetload
"italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text.
... 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.
Using the Geolocation API - Web APIs
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.
GlobalEventHandlers.onanimationcancel - Web APIs
javascript before we get to the animation code, we define a function which logs information to a box on the user's screen.
... 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.
GlobalEventHandlers.onanimationiteration - Web APIs
much of this code is the same as in other examples of animation events, so it may look familiar.
... @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.
GlobalEventHandlers.onkeydown - Web APIs
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.
GlobalEventHandlers.onkeyup - Web APIs
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.
GlobalEventHandlers.onpointerdown - Web APIs
javascript first, let's look at the javascript code that handles the pointerdown event.
... 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).
HTMLCanvasElement.toBlob() - Web APIs
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.
...style.display = 'block'; a.download = iconname + '.ico'; a.href = window.url.createobjecturl(b); } } canvas.toblob(blobcallback('passthisstring'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); save toblob to disk with os.file (chrome/add-on context only) this technique saves it to the desktop and is only useful in firefox chrome context or add-on code as os apis are not present on web sites.
HTMLCanvasElement.toDataURL() - Web APIs
syntax canvas.todataurl(type, encoderoptions); parameters type optional a domstring indicating the image format.
... 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.
HTMLElement.hidden - Web APIs
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.
... 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.
HTMLFormElement.enctype - Web APIs
possible values are: application/x-www-form-urlencoded: the initial default type.
... 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.
HTMLImageElement.srcset - Web APIs
.box { width: 200px; border: 2px solid rgba(150, 150, 150, 255); padding: 0.5em; word-break: break-all; } .box img { width: 200px; } javascript the following code is run within a handler for the window's load event.
... 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.
HTMLInputElement - Web APIs
maxlength long: returns / sets the element's maxlength attribute, containing the maximum number of characters (in unicode code points) that the value can have.
... minlength long: returns / sets the element's minlength attribute, containing the minimum number of characters (in unicode code points) that the value can have.
HTMLMediaElement.seekToNextFrame() - Web APIs
you should not use this method in production code, because its implementation may change—or be removed outright—without notice.
...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).
HTMLMediaElement - Web APIs
keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working.
... 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.
HTMLVideoElement - Web APIs
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.
IDBCursorSync - Web APIs
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.
... 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.
IDBDatabaseException - Web APIs
attributes attribute type description code unsigned short the most appropriate error code for the condition.
... 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.
IDBRequest.error - Web APIs
WebAPIIDBRequesterror
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.
... in addition to the error codes sent to the idbrequest object, asynchronous operations can also raise exceptions.
IDBTransaction - Web APIs
ts: all;} transactions are started when the transaction is created, not when the first request is placed; for example consider this: var trans1 = db.transaction("foo", "readwrite"); var trans2 = db.transaction("foo", "readwrite"); var objectstore2 = trans2.objectstore("foo") var objectstore1 = trans1.objectstore("foo") objectstore2.put("2", "key"); objectstore1.put("1", "key"); after the code is executed the object store should contain the value "2", since trans2 should run after trans1.
...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.
IIRFilterNode - Web APIs
examples you can find a simple iir filter demo live on codepen.
... also see the source code on github.
Basic concepts - Web APIs
they also have readystate, result, and errorcode properties that tell you the status of the request.
...you have to write code that synchronizes a client-side indexeddb database with a server-side database.
Checking when a deadline is due - Web 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.
...when a notification is fired for each item object, its notification property is set to "yes" so this check will not pass on the next iteration, via the following code inside the createnotification() function (read using indexeddb for an explanation): // now we need to update the value of notified to "yes" in this particular data object, so the // notification won't be set off on it again // first open up a tranaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object...
LocalFileSystemSync - Web APIs
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.
... exceptions this method can raise a fileexception with the following codes: exception description encoding_err the syntax of the url was invalid.
MediaCapabilities.decodingInfo() - Web APIs
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 : "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.
MediaCapabilities.encodingInfo() - Web APIs
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 encodinginfo() method is invalid, either 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.
MediaDevices.getDisplayMedia() - Web APIs
invalidstateerror the call to getdisplaymedia() was not made from code running due to a user action, such as an event handler.
... the call to getdisplaymedia() must be made from code which is running in response to a user action, such as in an event handler.
MediaRecorder() - Web APIs
the object can optionally be configured to record using a specific media container (file type), and, further, can specify the exact codec and codec configuration(s) to use by specifying the codecs parameter.
... 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.
MediaRecorder: dataavailable event - Web APIs
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); }); ...
... 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); } ...
MediaRecorder.ondataavailable - Web APIs
the mediarecorder.ondataavailable event handler (part of the mediastream recording api) handles the dataavailable event, letting you run code in response to blob data being made available for use.
... 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); } ...
MediaRecorder.onstop - Web APIs
the mediarecorder.onstop event handler (part of the mediarecorder api) handles the stop event, allowing you to run code in response to media recording via a mediarecorder being stopped.
... 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); } ...
MediaSource.MediaSource() - Web APIs
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); } ...
MediaSource.addSourceBuffer() - Web APIs
example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) 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); } 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 }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'addsourcebuffer()' in that specification.
MediaSource.readyState - Web APIs
example the following snippet is from a simple example written by nick desaulniers (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 = mediasour...
...ce.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'readystate' in that specification.
MediaSource - Web APIs
this example was written by nick desaulniers and can be viewed live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var 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); } 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 }); sourcebuffer.appendbuffer(buf); }); }; function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); }; specifications specification status comment media source extensionsthe definition of 'mediasource...
MediaStreamAudioSourceNode - Web APIs
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.
MediaStreamTrack.getSettings() - Web APIs
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().
MediaStream Image Capture API - Web APIs
the example code is adapted from chrome's image capture examples.
...the code below assumes that the first item in the mediastreamtrack array is the one to use.
MediaTrackConstraints.cursor - Web APIs
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.
MediaTrackConstraints.displaySurface - Web APIs
for example, if your app needs 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-...
...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.
Media Source API - Web APIs
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.
MessagePort: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessa...
...ge('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages on it using code like this: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.addeventlistener('message', (event) => { received.textcontent = event.data; }); myport.start(); }); note that the listener must call messageport.start() before any messages will be delivered to this port.
MessagePort: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; 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 will be delivered to this port.
NDEFRecord.data - Web APIs
WebAPINDEFRecorddata
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.
Navigation Timing API - Web APIs
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).
... 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).
Navigator.clipboard - Web APIs
examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard.
...perhaps this code is being used in a browser extension that displays the current clipboard contents, automatically updating periodically or when specific events fire.
Navigator - Web APIs
WebAPINavigator
standard navigatorid.appcodename read only returns the internal "code" name of the current browser.
... non-standard navigator.mozislocallyavailable() lets code check to see if the document at a given uri is available without using the network.
NavigatorID.userAgent - Web APIs
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.
...gecko-based browsers comply with the following general structure: useragent = appcodename/appversion number (platform; security; os-or-cpu; localization; rv: revision-version-number) product/productsub application-name application-name-version example alert(window.navigator.useragent) // alerts "mozilla/5.0 (windows; u; win98; en-us; rv:0.9.2) gecko/20010725 netscape6/6.1" specifications specification status comment html living standardthe defi...
NavigatorID - Web APIs
navigatorid.appcodename read only always returns "mozilla", in any browser.
... living standard added the appcodename property and the taintenabled() method, for compatibility purpose.
NavigatorLanguage.language - Web APIs
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.
Notification.Notification() - Web APIs
see the sitepoint iso 2 letter language codes page for a simple reference.
... example in our emogotchi demo (see source code), we run a spawnnotification() function when we want to trigger a notification.
Notification.requestPermission() - Web APIs
read using the notifications api for a good example of how to feature detect this and run code as appropriate.
...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.
Notification - Web APIs
notification.lang read only the language code of the notification as specified in the constructor's options parameter.
... 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.
Using the Notifications API - Web APIs
download the to-do list code, or view the app running live.
... 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.
OffscreenCanvas - Web APIs
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.
... 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"); // ...
PannerNode.orientationY - Web APIs
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.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which ...
PannerNode.orientationZ - Web APIs
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.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which ...
PaymentCurrencyAmount.currency - Web APIs
the value is always specified using the 3-letter codes defined by the iso 4127 standard.
... syntax currency = paymentcurrencyamount.currency; value a domstring specifying the canonical, three-character currency identification code defined by the iso 4217 standard.
PaymentRequest: merchantvalidation event - Web APIs
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.
... 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.
PaymentRequest: paymentmethodchange event - Web APIs
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.
PaymentRequest: shippingoptionchange event - Web APIs
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.
PerformanceEventTiming - Web APIs
// 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.
...this code // uses `/analytics`; you can replace it with your own url.
PerformanceResourceTiming - Web APIs
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.
Multi-touch interaction - Web APIs
this document demonstrates via example code, using pointer events with different multi-touch interactions.
...the source code is available on github; pull requests and bug reports are welcome.
PromiseRejectionEvent.promise - Web APIs
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.
... 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.
PublicKeyCredential.id - Web APIs
this property is a base64url encoded version of publickeycredential.rawid.
... syntax id = publickeycredential.id value a domstring being the base64url encoded version of publickeycredential.rawid.
RTCDTMFSender.toneBuffer - Web APIs
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".
... settting the tone buffer to an empty string ("") cancels any pending dtmf codes.
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
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 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().
RTCDataChannel.id - Web APIs
WebAPIRTCDataChannelid
code that uses that property needs to be updated.
...a unique id makes it easier for your code to do its own out-of-band data channel-related signaling.
RTCDataChannel: message event - Web APIs
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.
...ndler property to set the event handler: dc.onmessage = ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'the <code>message</code> event' in that specification.
RTCDtlsTransport - Web APIs
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.
... "connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; case "failed": results.failed++; break; default: results.unknown++; break; } } }); return results; } note that in this code, the new and connecting states are being treated as a single connectionpending status in the returned object.
RTCIceCandidate.candidate - Web APIs
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.
... 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.
RTCIceCandidatePairStats - Web APIs
you should update any existing code to avoid using them as soon as is practical.
... 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.
RTCIceServer.url - Web APIs
WebAPIRTCIceServerurl
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.
...try to update any existing code to use that property instead.
RTCIceTransport: statechange event - Web APIs
bubbles no cancelable no interface event event handler property rtcicetransport.onstatechange examples given an rtcpeerconnection, pc, the following code creates an event handler that calls a function named handlefailure() if the ice transport enters a failure state.
... let icetransport = pc.getsenders()[0].transport.icetransport; icetransport.addeventlistener("statechange", ev => { if (icetransport.state === "failed") { handlefailure(pc); } }, false); the same code, using the onstatechange event handler property, looks like this: let icetransport = pc.getsenders()[0].transport.icetransport; icetransport.onstatechange = ev => { if (icetransport.state === "failed") { handlefailure(pc); } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'statechange' in that specification.
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.
...each key is the string representation of a single differentiated services code point (dscp)'s id number.
RTCInboundRtpStreamStats.pliCount - Web APIs
a pli packet indicates that some amount of encoded video data has been lost for one or more frames.
...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.
RTCInboundRtpStreamStats.sliCount - Web APIs
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.
... this is a very technical part of how video codecs work.
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.
...each key is the string representation of a single differentiated services code point (dscp)'s id number.
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.
... 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.
RTCOutboundRtpStreamStats.sliCount - Web APIs
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.
... this is a very technical part of how video codecs work.
RTCPeerConnection.addTrack() - Web APIs
example this example is drawn from the code presented in the article signaling and video calling and its corresponding sample code.
..., // we want an audio track video: true // ...and we want a video track }; var desc = new rtcsessiondescription(sdp); pc.setremotedescription(desc).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { previewelement.srcobject = stream; stream.gettracks().foreach(track => pc.addtrack(track, stream)); }) this code takes sdp which has been received from the remote peer and constructs a new rtcsessiondescription to pass into setremotedescription().
RTCPeerConnection.getStreamById() - Web APIs
if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream.
... 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.
RTCPeerConnection.ontrack - Web APIs
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.
...the second line of code simply enables a "hang up" button, which the user can use to disconnect from the call.
RTCPeerConnection.signalingState - Web APIs
because the signaling process is a state machine, being able to verify that your code is in the expected state when messages arrive can help avoid unexpected and avoidable failures.
...your code will be more reliable if you watch for mismatched states like this and handle them gracefully.
RTCPeerConnectionIceErrorEvent - Web APIs
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.
RTCRtpEncodingParameters.maxBitrate - Web APIs
the rtcrtpencodingparameters dictionary's maxbitrate property specifies the maximum number of bits per second to allow a track encoded with this encoding to use.
... syntax rtpencodingparameters.maxbitrate = maxbitspersecond; rtpencodingparameters = { maxbitrate: maxbitspersecond }; maxbitspersecond = rtpencodingparameters.maxbitrate; value an unsigned long integer value specifying the maximum bandwidth this encoding is permitted to use for a track of media it encodes in terms of bits per second.
RTCRtpStreamStats.pliCount - Web APIs
a pli packet indicates that some amount of encoded video data has been lost for one or more frames.
... 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.
ReadableStream.cancel() - Web APIs
var searchterm = "service workers"; // chars to show either side of the result in the match var contextbefore = 30; var contextafter = 30; var caseinsensitive = true; var url = 'https://html.spec.whatwg.org/'; console.log(`searching '${url}' for '${searchterm}'`); fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); var reader = response.body.getreader(); var tomatch = caseinsensitive ?
...ar buffersize = math.max(tomatch.length - 1, contextbefore); var bytesreceived = 0; var buffer = ''; var matchfoundat = -1; return reader.read().then(function process(result) { if (result.done) { console.log('failed to find match'); return; } bytesreceived += result.value.length; console.log(`received ${bytesreceived} bytes of data so far`); buffer += decoder.decode(result.value, {stream: true}); // already found match & just context-gathering?
ReadableStream.pipeThrough() - Web APIs
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.
... 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.
Reporting API - Web APIs
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).
... note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia() method twice.
Resize Observer API - Web APIs
the resize observer api provides a performant mechanism by which code can monitor an element for changes to its size, with notifications being delivered to the observer each time the size changes.
... the code will usually follow this kind of pattern (taken from resize-observer-border-radius.html): const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { entry.target.style.borderradius = math.min(100, (entry.contentboxsize.inlinesize/10) + (entry.contentboxsize.blocksize/10)) + 'px';...
Resource Timing API - Web APIs
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.
Response() - Web APIs
WebAPIResponseResponse
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.
Response - Web APIs
WebAPIResponse
response.status read only the status code of the response.
... response.statustext read only the status message corresponding to the status code.
SVGAnimationElement - Web APIs
if there is no current interval, then a domexception with code invalid_state_err is thrown.
...if the simple duration is undefined (e.g., the end time is indefinite), then a domexception with code not_supported_err is raised.
SVGImageElement - Web APIs
svgimageelement.decoding returns a domstring representing a hint given to the browser on how it should decode the image.
... svgimageelement.decode() initiates asynchronous decoding of the image data.
SVGMarkerElement - Web APIs
exceptions: a domexception with code no_modification_allowed_err is raised when the object itself is read only.
... exceptions: a domexception with code no_modification_allowed_err is raised when the object itself is read only.
ServiceWorker.onstatechange - Web APIs
} ) examples this code snippet is from the service worker registration-events sample (live demo).
... the code listens for any change in the serviceworker.state and returns its value.
ServiceWorker.state - Web APIs
syntax someurl = serviceworker.state value a serviceworkerstate definition (see the spec.) examples this code snippet is from the service worker registration-events sample (live demo).
... the code listens for any change in the serviceworker.state and returns its value.
ServiceWorker - Web APIs
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.
SourceBuffer.changeType() - Web APIs
this makes it possible to change codecs or container type mid-stream.
... one scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change.
Using the Storage Access API - Web APIs
</iframe> now on to the code executed inside the embedded document.
...}); 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
WebAPITouchforce
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.
... for (var i=0; i < e.targettouches.length; i++) { // add code to "switch" based on the force value.
Multi-touch interaction - Web APIs
the source code is available on github and pull requests and bug reports are welcome.
...the code does not include error handling, or vertical moving.
Using Touch Events - Web APIs
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.
... 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.
URLUtilsReadOnly - Web APIs
nohash experimentalchrome no support noedge no support nofirefox full support 38 full support 38 no support 3.5 — 38notes notes before firefox 38, firefox returned the hash percent encoded.
... nowebview android no support nochrome android no support nofirefox android full support 38 full support 38 no support 4 — 38notes notes before firefox 38, firefox returned the hash percent encoded.
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.
WEBGL_compressed_texture_etc - Web APIs
the rgb part is encoded the same as rgb_etc2, but the alpha part is encoded separately.
...the srgb part is encoded the same as srgb_etc2, but the alpha part is encoded separately.
WaveShaperNode.curve - Web APIs
for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
...we found the below distortion curve code on stack overflow.
WaveShaperNode.oversample - Web APIs
for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
...we found the below distortion curve code on stack overflow.
WaveShaperNode - Web APIs
for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
...we found the below distortion curve code on stack overflow.
WebGLRenderingContext.getShaderInfoLog() - Web APIs
examples checking compilation messages /* load shader source code.
... */ gl.shadersource(shader, shadercode); /* compile shader source code.
WebGLRenderingContext.makeXRCompatible() - Web APIs
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.
... javascript the code that handles starting up graphics, switching to vr mode, and so forth looks like this: const outputcanvas = document.queryselector(".output-canvas"); const gl = outputcanvas.getcontext("webgl"); let xrsession = null; let usingxr = false; let currentscene = "scene1"; let glstartbutton; let xrstartbutton; window.addeventlistener("load", (event) => { loadsceneresources(currentscene); glstartb...
Hello GLSL - Web APIs
but remember to read through the explanations and code on this page, before moving on to the next.
...experimental-webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Raining rectangles - Web APIs
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.
...experimental-webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
WebGL constants - Web APIs
the rgb part is encoded the same as rgb_etc2, but the alpha part is encoded separately.
...the srgb part is encoded the same as srgb_etc2, but the alpha part is encoded separately.
WebGL tutorial - Web APIs
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).
...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.
WebGL best practices - Web APIs
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).
...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.
WebRTC connectivity - Web APIs
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.
WebRTC Statistics API - Web APIs
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.
Web Video Text Tracks Format (WebVTT) - Web APIs
webvtt is a text based format, which must be encoded using utf-8.
...the interface code is given below which can be used to expose the webvtt regions in dom api: enum scrollsetting { "" /* none */, "up" }; [constructor] interface vttregion { attribute double width; attribute long lines; attribute double regionanchorx; attribute double regionanchory; attribute double viewportanchorx; attribute double viewportanchory; attribute scrollsetting scroll; }; methods and prop...
WebXR application life cycle - Web APIs
in this guide, we'll get a birds-eye view of what's involved in creating and driving a webxr application, without diving down to the code level in detail.
... 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
however, there are issues and details to keep in mind while creating your lighting code, especially for augmented reality (ar) applications.
... 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.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
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().
... for example, given an xrsession whose reference space is worldrefspace, the following line of code would request the first frame of animation to be scheduled: animationframerequestid = xrsession.requestanimationframe(mydrawframe); then, the mydrawframe() function—the callback executed when it's time to draw the frame—might be something like this: function mydrawframe(currentframetime, frame) { let session = frame.session; let viewerpose = frame.getviewerpose(viewerrefspace); ani...
Example and tutorial: Simple synth keyboard - Web APIs
this article presents the code and working demo of a video keyboard you can play using the mouse.
...t: 30px; } .left { width: 50%; position: absolute; left: 0; display: table-cell; vertical-align: middle; } .left span, .left input { vertical-align: middle; } .right { width: 50%; position: absolute; right: 0; display: table-cell; vertical-align: middle; } .right span { vertical-align: middle; } .right input { vertical-align: baseline; } javascript the javascript code begins by initializing a number of variables.
Web Locks API - Web APIs
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.
...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.
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 ...
... note: as well as viewing the example pages live using the above links, you can also check out the source code.
Functions and classes available to Web Workers - Web APIs
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.
... 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.
Window.controllers - Web APIs
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).
Window.devicePixelRatio - Web APIs
javascript the javascript code creates the media query that monitors the device resolution and checks the value of devicepixelratio any time it changes.
... <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>.
Window.history - Web APIs
WebAPIWindowhistory
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.
Window.matchMedia() - Web APIs
WebAPIWindowmatchMedia
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.
... 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.
Window.screenX - Web APIs
WebAPIWindowscreenX
examples in our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle.
... also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using screenx/screeny.
Window: unhandledrejection event - Web APIs
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.
... window.addeventlistener('unhandledrejection', function (event) { // ...your code here to handle the unhandled rejection...
Worker - Web APIs
WebAPIWorker
worker.onmessageerror is an eventhandler representing the code to be called when the messageerror event is raised.
... example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker = new worker('/worker.js'); var first = document.queryselector('input#number1'); var second = document.queryselector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a full example, see our...
WorkerGlobalScope.self - Web APIs
example if you called console.log(self); inside a worker, you will 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: funct...
...ion blob() { [native code] } boolean: function boolean() { [native code] } dataview: function dataview() { [native code] } date: function date() { [native code] } dedicatedworkerglobalscope: function dedicatedworkerglobalscope() { [native code] } error: function error() { [native code] } // etc.
Worklet - Web APIs
WebAPIWorklet
with worklets, you can run javascript and webassembly code to do graphics rendering or audio processing where high performance is required.
...instead, you write vertex shaders and fragment shaders using glsl code, and those shaders will then run on the graphics card.
Sending and Receiving Binary Data - Web APIs
note that this will not decode the image and read the pixels.
... 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.
XMLHttpRequest.openRequest() - Web APIs
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 - Web APIs
non-standard methods xmlhttprequest.init() initializes the object for use from c++ code.
...this method is to be used from native code; to initialize a request from javascript code, use open() instead.
XRInputSource.targetRayMode - Web APIs
example this fragment of code shows part of a function to be called once every frame.
... 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.
XRInputSource.targetRaySpace - Web APIs
example this fragment of code shows part of a function to be called once every frame.
... 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.
XRSession.onsqueeze - Web APIs
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 just a snippet of code, but should establish the general idea.
XRSession: selectend event - Web APIs
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.
... 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.
XRSession: selectstart event - Web APIs
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.
... 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.
XRSession: squeezeend event - Web APIs
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.
... 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.
XRSession: squeezestart event - Web APIs
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.
... 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.
XRSystem - Web APIs
WebAPIXRSystem
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.
... 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.
XRTargetRayMode - Web APIs
examples this fragment of code shows part of a function to be called once every frame.
... 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.
XRViewerPose.views - Web APIs
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.
... this code is derived from drawing a frame in movement, orientation, and motion: a webxr example.
XRViewerPose - Web APIs
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.
... this code is derived from drawing a frame in movement, orientation, and motion: a webxr example.
Using the group role - Accessibility
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.
...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.
Using the slider role - Accessibility
<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.
... <label id="day-label">days</label> <div class="day-slider"> <div id="day-handle" class="day-slider-handle" role="slider" aria-labelledby="day-label" aria-valuemin="1" aria-valuemax="7" aria-valuenow="2" aria-valuetext="monday"> </div> </div> the code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var daynames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var updateslider = function (newvalue) { var handle = document.getelementbyid("day-handle"); handle.setattribute("aria-valuenow", newvalue.tostring()); handle.setattribute...
ARIA: Region role - Accessibility
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!
... <div role="region" aria-labelledby="heading"> <h3 id="use-discretion">please use the <code>region</code> role with discretion</h3> <!-- content --> </div> ...
ARIA: tab role - Accessibility
if the event's keycode is 39 for right arrow or 37 for the left arrow, we react to the event.
... { 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
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.
...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.
Web applications and ARIA FAQ - Accessibility
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.
...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.
Accessibility documentation index - Accessibility
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.
...these elements could be images, code snippets, text, emojis, or other content that can be combined to deliver information in a visual manner.
Accessibility Information for Web Authors - Accessibility
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.
Text labels and names - Accessibility
example the following example shows code for a figure with a caption.
...since mglyph elements are used for non-standard symbols without unicode definitions, screen readers won't automatically be able to name them.
Understandable - Accessibility
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.
...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.
-moz-image-rect - CSS: Cascading Style Sheets
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.
:lang() - CSS: Cascading Style Sheets
WebCSS:lang
syntax formal syntax :lang( <language-code> ) parameter <language-code> a <string> representing the language you want to target.
...also note that unicode values are used to specify some of the special quote characters.
@charset - CSS: Cascading Style Sheets
WebCSS@charset
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.
... formal syntax @charset "<charset>"; examples valid and invalid charset declarations @charset "utf-8"; /* set the encoding of the style sheet to unicode utf-8 */ @charset 'iso-8859-15'; /* invalid, wrong quoting style used */ @charset "utf-8"; /* invalid, more than one space */ @charset "utf-8"; /* invalid, there is a character (a space) before the at-rule */ @charset utf-8; /* invalid, without ' or ", the charset is not a css <string> */ specifications specification status comment css level 2 (r...
@font-face - CSS: Cascading Style Sheets
unicode-range the range of unicode code points to be used from the font.
...for example, the following will not work: .classname { @font-face { font-family: myhelvetica; src: local("helvetica neue bold"), local("helveticaneue-bold"), url(mgopenmodernabold.ttf); font-weight: bold; } } formal syntax @font-face { [ font-family: <family-name>; ] | [ src: <src>; ] | [ unicode-range: <unicode-range>; ] | [ font-variant: <font-variant>; ] | [ font-feature-settings: <font-feature-settings>; ] | [ font-variation-settings: <font-variation-settings>; ] | [ font-stretch: <font-stretch>; ] | [ font-weight: <font-weight>; ] | [ font-style: <font-style>; ] }where <family-name> = <string> | <custom-ident>+ examples specifying a downloadable font this example simpl...
@media - CSS: Cascading Style Sheets
WebCSS@media
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.
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...
Mastering margin collapsing - CSS: Cascading Style Sheets
examples html <p>the bottom margin of this paragraph is collapsed …</p> <p>… with the top margin of this paragraph, yielding a margin of <code>1.2rem</code> in between.</p> <div>this parent element contains two paragraphs!
... <p>this paragraph has a <code>.4rem</code> margin between it and the text above.</p> <p>my bottom margin collapses with my parent, yielding a bottom margin of <code>2rem</code>.</p> </div> <p>i am <code>2rem</code> below the element above.</p> css div { margin: 2rem 0; background: lavender; } p { margin: .4rem 0 1.2rem 0; background: yellow; } result specifications specification status comment css level 2 (revision 1)the definition of 'margin collapsing' in that specification.
OpenType font features guide - CSS: Cascading Style Sheets
the general syntax looks like this: .small-caps { font-feature-settings: "smcp", "c2sc"; } 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.
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
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.
... .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.
Grid template areas - CSS: Cascading Style Sheets
using grid-template-areas can be especially nice as it is easy to see in the code what your element looks like.
... the following code creates a layout using grid-template that is the same as the layout created earlier in this guide.
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
art: 1; grid-row-end: 4; } .box2 { grid-column-start: 3; grid-column-end: 4; grid-row-start: 1; grid-row-end: 3; } .box3 { grid-column-start: 2; grid-column-end: 3; grid-row-start: 1; grid-row-end: 2; } .box4 { grid-column-start: 2; grid-column-end: 4; grid-row-start: 3; grid-row-end: 4; } the grid-column and grid-row shorthands we have quite a lot of code here to position each item.
..."box3">three</div> <div class="box4">four</div> </div> .box1 { grid-column-start: 1; grid-row-start: 1; grid-row-end: 4; } .box2 { grid-column-start: 3; grid-row-start: 1; grid-row-end: 3; } .box3 { grid-column-start: 2; grid-row-start: 1; } .box4 { grid-column-start: 2; grid-column-end: 4; grid-row-start: 3; } our shorthand would look like the following code, with no forward slash and second value for the items spanning one track only.
Stacking context example 3 - CSS: Cascading Style Sheets
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.
... example source code <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html> <head><style type="text/css"> div { font: 12px arial; } span.bold { font-weight: bold; } div.lev1 { width: 250px; height: 70px; position: relative; border: 2px outset #669966; background-color: #ccffcc; padding-left: 5px; } #container1 { z-index: 1; position: absolute; top: 30px; left: 75px; } div.lev2 { opacity: 0.9; width: 200px; height: 60px; position: relative; border: 2px outset #990000; background-color: #ffdddd; padding-left: 5px; } #container2 { z-index: 1; position: absolute; top: 20px; left: 110px; } div.lev3...
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...
..."> <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 #696; padding: 10px; background-color: #cfc; } #div1 { z-index: 5; margin-bottom: 190px; } #div2 { z-index: 2; } #div3 { z-index: 4; opacity: 1; position: absolute; top: 40px; left: 180px; width: 330px; border: 1px dashed #900; background-color: #fdd; padding: 40px 20px 20px; } #div4, #div5 { border: 1px dashed #996; backgrou...
Testing media queries programmatically - CSS: Cascading Style Sheets
mediaquerylist.addlistener(handleorientationchange); this code creates the orientation-testing media query list, then adds an event listener to it.
...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.
border-collapse - CSS: Cascading Style Sheets
formal definition initial valueseparateapplies totable and inline-table elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax collapse | separate examples a colorful table of browser engines html <table class="separate"> <caption><code>border-collapse: separate</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...
...ra</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">opera</td> <td class="bk">blink</td></tr> </tbody> </table> css .collapse { border-collapse: collapse; } .separate { border-collapse: separate; } table { display: inline-table; margin: 1em; border: dashed 5px; } table th, table td { border: solid 3px; } .fx { border-color: orange blue; ...
border-color - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples complete border-color usage html <div id="justone"> <p><code>border-color: red;</code> is equivalent to</p> <ul><li><code>border-top-color: red;</code></li> <li><code>border-right-color: red;</code></li> <li><code>border-bottom-color: red;</code></li> <li><code>border-left-color: red;</code></li> </ul> </div> <div id="horzvert"> <p><code>border-color: gold red;</code> is equivalent to</p> <ul><li><code>border-top-color: gold;</code></li...
...> <li><code>border-right-color: red;</code></li> <li><code>border-bottom-color: gold;</code></li> <li><code>border-left-color: red;</code></li> </ul> </div> <div id="topvertbott"> <p><code>border-color: red cyan gold;</code> is equivalent to</p> <ul><li><code>border-top-color: red;</code></li> <li><code>border-right-color: cyan;</code></li> <li><code>border-bottom-color: gold;</code></li> <li><code>border-left-color: cyan;</code></li> </ul> </div> <div id="trbl"> <p><code>border-color: red cyan black gold;</code> is equivalent to</p> <ul><li><code>border-top-color: red;</code></li> <li><code>border-right-color: cyan;</code></li> <li><code>border-bottom-color: black;</code></li> <li><code>border-left-color: gold;</code></li> </ul> </div> css ...
<custom-ident> - CSS: Cascading Style Sheets
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.
... 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.
env() - CSS: Cascading Style Sheets
WebCSSenv
<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.
<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 { ...
... 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 === 'brightness' || filter === 'contrast' || filter === 'saturate') { slider.value = 1; slider.min = 0; slide...
hyphens - CSS: Cascading Style Sheets
WebCSShyphens
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.
... html <dl> <dt><code>none</code>: no hyphen; overflow if needed</dt> <dd lang="en" class="none">an extreme&shy;ly long english word</dd> <dt><code>manual</code>: hyphen only at &amp;hyphen; or &amp;shy; (if needed)</dt> <dd lang="en" class="manual">an extreme&shy;ly long english word</dd> <dt><code>auto</code>: hyphens where the algorithm decides (if needed)</dt> <dd lang="en" class="auto">an extreme&shy;ly...
ident - CSS: Cascading Style Sheets
WebCSSident
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.
... 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.
max-block-size - CSS: Cascading Style Sheets
<p>writing mode <code>horizontal-tb</code> (the default):</p> <div class="standard-box horizontal"> call me ishmael.
...</div> <p>writing mode <code>vertical-rl</code>:</p> <div class="standard-box vertical"> call me ishmael.
offset-path - CSS: Cascading Style Sheets
| [ [ 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.
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...
...de 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;} #div4 { overflow-inline: auto;} result specifications specification status comment css overflow module level 3the definition of 'overflow-inline' in that specification.
overflow-x - CSS: Cascading Style Sheets
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 n...
...eeded <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;} result specifications specification status comment css overflow module level 3the definition of 'overflow-x' in that specification.
perspective - CSS: Cascading Style Sheets
<table> <tbody> <tr> <th><code>perspective: 250px;</code> </th> <th><code>perspective: 350px;</code> </th> </tr> <tr> <td> <div class="container"> <div class="cube pers250"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top...
... <div class="container"> <div class="cube pers350"> <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> </td> </tr> <tr> <th><code>perspective: 500px;</code> </th> <th><code>perspective: 650px;</code> </th> </tr> <tr> <td> <div class="container"> <div class="cube pers500"> <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...
<ratio> - CSS: Cascading Style Sheets
WebCSSratio
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>.
... 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>.
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>...
... excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </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.addeventlis...
Adding captions and subtitles to HTML5 video - Developer guides
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.
...ement('ul')); subtitlesmenu.classname = 'subtitles-menu'; subtitlesmenu.appendchild(createmenuitem('subtitles-off', '', 'off')); for (var i = 0; i < video.texttracks.length; i++) { subtitlesmenu.appendchild(createmenuitem('subtitles-' + video.texttracks[i].language, video.texttracks[i].language, video.texttracks[i].label)); } videocontainer.appendchild(subtitlesmenu); } this code creates a documentfragment, which is used to hold an unordered list containing our subtitles menu.
Rich-Text Editing in Mozilla - Developer guides
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.
...ion getiframedocument(aid){ // if contentdocument exists, w3c compliant (mozilla) if (document.getelementbyid(aid).contentdocument){ return document.getelementbyid(aid).contentdocument; } else { // ie return document.frames[aid].document; } } the example contains a doricheditcommand function that makes it easier to execute commands on the iframe's document and keeps the html code clean.
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(...
...nt("section"); document.createelement("time"); </script> <![endif]--> <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> note: this code will also cause the html validator to return errors.
Mobile Web Development - Developer guides
WebGuideMobile
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.
... 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.
User input and controls - Developer guides
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.
...bear in mind that many browsers still implement this with a vendor prefix, so you will probably need to fork your code something like this: var elem = document.getelementbyid("myvideo"); if (elem.requestfullscreen) { elem.requestfullscreen(); } else if (elem.msrequestfullscreen) { elem.msrequestfullscreen(); } else if (elem.mozrequestfullscreen) { elem.mozrequestfullscreen(); } else if (elem.webkitrequestfullscreen) { elem.webkitrequestfullscreen(); } note: to find more out about adding fullscreen func...
HTML attribute: maxlength - HTML: Hypertext Markup Language
the maxlength attribute defines the maximum number of characters (as utf-16 code units) the user can enter into an <input> or <textarea>.
...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.
HTML attribute: minlength - HTML: Hypertext Markup Language
the minlength attribute defines the minimum number of characters (as utf-16 code units) the user can enter into an <input> or <textarea>.
... 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.
HTML attribute: pattern - HTML: Hypertext Markup Language
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.
... examples given the following: <p> <label>enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"/> </label> </p> here we have 3 sections for a north american phone number with an implicit label encompassing all three components of the phone number, expecting 3-...
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
WebHTMLElementbdi
browsers implement the unicode bidirectional algorithm to handle this.
... 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.
<button>: The Button element - HTML: Hypertext Markup Language
WebHTMLElementbutton
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.
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
WebHTMLElementcanvas
examples html this code snippet adds a canvas element to your html document.
...</canvas> javascript then in the javascript code, call htmlcanvaselement.getcontext() to get a drawing context and start drawing onto the canvas: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); result accessibility concerns alternative content the <canvas> element on its own is just a bitmap and does not provide information about any drawn objects.
<col> - HTML: Hypertext Markup Language
WebHTMLElementcol
they are documented below for reference when updating existing code and for historical interest only.
...it is a 6-digit hexadecimal rgb code, prefixed by a '#'.
<colgroup> - HTML: Hypertext Markup Language
WebHTMLElementcolgroup
they are documented below for reference when updating existing code and for historical interest only.
...it is a 6-digit hexadecimal rgb code, prefixed by a '#'.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcontent
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.
... note: for this code to work, the browser you display it in must support web components.
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
</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.
... result the output of the above code looks like this: specifications specification status comment html living standardthe definition of '<dfn>' in that specification.
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
WebHTMLElementfigure
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.
... examples images <!-- 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...
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
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.
<input type="hidden"> - HTML: Hypertext Markup Language
WebHTMLElementinputhidden
note: there is a live example below the following line of code — if it is working correctly, you should see nothing!
... the output looks like this: note: you can also find the example on github (see the source code, and also see it running live).
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
the user never sees the value or the name (unless you expressly add code to display it).
... let's add a little bit of code to our example so we can examine the data generated by this form.
<listing> - HTML: Hypertext Markup Language
WebHTMLElementlisting
instead use the <pre> element or if semantically adequate the <code> element, eventually escaping the html '<' and '>' so that they don't get interpreted.
... see also the <pre> and <code> elements to be used instead.
<object> - HTML: Hypertext Markup Language
WebHTMLElementobject
codebasehtml 4 onlyobsolete since html5 the base path used to resolve relative uris specified by classid, data, or archive.
... codetypehtml 4 onlyobsolete since html5 the content type of the data specified by classid.
<table>: The Table element - HTML: Hypertext Markup Language
WebHTMLElementtable
it is a 6-digit hexadecimal rgb code, prefixed by a '#'.
... example <table> <caption>color names and values</caption> <tbody> <tr> <th scope="col">name</th> <th scope="col">hex</th> <th scope="col">hsla</th> <th scope="col">rgba</th> </tr> <tr> <th scope="row">teal</th> <td><code>#51f6f6</code></td> <td><code>hsla(180, 90%, 64%, 1)</code></td> <td><code>rgba(81, 246, 246, 1)</code></td> </tr> <tr> <th scope="row">goldenrod</th> <td><code>#f6bc57</code></td> <td><code>hsla(38, 90%, 65%, 1)</code></td> <td><code>rgba(246, 188, 87, 1)</code></td> </tr> </tbody> </table> providing a declaration of scope="col" on a <th> eleme...
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
maxlength the maximum number of characters (utf-16 code units) that the user can enter.
... minlength the minimum number of characters (utf-16 code units) required that the user should enter.
<wbr> - HTML: Hypertext Markup Language
WebHTMLElementwbr
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.
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
<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.
... <script> the html <script> element is used to embed executable code or data; this is typically used to embed or refer to javascript code.
Evolution of HTTP - HTTP
there were no 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.
... http/1.0 – building extensibility http/0.9 was very limited and both browsers and servers quickly extended it to be more versatile: versioning information is now sent within each request (http/1.0 is appended to the get line) a status code line is also sent at the beginning of the response, allowing the browser itself to understand the success or failure of the request and to adapt its behavior in consequence (like in updating or using its local cache in a specific way) the notion of http headers has been introduced, both for the requests and the responses, allowing metadata to be transmitted and making the protocol extremely flexible and extensible.
CORS errors - HTTP
WebHTTPCORSErrors
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.
Content Security Policy (CSP) - HTTP
WebHTTPCSP
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.
... status-code the http status code of the resource on which the global object was instantiated.
Configuring servers for Ogg media - HTTP
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.
... 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.
Cache-Control - HTTP
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.
...the cache should either respond using a stored response, or respond with a 504 status code.
CSP: child-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: connect-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: font-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: frame-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: manifest-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: media-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: object-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: style-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
CSP: worker-src - HTTP
'unsafe-eval' allows the use of eval() and similar methods for creating code from strings.
...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.
If-None-Match - HTTP
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.
Firefox user agent string reference - HTTP
this way, your code will work if/when firefox ships on other phone/tablet operating systems or android is used for laptops.
...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).
PATCH - HTTP
WebHTTPMethodsPATCH
se has body yes safe no idempotent no cacheable no allowed in html forms no syntax patch /file.txt http/1.1 example request patch /file.txt http/1.1 host: www.example.com content-type: application/example if-match: "e0023aa4e" content-length: 100 [description of changes] response a successful response is indicated by any 2xx status code.
... in the example below a 204 response code is used, because the response does not carry a payload body.
An overview of HTTP - HTTP
WebHTTPOverview
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.
Protocol upgrade mechanism - HTTP
right after sending the 101 status code, the server can begin speaking the new protocol, performing any additional protocol-specific handshakes as necessary.
...that value is then base64 encoded to obtain the value of this property.
100 Continue - HTTP
WebHTTPStatus100
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.
201 Created - HTTP
WebHTTPStatus201
the http 201 created success status response code indicates that the request has succeeded and has led to the creation of a resource.
... the common use case of this status code is as the result of a post request.
300 Multiple Choices - HTTP
WebHTTPStatus300
the http 300 multiple choices redirect status response code indicates that the request has more than one possible responses.
...as there is no standardized way of choosing one of the responses, this response code is very rarely used.
301 Moved Permanently - HTTP
WebHTTPStatus301
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.
...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.
302 Found - HTTP
WebHTTPStatus302
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.
...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.
303 See Other - HTTP
WebHTTPStatus303
the hypertext transfer protocol (http) 303 see other redirect status response code indicates that the redirects don't link to the newly uploaded resources, but to another page (such as a confirmation page or an upload progress page).
... this response code is usually sent back as a result of put or post.
308 Permanent Redirect - HTTP
WebHTTPStatus308
the hypertext transfer protocol (http) 308 permanent redirect redirect status response code indicates that the resource requested has been definitively moved to the url given by the location headers.
...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) ...
402 Payment Required - HTTP
WebHTTPStatus402
the http 402 payment required is a nonstandard client error status response code that is reserved for future use.
... sometimes, this code indicates that the request can not be processed until the client makes a payment.
410 Gone - HTTP
WebHTTPStatus410
the hypertext transfer protocol (http) 410 gone client error response code indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent.
... if you don't know whether this condition is temporary or permanent, a 404 status code should be used instead.
418 I'm a teapot - HTTP
WebHTTPStatus418
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.
... 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
WebHTTPStatus428
the http 428 precondition required response status code indicates that the server requires the request to be conditional.
... status 428 precondition required specifications specification title rfc 6585, section 3: 428 precondition required additional http status codes ...
429 Too Many Requests - HTTP
WebHTTPStatus429
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").
... 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
WebHTTPStatus431
the http 431 request header fields too large response status code indicates that the server refuses to process the request because the request’s http headers are too long.
... servers will often produce this status if: the referer url is too long there are too many cookies sent in the request status 431 request header fields too large specifications specification title rfc 6585, section 5: 431 request header fields too large additional http status codes ...
451 Unavailable For Legal Reasons - HTTP
WebHTTPStatus451
the hypertext transfer protocol (http) 451 unavailable for legal reasons client error response code indicates that the user requested a resource that is not available due to legal reasons, such as a web page for which a legal action has been issued.
... <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 ...
506 Variant Also Negotiates - HTTP
WebHTTPStatus506
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).
... 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.
510 Not Extended - HTTP
WebHTTPStatus510
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.
...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.
511 Network Authentication Required - HTTP
WebHTTPStatus511
the http 511 network authentication required response status code indicates that the client needs to authenticate to gain network access.
... 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 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.
...houdini code doesn't wait for that first rendering cycle to be complete.
About JavaScript - JavaScript
in), and source code recovery (javascript programs can decompile function bodies back into their source text).
...this engine, code named spidermonkey, is implemented in c/c++.
JavaScript data types and data structures - JavaScript
bit masking also tends to make the code more difficult to read, understand, and maintain.
... beware of "stringly-typing" your code!
Iterators and generators - JavaScript
when called, generator functions do not initially execute their code.
...the behavior of this code is identical, but the implementation is much easier to write and read.
Numbers and dates - JavaScript
for example, the following code displays the number of days left in the current year: var today = new date(); var endyear = new date(1995, 11, 31, 23, 59, 59, 999); // set day and month endyear.setfullyear(today.getfullyear()); // set year to this year var msperday = 24 * 60 * 60 * 1000; // number of milliseconds per day var daysleft = (endyear.gettime() - today.gettime()) / msperday; var daysleft = math.round(daysleft); //ret...
...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.
SyntaxError: invalid regular expression flag "x" - JavaScript
there are invalid regular expression flags in the code.
...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.
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
this error happens only in strict mode code.
... in non-strict code, the operation returns false.
TypeError: can't access dead object - JavaScript
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.
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
this error only happens in strict mode code.
... in non-strict code, the operation just returns false.
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
message warning: string.charat is deprecated; use string.prototype.charat instead warning: string.charcodeat is deprecated; use string.prototype.charcodeat instead warning: string.concat is deprecated; use string.prototype.concat instead warning: string.contains is deprecated; use string.prototype.contains instead warning: string.endswith is deprecated; use string.prototype.endswith instead warning: string.includes is deprecated; use string.prototype.includes instead warning: string.indexof is deprecated; use string.prototype.in...
...) { '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: test for equality (==) mistyped as assignment (=)? - JavaScript
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.
SyntaxError: Malformed formal parameter - JavaScript
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.
SyntaxError: missing } after function body - JavaScript
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.
SyntaxError: missing } after property list - JavaScript
indenting or formatting the code a bit nicer might also help you to see through the jungle.
... examples forgotten comma oftentimes, there is a missing comma in your object initializer code: var obj = { a: 1, b: { myprop: 2 } c: 3 }; correct would be: var obj = { a: 1, b: { myprop: 2 }, c: 3 }; ...
SyntaxError: missing ; before statement - JavaScript
you need to provide a semicolon, so that javascript can parse the source code correctly.
...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.
TypeError: "x" is not a function - JavaScript
some code expects you to provide a function, but that didn't happen.
... 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.
TypeError: "x" is read-only - JavaScript
(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.
SyntaxError: "x" is a reserved identifier - JavaScript
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.
TypeError: variable "x" redeclares argument - JavaScript
this error occurs as a warning in strict mode code only.
... in non-strict code, the redeclaration is silently ignored.
Array.prototype.concat() - JavaScript
examples concatenating two arrays the following code concatenates two arrays: const letters = ['a', 'b', 'c']; 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.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.concat' in that specification.
Array.from() - JavaScript
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.
...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.
Array.prototype.lastIndexOf() - JavaScript
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.
...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.
Array.prototype.pop() - JavaScript
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.
Boolean - JavaScript
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.
EvalError() constructor - JavaScript
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.
Function() constructor - JavaScript
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.
... examples specifying arguments with the function constructor the following code creates a function object that takes two arguments.
Function.prototype.apply() - JavaScript
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.
...(the javascriptcore engine has hard-coded argument limit of 65536.
Function.caller - JavaScript
description if the function f was invoked by the top level code, the value of f.caller is null, otherwise it's the function that called f.
... examples checking the value of a function's caller property the following code checks the value a function's caller property.
Function.name - JavaScript
javascript 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.
... source code such as: function foo() {}; let foo = new foo(); if (foo.constructor.name === 'foo') { console.log("'foo' is an instance of 'foo'"); } else { console.log('oops!'); } may be compressed to: function a() {}; let b = new a(); if (b.constructor.name === 'foo') { console.log("'foo' is an instance of 'foo'"); } else { console.log('oops!'); } in the uncompressed version, the program runs into the truthy-branch and logs "'foo' is an instance of 'foo'".
InternalError() constructor - JavaScript
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.DateTimeFormat() constructor - JavaScript
unicode extension are supported (for example "en-us-u-ca-buddhist").
...the following unicode extension keys are allowed: nu numbering system.
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
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.
..."gregory" numberingsystem the values requested using the unicode extension keys "ca" and "nu" or filled in as default values.
Intl.Locale.prototype.calendar - JavaScript
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.
Intl.Locale.prototype.script - JavaScript
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.
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
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.
Intl.PluralRules() constructor - JavaScript
possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the iso 4217 currency code list (2 if the list doesn't provide that information).
...possible values are from 0 to 20; the default for plain number formatting is the larger of minimumfractiondigits and 3; the default for currency formatting is the larger of minimumfractiondigits and the number of minor unit digits provided by the iso 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumfractiondigits and 0.
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
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 requested using the unicode extension key "nu" or filled in as a default.
JSON.parse() - JavaScript
in the first stage, we replace certain // unicode characters with escape sequences.
... 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.
Object.prototype.__proto__ - JavaScript
statements, but may extend to any code that has access to any object whose [[prototype]] has been altered.
...do not do this in real code.
Object.seal() - JavaScript
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).
... 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.
Object.prototype.valueOf() - JavaScript
you can use valueof within your own code to convert a built-in object into a primitive value.
...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.
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...
...nicity, 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(mixedpromisesarray); ...
Promise.any() - JavaScript
function fetchanddecode(url) { return fetch(url).then(response => { if(!response.ok) { throw new error(`http error!
... status: ${response.status}`); } else { return response.blob(); } }) } let coffee = fetchanddecode('coffee.jpg'); let tea = fetchanddecode('tea.jpg'); promise.any([coffee, tea]).then(value => { let objecturl = url.createobjecturl(value); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log(e.message); }); specifications specification promise.any ...
Promise.prototype.finally() - JavaScript
this provides a way for code to be run whether the promise was fulfilled successfully or rejected once the promise has been dealt with.
... this helps to avoid duplicating code in both the promise's then() and catch() handlers.
Promise.prototype.then() - JavaScript
the below snippet simulates asynchronous code with the settimeout function.
...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.
handler.get() - JavaScript
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.
handler.getOwnPropertyDescriptor() - JavaScript
examples trapping of getownpropertydescriptor the following code traps object.getownpropertydescriptor().
... const p = new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(object.getownpropertydescriptor(p, 'a').value); // "called: a" // 10 the following code violates an invariant.
handler.has() - JavaScript
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.
handler.isExtensible() - JavaScript
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.
handler.ownKeys() - JavaScript
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.
handler.preventExtensions() - JavaScript
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.
handler.set() - JavaScript
if the set() method returns false, and the assignment happened in strict-mode code, a typeerror will be thrown.
... examples trap setting of a property value the following code traps setting a property value.
Proxy - JavaScript
for example, this code defines a simple target with just two properties, and an even simpler handler with no properties: const target = { message1: "hello", message2: "everyone" }; const handler1 = {}; const proxy1 = new proxy(target, handler1); because the handler is empty, this proxy behaves just like the original target: console.log(proxy1.message1); // hello console.log(proxy1.message2); // everyone to customise the pr...
...get the "doccookies" object here: https://developer.mozilla.org/docs/dom/document.cookie#a_little_framework.3a_a_complete_cookies_reader.2fwriter_with_full_unicode_support */ var doccookies = new proxy(doccookies, { get: function (otarget, skey) { return otarget[skey] || otarget.getitem(skey) || undefined; }, set: function (otarget, skey, vvalue) { if (skey in otarget) { return false; } return otarget.setitem(skey, vvalue); }, deleteproperty: function (otarget, skey) { if (skey in otarget) { return false; } return otarget.remo...
ReferenceError() constructor - JavaScript
the name of the file containing the code that caused the exception.
...the line number of the code that caused the exception.
RegExp() constructor - JavaScript
i (ignore case) if u flag is also enabled, use unicode case folding.
... u (unicode) treat pattern as a sequence of unicode code points.
String.prototype.split() - JavaScript
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.
... 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.
Symbol - JavaScript
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.
... 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.
TypeError() constructor - JavaScript
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 typeerror try { null.f() } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating a typeerror try { throw new typeerror('hello', "somefile.js", 10) } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "hello" console.log(e.name) // "typeerror" console.log(e.filename) // "somefile.js" co...
TypedArray.prototype.map() - JavaScript
examples mapping a typed array to a typed array of square roots the following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array.
... const numbers = new uint8array([1, 4, 9]); const roots = numbers.map(math.sqrt); // roots is now: uint8array [1, 2, 3], // numbers is still uint8array [1, 4, 9] mapping a typed array of numbers using a function containing an argument the following code shows how map works when a function requiring one argument is used with it.
WeakRef - JavaScript
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).
...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.
WebAssembly.CompileError - JavaScript
instance methods webassembly.compileerror.prototype.tosource() returns code that could eval to the same error.
...tch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.LinkError - JavaScript
instance methods webassembly.linkerror.prototype.tosource() returns code that could eval to the same error.
...; } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that specification.
WebAssembly.Memory() constructor - JavaScript
a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
...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.
WebAssembly.Memory - JavaScript
a memory created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
... 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.
WebAssembly.Module - JavaScript
a webassembly.module object contains stateless webassembly code that has already been compiled by the browser — this can be efficiently shared with workers, and instantiated multiple times.
... 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().
WebAssembly.RuntimeError - JavaScript
instance methods webassembly.runtimeerror.prototype.tosource() returns code that could eval to the same error.
...tch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly constructors' in that specification.
WebAssembly.Table - JavaScript
a table created by javascript or in webassembly code will be accessible and mutable from both javascript and webassembly.
... 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.
globalThis - JavaScript
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.
... 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.
undefined - JavaScript
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.
...in the following code, the variable x is not initialized, and the if statement evaluates to true.
uneval() - JavaScript
the uneval() function creates a string representation of the source code of an object.
... return value a string representing the source code of object.
Comma operator (,) - JavaScript
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.
new operator - JavaScript
when the code new foo(...) is executed, the following things happen: a new object is created, inheriting from foo.prototype.
...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.
void operator - JavaScript
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.
... button.onclick = () => void dosomething(); this ensures the return value of dosomething changing from undefined to true will not change the behavior of this code.
debugger - JavaScript
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.
export - JavaScript
note: the following is syntactically invalid despite its import equivalent: import defaultexport from 'bar.js'; // valid export defaultexport from 'bar.js'; // invalid the correct way of doing this is to rename the export: export { default as defaultexport } from 'bar.js'; examples using named exports in a module my-module.js, we could include the following code: // module "my-module.js" function cube(x) { return x * x * x; } const foo = math.pi + math.sqrt2; var graph = { options: { color:'white', thickness:'2px' }, draw: function() { console.log('from graph draw function'); } } export { cube, foo, graph }; then in the top-level module included in your html page, we could have: import { cube, foo, graph } from './my-mo...
...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
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.
...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.
return - JavaScript
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.
with - JavaScript
where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object.
... contra: code using with may not be forward compatible, especially when used with something other than a plain object.
Trailing commas - JavaScript
trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to javascript code.
...this makes version-control diffs cleaner and editing code might be less troublesome.
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.
... 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).
MathML documentation index - MathML
WebMathMLIndex
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.
... 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.
Guide to streaming audio and video - Web media technologies
in this guide, we'll examine the techniques used to stream audio and/or video media on the web, and how you can optimize your code, your media, your server, and the options you use while performing the streaming to bring out the best quality and performance possible.
... <<<...xxxxxx...>>> protocols in addition to the configuration of the server and the streaming code, there are sometimes special protocols which can be used to optimize performance.
Web media technologies
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.
Animation performance and frame rate - Web Performance
code based animations, be it css, svg, <canvas>, webgl or other javascript animations, can cause performance issues even if the bandwidth footprint is small.
... the developer tool's frame rate and waterfall charts provide insight into the work the browser is performing to animate code.
Populating the page: how browsers work - Web Performance
some browser engines take the abstract syntax tree and pass it into an interpreter, outputting bytecode which is executed on the main thread.
...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.
Web Performance
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.
... glossary terms beacon brotli compression client hints code splitting cssom domain sharding effective connection type first contentful paint first cpu idle first input delay first interactive first meaningful paint first paint http http/2 jank latency lazy load long task lossless compression lossy compression main thread minification network throttling packet page load time page prediction parse perceived performance prefetch pr...
SVG Presentation Attributes - SVG: Scalable Vector Graphics
cal image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering solid-color solid-opacity stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering transform unicode-bidi vector-effect visibility word-spacing writing-mode attributes alignment-baseline it specifies how an object is aligned along the font baseline with respect to its parent.
... value: <transform-list>; animatable: yes unicode-bidi - value:; animatable: - vector-effect specifies the vector effect to use when drawing an object.
clip-rule - SVG: Scalable Vector Graphics
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" ...
direction - SVG: Scalable Vector Graphics
it also may affect the direction in which characters are positioned if the unicode-bidi property's value is either embed or bidi-override.
... in many cases, the bidirectional unicode algorithm produces the desired result automatically, so this attribute doesn't need to be specified in those cases.
SVG Attribute reference - SVG: Scalable Vector Graphics
WebSVGAttribute
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
WebSVGElementglyph
structural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <filter>, <font>, <font-face>, <foreignobject>, <image>, <marker>, <mask>, <pattern>, <script>, <style>, <switch>, <text>, <view> attributes global attributes core attributes presentation attributes class style specific attributes d horiz-adv-x vert-origin-x vert-origin-y vert-adv-y unicode glyph-name orientation arabic-form lang dom interface this element implements the svgglyphelement interface.
...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
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-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).
Scripting - SVG: Scalable Vector Graphics
WebSVGScripting
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.
Paths - SVG: Scalable Vector Graphics
WebSVGTutorialPaths
the interactive codepen at the bottom of this page demonstrates this well.
...this interactive demo might help understand the concepts behind svg arcs: http://codepen.io/lingtalfi/pen/yalwjg (tested in chrome and firefox only, might not work in your browser) « previousnext » ...
Texts - SVG: Scalable Vector Graphics
WebSVGTutorialTexts
<text> this is <tspan font-weight="bold" fill="red">bold and red</tspan> </text> playable code <svg width="350" height="60" xmlns="http://www.w3.org/2000/svg"> <text> this is <tspan font-weight="bold" fill="red">bold and red</tspan> </text> <style><![cdata[ text{ dominant-baseline: hanging; font: 28px verdana, helvetica, arial, sans-serif; } ]]></style> </svg> the tspan element has the following custom attributes: x set a new absolute x coordinate for the containin...
... </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.
lang - XPath
WebXPathFunctionslang
syntax lang(string ) arguments string the language code or localization (language and country) code to be matched.
... if the given string does not specify a country code, this function will match nodes of that language with any country code.
Index - XPath
WebXPathIndex
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.
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.
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order.
... 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.
Web technology for developers
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.
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.
Loading Content Scripts - Archive of obsolete content
this makes your code easier to maintain, secure, debug and review.
Reddit Example - Archive of obsolete content
g", onclick: function() { reddit_panel.show(); } }); var reddit_panel = require("sdk/panel").panel({ width: 240, height: 320, contenturl: "http://www.reddit.com/.mobile?keep_extension=true", contentscriptfile: [data.url("jquery-2.1.0.min.js"), data.url("panel.js")] }); reddit_panel.port.on("click", function(url) { require("sdk/tabs").open(url); }); this code supplies two content scripts to the panel's constructor in the contentscriptfile option: the jquery library and the script that intercepts link clicks.
Getting Started - Archive of obsolete content
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
we've designed the apis to be forward-compatible with the new multiple process architecture (codenamed electrolysis) planned for firefox.
clipboard - Archive of obsolete content
the following types are supported: text (plain text) html (a string of html) image (a base-64 encoded png) if no data type is provided, then the module will detect it for you.
indexed-db - Archive of obsolete content
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.
notifications - Archive of obsolete content
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.
passwords - Archive of obsolete content
so: if a web server at http://www.example.com requested authentication with a response code like this: http/1.0 401 authorization required server: apache/1.3.27 www-authenticate: basic realm="exampleco login" the corresponding values for the credential (excluding username and password) should be: url: "http://www.example.com" realm: "exampleco login" oncomplete and onerror this api is explicitly asynchronous, so all its functions take two callback functions as additional option...
simple-prefs - Archive of obsolete content
{ "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.
simple-storage - Archive of obsolete content
constructing arrays be careful to construct array objects conditionally in your code, or you may zero them each time the construction code runs.
windows - Archive of obsolete content
in particular, depending on what you do with these objects, your code might not work with multiprocess firefox.
High-Level APIs - Archive of obsolete content
l10n localize strings appearing in the add-on's javascript code.
core/namespace - Archive of obsolete content
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.
frame/hidden-frame - Archive of obsolete content
the following code creates a hidden frame, loads a web page into it, and then logs its title: var hiddenframes = require("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ onready: function() { this.element.contentwindow.location = "http://www.mozilla.org/"; let self = this; this.element.addeventlistener("domcontentloaded", function() { console.log(self.ele...
io/file - Archive of obsolete content
note that if you do decide to hardcode windows-style paths, be sure to escape backslashes in strings.
lang/functional - Archive of obsolete content
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.
system/events - Archive of obsolete content
you can find a list of events dispatched by the firefox codebase here.
test/httpd - Archive of obsolete content
}) }); this starts a server in background (assuming you're running this code in an application that has an event loop, such as firefox).
ui/button/action - Archive of obsolete content
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.
ui/toolbar - Archive of obsolete content
for example, this code is equivalent to once(): var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ title: "my toolbar", items: [frame] }); toolbar.on("show", showing); toolbar.on("hide", hiding); function showing(e) { console.log("showing: " + e.title); toolbar.removelistener("show", showing); } fu...
util/collection - Archive of obsolete content
for example, the following code...
util/deprecate - Archive of obsolete content
experimental functions to deprecate code.
Low-Level APIs - Archive of obsolete content
util/deprecate functions to deprecate code.
cfx to jpm - Archive of obsolete content
requiring modules from test code similarly, suppose you've written some tests for your add-on: my-addon lib my-addon.js test test-my-addon-js with cfx, code inside "test-my-addon.js" can import "my-addon.js" using a statement like this: var my_addon = require("my-addon"); // this will not work with jpm!
console - Archive of obsolete content
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.
package.json - Archive of obsolete content
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.
Adding a Button to the Toolbar - Archive of obsolete content
create a directory called "data", mkdir data and save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png then open the file called "index.js" in the root of your addon directory and add the following code to it: 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/"); } now run the add-on with jpm ru...
Developing for Firefox Mobile - Archive of obsolete content
you can use the same code to target both desktop firefox and firefox mobile, and use jpm-mobile instead of the normal jpm.
Modifying the Page Hosted by a Tab - Archive of obsolete content
this makes the code easier to maintain, debug, and review.
Troubleshooting - Archive of obsolete content
check your text console when errors are generated in the sdk's apis and your code, they are logged to the text console.
Using XPCOM without chrome - Archive of obsolete content
s.jsm"); let bmlistener = class({ extends: unknown, interfaces: [ "nsinavbookmarkobserver" ], //this event most often handles all events onitemchanged: function(bid, prop, an, nv, lm, type, parentid, aguid, aparentguid) { console.log("onitemchanged", "bid: "+bid, "property: "+prop, "isanno: "+an, "new value: "+nv, "lastmod: "+lm, "type: "+type, "parentid:"+parentid, "aguid:"+aguid);0 // code to handle the event here } }); //we just have a class, but need an object.
Using third-party modules (jpm) - Archive of obsolete content
in your add-on code, you can require() modules by passing a path to the module starting from, but not including "node_modules": var menuitems = require("menuitem"); details create a new directory called, for example, "my-menuitem", navigate to it, type "jpm init" and accept all the defaults: mkdir my-menuitem cd my-menuitem jpm init install the menuitem package from npm: npm install menuitem --save this will...
Tutorials - Archive of obsolete content
localization writing localizable code.
Add-on SDK - Archive of obsolete content
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.
Alerts and Notifications - Archive of obsolete content
basic modal alert alert('hello'); pop-ups the following code presents a non-modal pop-up, which automatically disappears after an appropriate delay.
Cookies - Archive of obsolete content
setting a cookie the following code demonstrates how to set a cookie in firefox.
HTML in XUL for rich tooltips - Archive of obsolete content
dynamic html in xul tooltip insert the appropriate code from below into your xul overlay.
JS XPCOM - Archive of obsolete content
here are a few useful snippets of code for dealing with xpcom components in javascript.
LookupPrefix - Archive of obsolete content
function lookupprefix (node, namespaceuri) { var htmlmode = document.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 ...
Toolbar - Archive of obsolete content
the following code will place your button on the toolbar by default.
URI parsing - Archive of obsolete content
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"].
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;...
Extension Theming Guidelines - Archive of obsolete content
skin packages just as extension code should exist in chrome content packages, all of the styling for an extension including css and images should exist in a chrome skin package.
Inline options - Archive of obsolete content
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.
Migrating raw components to add-ons - Archive of obsolete content
it allows javascript code to load functions from dlls on windows, and should allow you to eliminate your dependence on binary components entirely.
Introduction - Archive of obsolete content
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.
Using the Stylesheet Service - Archive of obsolete content
'#' must be percent-encoded, details see bug 659650.
XML data - Archive of obsolete content
notes about this demonstration: the superscript 2 (in "million km²") a unicode character, coded as \b2 in the css file.
XUL user interfaces - Archive of obsolete content
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.
Beginner tutorials - Archive of obsolete content
creating reusable content with css and xblthis page illustrates how you can use css in mozilla to improve the structure of complex applications, making code and resources more easily reusable.underscores in class and id namessummary: the use of the underscore character in css can lead to major display problems in multiple browsers.
CSS3 - Archive of obsolete content
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.
DOMSubtreeModified - Archive of obsolete content
example the following code will display the time of last dom change on the title bar of the page.
MozAudioAvailable - Archive of obsolete content
framebuffer read only framebuffer (array) the decoded audio sample data (i.e., floats).
Getting the page URL in NPAPI plugin - Archive of obsolete content
bool b2 = npn_getproperty( m_pnpinstance, locationobj, identifier, &variantvalue ); this code is just a rough example.
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
this information applies to mozilla based browsers that pull the mozilla codebase after the mozilla 0.9.1 milestone release.
Visualizing an audio spectrum - Archive of obsolete content
note: you can use the audionode called analysernode to perform real-time fft analysis on an audio stream, rather than the code shown below.
Bookmark Keywords - Archive of obsolete content
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.
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...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
to make it work we have to add javascript code that changes its status when the tinderbox status changes.
Enabling the behavior - updating the status bar panel - Archive of obsolete content
the color red (represented by the rgb code ee0000) means a tinderbox client failed to build mozilla.
Finding the file to modify - Archive of obsolete content
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.
Getting Started - Archive of obsolete content
in the code search for all instances of "my_theme" and replace them with the name of your theme.
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
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.
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
in the code, search for all instances of "my_theme" and replace them with the name of your theme.
Installing Dehydra - Archive of obsolete content
/null for example, in the tests directory created by the installation procedure, i can run a dehydra script 'a.js' on a mozilla file like this: g++ -quiet -fplugin=../gcc_dehydra.so \ -fplugin-arg=a.js -fshort-wchar -fpreprocessed \ /home/dmandelin/builds/dehydra-gcc/browser/app/nsbrowserapp.ii -o /dev/null the -fshort-wchar is required for running against firefox, but not necessarily for other codebases.
Download Manager improvements in Firefox 3 - Archive of obsolete content
note: these changes will require some modest revisions to code using the download manager; several methods have had minor changes.
Drag and Drop - Archive of obsolete content
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.
Editor Embedding Guide - Archive of obsolete content
cmd_code toggles code on selection.
Error Console - Archive of obsolete content
it reports javascript-related errors and warnings, css errors and arbitrary messages from chrome code.
Block and Line Layout Cheat Sheet - Archive of obsolete content
(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.
Downloading Nightly or Trunk Builds - Archive of obsolete content
sometimes the firefox releases are described by a code name.
Firefox Sync - Archive of obsolete content
related info javascript client api (useful for interacting with sync from mozilla applications, including developing extensions against sync) syncing custom preferences (useful for extension developers) code snippets (demonstrates common actions with the javascript api) ...
HTTP Class Overview - Archive of obsolete content
nshttphandler implements nsiprotocolhandler manages preferences owns the authentication cache holds references to frequently used services nshttpchannel implements nsihttpchannel talks to the cache initiates http transactions processes http response 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 ...
CRMF Request object - Archive of obsolete content
avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision.
Twitter - Archive of obsolete content
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.
Settings - Archive of obsolete content
with the above manifest the following stored properties are available in the jetpack's code: * jetpack.storage.settings.twitter.username * jetpack.storage.settings.twitter.password * jetpack.storage.settings.facebook.username * jetpack.storage.settings.facebook.password * jetpack.storage.settings.music * jetpack.storage.settings.volume see also simple storage jep 24 ...
Settings - Archive of obsolete content
with the above manifest the following stored properties are available in the jetpack's code: jetpack.storage.settings.twitter.username jetpack.storage.settings.twitter.password jetpack.storage.settings.facebook.username jetpack.storage.settings.facebook.password jetpack.storage.settings.music jetpack.storage.settings.volume ...
Simple Storage - Archive of obsolete content
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.notificat...
Clipboard - Archive of obsolete content
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.
Clipboard Test - Archive of obsolete content
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.
Clipboard - Archive of obsolete content
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.
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
it's less code.
slideBar - Archive of obsolete content
creating a slidebar and adding options to implement a new slidebar within your jetpack code, use the method jetpack.slidebar.append(options) ...
Simple Storage - Archive of obsolete content
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.not...
Clipboard - Archive of obsolete content
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 - Archive of obsolete content
get started visit the getting started tutorial download the add-on sdk (formerly called the jetpack sdk) documentation check out the documentation, including tutorials, examples, guides, and api reference join the jetpack community follow jetpack on the mozilla add-ons blog report a bug check out the open bugs discuss jetpack grab the source code join us in #jetpack on irc.mozilla.org ...
Makefile.mozextension.2 - Archive of obsolete content
which is why the code shown below is corrupt - so you may wanna click on edit and view source instead !!
Metro browser chrome tests - Archive of obsolete content
it currently allows you to run javascript code in the same scope as the immersive browser and report results using the same functions as the mochitest test framework.
Microsummary topics - Archive of obsolete content
for example, the following code snippet installs the microsummary generator from the creating a microsummary tutorial: var generatortext = ' \ <?xml version="1.0" encoding="utf-8"?> \ <generator xmlns="http://www.mozilla.org/microsummaries/0.1" \ name="firefox download count" \ uri="urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16}"> \ <template> \ <transform xmlns="http://www.w3.org/1999/xsl/tr...
How to Write and Land Nanojit Patches - Archive of obsolete content
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.
Plug-n-Hack Phase1 - Archive of obsolete content
security tool commands manifest an example commands manifest (for owasp zap) is: https://code.google.com/p/zap-extensions/source/browse/branches/beta/src/org/zaproxy/zap/extension/plugnhack/resource/service.json firefox ui in firefox the tool commands will be made available via the developer toolbar (gcli) https://developer.mozilla.org/docs/tools/gcli a example of how the zap commands are currently displayed is: note that user specified parameters can be specified for commands, which can...
Plugin Architecture - Archive of obsolete content
nsobjectframe the frame responsible for displaying plugins nsplugininstanceowner glue between plugin code (modules/plugin) and layout code (layout/generic).
Extensions - Archive of obsolete content
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.
FAQ - Archive of obsolete content
ArchiveMozillaPrismFAQ
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.
Scripting - Archive of obsolete 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.
New Skin Notes - Archive of obsolete content
-- gandalf unfortunately the category styling is very much embedded into the mediawiki code.
Proxy UI - Archive of obsolete content
mouseover when online, the tooltip will include the current proxy mode: code http://mxr.mozilla.org/seamonkey/sou...ityoverlay.xul bugs bug 243624 reference network.proxy.type ...
RDF Datasource How-To - Archive of obsolete content
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.
Safely loading URIs - Archive of obsolete content
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.
Space Manager Detailed Design - Archive of obsolete content
return an error code so the caller can reallocate the collection and try again.
SpiderMonkey coding conventions - Archive of obsolete content
the spidermonkey project owners enforce coding conventions pretty strictly during code reviews.
Archived SpiderMonkey docs - Archive of obsolete content
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
left(), right() and mid() to grab a segment of a string: // get an 8-character string starting at the 4th position nsautostring leftside; str.left(leftside, 12); nsautostring middle; leftside.right(middle, 8); new way: use substring() to grab a direct reference to those characters: // get an 8-character string starting at the 4th position const nsastring& middle = substring(str, 4, 8); unicode literals what: use macro tricks to make wide-character literal strings.
Supporting private browsing mode - Archive of obsolete content
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.
Table Layout Strategy - Archive of obsolete content
the code the layout strategies are invoked from nstableframe::reflow.
Running Tamarin performance tests - Archive of obsolete content
he executable must be 'avmshell' $ adb push avmshell /data/app/avmshell $ adb shell chmod 777 /data/app/avmshell copy android_runner.sh, if it doesn't already exist on the phone in /data/app $ adb push tamarin-redux/platform/android/android_runner.sh /data/app/android_runner.s $ adb shell chmod 777 /data/app/android_runner.sh test it out with a simple .abc or no args for usage (should return exitcode=0) $ tamarin-redux/platform/android/android_shell.h hello.abc hello exitcode=0 running performance tests to run performance tests on android you don't need to pass --androidthreads or --threads=1 as with the acceptance tests; in fact, a usage error will result.
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.
Tamarin Build System Documentation - Archive of obsolete content
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.
Tamarin-central rev 703:2cee46be9ce0 - Archive of obsolete content
gertc-703 vs tc-663: 14.6% largertc-703 vs tc-700: 16.4% largertc-703 vs tc-663: 2.1% larger windows (xp pro, 2.13ghz dual core)tc-703 vs tc-700: 3.2% largertc-703 vs tc-663: 7.6% largertc-703 vs tc-700: 3.9% largertc-703 vs tc-663: 12.4% largertc-703 vs tc-700: 3.3% largertc-703 vs tc-663: 21.4% larger linux (ubuntu linux, 2.13 ghz dual core)n/an/an/a vm code size the following is a comparison of the current tamarin-central compiled size (tc-703) versus the prior build (tc-700) as well as the current build against the vm in flash player 10.
Tamarin Releases - Archive of obsolete content
this page tracks tamarin source code releases, past, present and future.
The new nsString class implementation (1999) - Archive of obsolete content
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.
[Deprecated] The Mozilla build VM - Archive of obsolete content
when you've completed the bug, they will help you get your code into the tree.
Binding Attachment and Detachment - Archive of obsolete content
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.
XBL - Archive of obsolete content
xbl bindings have been removed from the firefox codebase and the work was tracked in bug 1397874 and are we xbl still?.
Unix stub installer - Archive of obsolete content
where does the unix stub installer code reside?
Trigger Scripts and Install Scripts - Archive of obsolete content
trigger scripts and install scripts trigger scripts are simple installations that can be initiated from event handlers and other javascript code on a web page.
compareTo - Archive of obsolete content
ants are defined and available for checking the value returned by compareto: installversion.major_diff installversion.minor_diff installversion.rel_diff installversion.bld_diff installversion.equal installversion.major_diff_minus installversion.minor_diff_minus installversion.rel_diff_minus installversion.bld_diff_minus example this code uses the compareto method to determine whether or not version 3.2.1 of the royal airways software has been previously installed: existingvi = installtrigger.getversion("/royalairways/royalsw"); if ( existingvi.compareto("3.2.1") <= 0 ) { // ...
Properties - Archive of obsolete content
for more details, see the corresponding code living in the getinstallplatform method of class nsinstall.
Install Object - Archive of obsolete content
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
for a list of possible values, see return codes.
deleteKey - Archive of obsolete content
for a list of possible values, see return codes.
setValue - Archive of obsolete content
for a list of possible values, see return codes.
setValueNumber - Archive of obsolete content
for a list of possible values, see return codes.
setValueString - Archive of obsolete content
for a list of possible values, see return codes.
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 ...
emptytext - Archive of obsolete content
the old name is retained for compatibility, but you should update your code.
image.onload - Archive of obsolete content
« xul reference home image.onload type: script code this event handler will be called on the image element when the image has finished loading.
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.
onbookmarkgroup - Archive of obsolete content
« xul reference home onbookmarkgroup not in firefox type: script code this code executes when the user chooses the "bookmark this group of tabs" command.
onchange - Archive of obsolete content
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.
onclick - Archive of obsolete content
« xul reference home onclick type: script code this event handler is called when the object is clicked.
onclosetab - Archive of obsolete content
« xul reference home onclosetab type: script code this script will be called when the close tab button is clicked.
oncommandupdate - Archive of obsolete content
« xul reference home oncommandupdate type: script code this event occurs when a command update occurs.
onerror - Archive of obsolete content
« xul reference home onerror type: script code this event is sent to an image element when an error occurs loading the image.
onerrorcommand - Archive of obsolete content
« xul reference home onerrorcommand type: script code this event handler is called when an error occurs when selecting a result from the popup.
oninput - Archive of obsolete content
« xul reference home oninput type: script code this event is sent when a user enters text in a textbox.
onnewtab - Archive of obsolete content
« xul reference home onnewtab not in firefox type: script code this script will be called when the new tab button is clicked.
onpaneload - Archive of obsolete content
« xul reference home onpaneload type: script code code defined here is called when the pane has been loaded, much like the load event for a window.
onpopuphidden - Archive of obsolete content
« xul reference home onpopuphidden type: script code this event is sent to a popup after it has been hidden.
onpopuphiding - Archive of obsolete content
« xul reference home onpopuphiding type: script code this event is sent to a popup when it is about to be hidden.
onpopupshowing - Archive of obsolete content
« xul reference home onpopupshowing type: script code this event is sent to a popup just before it is opened.
onpopupshown - Archive of obsolete content
« xul reference home onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened.
onsearchbegin - Archive of obsolete content
« xul reference home onsearchbegin type: script code this event handler is called when the autocomplete search begins.
onsearchcomplete - Archive of obsolete content
« xul reference home 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 - 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.
ontextentered - Archive of obsolete content
« xul reference home ontextentered new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when a result is selected for the textbox.
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.
ontextreverted - Archive of obsolete content
« xul reference home 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.
ordinal - Archive of obsolete content
by default, elements appear in the order they appear in the xul code.
preference.type - Archive of obsolete content
int an integer string a string unichar a unicode string wstring a localized string.
prefwindow.onload - Archive of obsolete content
« xul reference home prefwindow.onload type: script code when a window finishes loading, it calls this event handler on the prefwindow element.
sizemode - Archive of obsolete content
to get the window state from javascript code, use window.windowstate.
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.
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.
textbox.onchange - Archive of obsolete content
« xul reference home onchange type: script code this event is sent when the value of the textbox is changed.
tree.onselect - Archive of obsolete content
« xul reference home onselect type: script code this event is sent to a tree when a row is selected, or whenever the selection changes.
onunload - Archive of obsolete content
« xul reference home onunload type: script code closing the window calls this event handler on the prefwindow element.
visuallyselected - Archive of obsolete content
if your code needs to apply some styling to the currently selected tab, this is the attribute you should use from firefox 40 onwards.
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...
Dynamically modifying XUL-based user interface - Archive of obsolete content
(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.
Accessing Files - Archive of obsolete content
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.
Working With Directories - Archive of obsolete content
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.
Getting File Information - Archive of obsolete content
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.
Uploading and Downloading Files - Archive of obsolete content
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.
IO - Archive of obsolete content
ArchiveMozillaXULFileGuideIO
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.
Moving, Copying and Deleting Files - Archive of obsolete content
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.
TOC - Archive of obsolete content
ArchiveMozillaXULFileGuideTOC
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.
addTab - Archive of obsolete content
ArchiveMozillaXULMethodaddTab
see code snippets: tabbed browser for examples.
advance - Archive of obsolete content
ArchiveMozillaXULMethodadvance
the code in the onwizardnext attribute is called before the page is changed.
cancel - Archive of obsolete content
ArchiveMozillaXULMethodcancel
the code in the onwizardcancel attribute is called before the wizard is cancelled.
extra1 - Archive of obsolete content
ArchiveMozillaXULMethodextra1
the code in the onextra1 attribute is called.
extra2 - Archive of obsolete content
ArchiveMozillaXULMethodextra2
the code in the onextra2 attribute is called.
goTo - Archive of obsolete content
ArchiveMozillaXULMethodgoTo
the onwizardback and onwizardnext code is not called when using this function.
rewind - Archive of obsolete content
ArchiveMozillaXULMethodrewind
the code in the onwizardback attribute is called before the page is changed.
ContextMenus - Archive of obsolete content
you will still need to associate code with the element to handle the default operation.
Special per-platform menu considerations - Archive of obsolete content
this makes it easier to write the same xul code for all platforms.
Positioning - Archive of obsolete content
this allows the script and xul code to coordinate in different ways as to how the popup should be opened.
emptyText - Archive of obsolete content
the old name is retained for compatibility, but you should update your code.
Additional Navigation - Archive of obsolete content
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'.
Attribute Substitution - Archive of obsolete content
the bug is that this code path for bindings doesn't handle the textnode element properly.
RDF Modifications - Archive of obsolete content
no extra code needs to be written to do this; it happens automatically.
Rule Compilation - Archive of obsolete content
for example, just calling the code like the following on the hidden vbox above will start off the template builder.
Simple Query Syntax - Archive of obsolete content
you can see that this code is much simpler than the full syntax.
Sorting Results - Archive of obsolete content
getservice(components.interfaces.nsixulsortservice); sortservice.sort(listbox, "?gender", "descending"); this code will sort a listbox by title in a descending order.
Toolbars - Archive of obsolete content
code snippets: toolbar code snippets that are helpful when working with toolbars.
Adding HTML Elements - Archive of obsolete content
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.
Box Objects - Archive of obsolete content
the content tree stores the nodes as they are found in the source code.
Creating a Skin - Archive of obsolete content
in the code above, we use the same image for each button, but set a different image region each one.
Features of a Window - Archive of obsolete content
just create a second xul file with the window code in it.
Focus and Selection - Archive of obsolete content
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().
Install Scripts - Archive of obsolete content
the script will contain javascript code which calls a number of install functions.
Introduction to RDF - Archive of obsolete content
alternatively, data in other formats can be used and code written that will read the file and create rdf data from it.
Manipulating Lists - Archive of obsolete content
this code isn't foolproof though; for example it doesn't check if the value entered is out of range.
Open and Save Dialogs - Archive of obsolete content
it takes no arguments but returns a status code that indicates what the user selected.
Styling a Tree - Archive of obsolete content
we'll need to add code to the getcellproperties() function, to add a property 'makeitblue' for cells in every fourth row.
Tabboxes - Archive of obsolete content
you can place the tabs on the right or bottom side by moving the tabs element to after the tabpanels element in your code.
Templates - Archive of obsolete content
nevertheless, we'll start with these other elements because trees and menus require more code.
Tree Selection - Archive of obsolete content
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.
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
the following code should be added in place of the iframe.
Using Spacers - Archive of obsolete content
our find file example the code to add a spacer is shown below.
Using the standard theme - Archive of obsolete content
note that you can also mix these two approaches, although it makes your code more readable when sticking to only one way.
Window icons - Archive of obsolete content
older versions to support older applications, such as firefox 1.0, you need to copy the icons to app_dir/chrome/icons/default manually on the first start (example code).
XUL Parser in Python/source - Archive of obsolete content
source code for the xul parser in python.
XUL accessibility tool - Archive of obsolete content
future work the following things have been suggested or are planned for a future version of the tool: new tests: (aaronlev) warning: hardcoded color and pixel sizings (aaronlev) error: duplicate accesskey in a dialog (already have this for menus) (aaronlev) error: form control without accesskey (aaronlev) warning: accesskey as lowercase letter with descender (underlined g,j,y,q,p are hard to read, not recommended) (aaronandy) list of things to check manually, such as a list oftrees in the document (make sure they have accessible co...
XML - Archive of obsolete content
in order to provide flexibility to you as adesigner of interfaces, xul offers no flexibility to you as acoder.
colorpicker - Archive of obsolete content
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.
commandset - Archive of obsolete content
oncommandupdate type: script code this event occurs when a command update occurs.
dialog - Archive of obsolete content
more information is available in the xul tutorial and dialogs and prompts (code snippets).
notificationbox - Archive of obsolete content
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.
preferences - Archive of obsolete content
also executes code specified in onchanged attribute of the element.
prefpane - Archive of obsolete content
onpaneload type: script code code defined here is called when the pane has been loaded, much like the load event for a window.
script - Archive of obsolete content
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.
tab - Archive of obsolete content
ArchiveMozillaXULtab
oncommand type: script code this event handler is called when the command is activated.
treecol - Archive of obsolete content
copy and paste the code above and link the css file to your xul file.
Building XULRunner - Archive of obsolete content
on mac, xulrunner requires mac os x 10.3 or higher and xcode 1.5 or higher to build properly.
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
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.
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
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.
Dialogs in XULRunner - Archive of obsolete content
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.
Using LDAP XPCOM with XULRunner - Archive of obsolete content
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 = ../..
What XULRunner Provides - Archive of obsolete content
s the following embedding apis are provided by xulrunner: cross-platform embedding (xre_initembedding) javaxpcom embedding gtkmozembed (linux only) activex control (windows only) (not yet complete) obsolete since gecko 7.0 nsview-based-widget (mac os x only) (not yet complete) the "maybe" list the following features have been discussed and may be included if developer time permits and code size is controlled: ldap support spellchecking support (with or without dictionaries provided) see bug 285977 core support for profile roaming (with application-specific extensibility) pyxpcom embedding (not yet complete) - but it does work, if you compile a custom build that includes the pyxpcom bindings and there is a working python available.
XUL Application Packaging - Archive of obsolete content
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.
Mozprocess - Archive of obsolete content
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()).
2006-10-26 - Archive of obsolete content
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.
2006-10-27 - Archive of obsolete content
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.
2006-11-03 - Archive of obsolete content
source code for the nsinstall contained in moztools a user asks for advice about building nsinstall on windows.
2006-11-04 - Archive of obsolete content
code for the nsinstall contained in moztools a user asks for advice about building nsinstall on windows.
2006-11-17 - Archive of obsolete content
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.
2006-10-06 - Archive of obsolete content
peter lairo requested someone who are knowledgeable in w3c standards to confirm if the use of <blockquote type="cite"> is valid w3c code.
2006-10-27 - Archive of obsolete content
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?".
2006-10-06 - Archive of obsolete content
l10n locked down - ff2 rc2 code freeze 9/29/2006 at 9am pdt the l10n repository is locked down.
2006-10-06 - Archive of obsolete content
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.
2006-10-13 - Archive of obsolete content
firefox 1.5.0.x and vista firefox 1.5.0.x was added to the vista compatibility list firefox 2 rc3 code freeze the firefox 2 rc3 code was frozen on oct.
2006-11-17 - Archive of obsolete content
announcements 1.5.0.9/2.0.0.1 code freeze - friday, november 24 code freeze for 1.5.0.9 and 2.0.0.1 on friday nov.
2006-11-10 - Archive of obsolete content
matthew gertner wants to know if anyone has written code to paste images from the clipboard on platforms other than windows?
2006-11-17 - Archive of obsolete content
peter naulls makes the suggestion in use and maintenance of xlib code that he become the nominal maintainer of the xlib code.
2006-11-17 - Archive of obsolete content
discussions js_addnamedroot a user is wondering where and when he would need to call js_addnamedroot in c code.
2006-11-10 - Archive of obsolete content
block images discussion on how where to change source code so that images could be blocked in mozilla.
2006-09-30 - Archive of obsolete content
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_PluginThreadAsyncCall - Archive of obsolete content
plug-ins should perform appropriate synchronization with the code in their npp_destroy() routine to ensure correct execution and avoid memory leaks.
NPN_ReloadPlugins - Archive of obsolete content
syntax #include <npapi.h> void npn_reloadplugins(npbool reloadpages);code parameters the function has the following parameter: reloadpages whether to reload pages.
NPN_UserAgent - Archive of obsolete content
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.
NPP_NewStream - Archive of obsolete content
if unsuccessful, the function should return one of the nperror error codes.
NPSavedData - Archive of obsolete content
see instance destruction for a code example that shows how to use npsaveddata.
NP_GetMIMEDescription - Archive of obsolete content
#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); } ...
The First Install Problem - Archive of obsolete content
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.
Getting Started - Archive of obsolete content
in other words, code like this doesn't bother you: this is some markup with <b>bold</b> tags.
SAX - Archive of obsolete content
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.
.htaccess ( hypertext access ) - Archive of obsolete content
redirects can be made on a temporary basis or permanently by supplying the status codes.
TCP/IP Security - Archive of obsolete content
the integrity of data can be assured by generating a message authentication code (mac) value, which is a keyed cryptographic checksum of the data.
Common Firefox theme issues and solutions - Archive of obsolete content
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.
Theme changes in Firefox 2 - Archive of obsolete content
bookmarks/bookmarksproperties.css this is a new file in firefox 2, and should contain the same css code as you added to addbookmark.css.
Settings - Archive of obsolete content
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.
Using SSH to connect to CVS - Archive of obsolete content
please see our source code page for directions accessing read-only cvs, and our getting write access page for directions on obtaining write access.
References - Archive of obsolete content
the webpage explains and proposes with small examples the best coding practices and most recommendable ways of developing problem-free javascript code.
Using Web Standards in your Web Pages - Archive of obsolete content
how to upgrade a webpage markup code to pass validation and how to implement css are addressed by providing recommendations, tutorials and references.
-ms-scrollbar-3dlight-color - Archive of obsolete content
code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/scrollbarcolor.htm <!doctype html> <html> <head> <title>scrollbar-3dlight-color</title> <style> .blue3dlight { -ms-scrollbar-3dlight-color: blue; scrollbar-3dlight-color: blue; /* use the standard when available.
-ms-scrollbar-darkshadow-color - Archive of obsolete content
code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/scrollbarcolor.htm <!doctype html> <html> <head> <title>scrollbar-darkshadow-color</title> <style> .blueshadow { scrollbar-darkshadow-color: blue; } </style> </head> <body> <textarea class="blueshadow">the gutter elements in the scroll bar for this element will be blue.</textarea> </body> </htm...
-moz-windows-compositor - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(images-in-menus) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(mac-graphite-theme) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(scrollbar-end-backward) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(scrollbar-end-forward) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(scrollbar-start-backward) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(scrollbar-start-forward) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(scrollbar-thumb-proportional) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(touch-enabled) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric(windows-default-theme) - Archive of obsolete content
to xul / chrome code).
:-moz-system-metric() - Archive of obsolete content
to xul / chrome code).
-moz-mac-graphite-theme - Archive of obsolete content
to xul / chrome code).
-moz-scrollbar-end-backward - Archive of obsolete content
to xul / chrome code).
-moz-scrollbar-end-forward - Archive of obsolete content
to xul / chrome code).
-moz-scrollbar-start-backward - Archive of obsolete content
to xul / chrome code).
-moz-scrollbar-start-forward - Archive of obsolete content
to xul / chrome code).
-moz-scrollbar-thumb-proportional - Archive of obsolete content
to xul / chrome code).
-moz-windows-accent-color-in-titlebar - Archive of obsolete content
to xul / chrome code).
-moz-windows-classic - Archive of obsolete content
to xul / chrome code).
-moz-windows-default-theme - Archive of obsolete content
to xul / chrome code).
-moz-windows-glass - Archive of obsolete content
to xul / chrome code).
Using JavaScript Generators in Firefox - Archive of obsolete content
generators can be used to simplify asynchronous code in firefox by opting in to using javascript version 1.7 or later.
ArrayBuffer.transfer() - Archive of obsolete content
0] = 42; var buf2 = arraybuffer.transfer(buf1, 80); buf1.bytelength; // 0 but if you use the polyfill then the value is still 40 buf2.bytelength; // 80 new int32array(buf2)[0]; // 42 var buf3 = arraybuffer.transfer(buf2, 0); buf2.bytelength; // 0 but if you use the polyfill then the value is still 80 buf3.bytelength; // 0 polyfill you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of transfer() in browsers that do not natively support it.
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
there is no added benefit to writing code in this manner, other than having it be syntactically shorter.
Date.getVarDate() - Archive of obsolete content
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.
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
example the following code provides an example of tracing an asynchronous call for a windows 8.x store app.
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
example the following code provides an example of tracing an asynchronous call for a windows 8.x store app.
Enumerator.atEnd - Archive of obsolete content
example in following code, the atend method is used to determine if the end of a list of drives has been reached: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; ...
Enumerator - Archive of obsolete content
example the following code shows the usage of the enumerator object: var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); document.write(fso.drives); var e = new enumerator(fso.drives); var drivestring = ""; e.movefirst(); while (e.atend() == false) { var drv = e.item(); drivestring += drv.path + " - "; if (drv.isready){ var freegb = drv.freespace / byte...
@cc_on - Archive of obsolete content
when you write a script for a web page, always put conditional compilation code in comments.
@if - Archive of obsolete content
when you write a script for a web page, always add conditional compilation code in comments.
@set - Archive of obsolete content
variables created using @set are generally used in conditional compilation statements, but can be used anywhere in javascript code.
New in JavaScript 1.1 - Archive of obsolete content
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.
New in JavaScript 1.2 - Archive of obsolete content
arguments new properties function.arity new methods array.prototype.concat() array.prototype.slice() string.prototype.charcodeat() string.prototype.concat() string.fromcharcode() string.prototype.match() string.prototype.replace() string.prototype.search() string.prototype.slice() string.prototype.substr() new operators delete equality operators (== and !=) new statements labeled statements switch do...while import export other new features regular expressions signed scripts changed function...
New in JavaScript 1.7 - Archive of obsolete content
in html or xul code, use: <script type="application/javascript;version=1.7"></script> when using the javascript shell, you need to set the version you wish to use using the -version 170 switch on the command line or using the version() function: version(170); the features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 because existing code might use those keywords ...
ECMAScript 5 support in Mozilla - Archive of obsolete content
improvements laid out by ecmascript 5 have been made in the parsing algorithm that prevents evaluating xhtml as javascript code in certain circumstances.
Object.prototype.eval() - Archive of obsolete content
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.__noSuchMethod__ - Archive of obsolete content
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.
Object.prototype.watch() - Archive of obsolete content
in firefox, handler is only called from assignments in script, not from native code.
arguments.caller - Archive of obsolete content
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.
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
javascript-to-java these classes allow a java object to access javascript code.
JavaPackage - Archive of obsolete content
the following code creates the javapackage red: var red = packages.redwood; see also javaarray, javaclass, javaobject, packages ...
Packages - Archive of obsolete content
summary a top-level object used to access java classes from within javascript code.
ParallelArray - Archive of obsolete content
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.
XForms Group Element - Archive of obsolete content
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
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.
Describing microformats in JavaScript - Archive of obsolete content
follows: var adr_definition = { mfversion: 0.8, mfobject: adr, classname: "adr", properties: { "type" : { plural: true, types: ["work", "home", "pref", "postal", "dom", "intl", "parcel"] }, "post-office-box" : { }, "street-address" : { plural: true }, "extended-address" : { }, "locality" : { }, "region" : { }, "postal-code" : { }, "country-name" : { } } }; the properties are quite simple here.
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
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.
Mozilla's DOCTYPE sniffing - Archive of obsolete content
the code that makes this determination is currently in determineparsemode() in nsparser.cpp.
Game promotion - Game development
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.
Bounding volume collision detection with THREE.js - Game development
// get box closest point to sphere center by clamping three.sphere.__closest.set(this.center.x, this.center.y, this.center.z); three.sphere.__closest.clamp(box.min, box.max); var distance = this.center.distancetosquared(three.sphere.__closest); return distance < (this.radius * this.radius); }; demos we have prepared some live demos to demonstrate these techniques, with source code to examine.
Mobile touch controls - Game development
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.
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
it takes data from the system folder lib/visual_scripts/ and generates your code.
Game development
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.
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
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).
API - MDN Web Docs Glossary: Definitions of Web-related terms
in web development, an api is generally a set of code features (e.g.
ASCII - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Block (scripting) - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Block - MDN Web Docs Glossary: Definitions of Web-related terms
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.
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.
Bootstrap - MDN Web Docs Glossary: Definitions of Web-related terms
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.
CMS - MDN Web Docs Glossary: Definitions of Web-related terms
a cms (content management system) is software that allows users to publish, organize, change, or remove various kinds of content, not only text but also embedded images, video, audio, and interactive code.
CORS-safelisted request header - MDN Web Docs Glossary: Definitions of Web-related terms
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.
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
cors (cross-origin resource sharing) is a system, consisting of transmitting http headers, that determines whether browsers block frontend javascript code from accessing responses for cross-origin requests.
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
cr and lf are control characters or bytecode that can be used to mark a line break in a text file.
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks.
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Cryptanalysis - MDN Web Docs Glossary: Definitions of Web-related terms
cryptanalysis is the branch of cryptography that studies how to break codes and cryptosystems.
Cryptographic hash function - MDN Web Docs Glossary: Definitions of Web-related terms
cryptographic hash functions are used for authentication, digital signatures, and message authentication codes.
DHTML - MDN Web Docs Glossary: Definitions of Web-related terms
dhtml (dynamic html) refers to the code behind interactive webpages that need no plugins like flash or java.
DOM (Document Object Model) - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Element - MDN Web Docs Glossary: Definitions of Web-related terms
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
in cryptography, encryption is the conversion of cleartext into a coded text or ciphertext.
Exception - MDN Web Docs Glossary: Definitions of Web-related terms
an exception is a condition that interrupts normal code execution.
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
naming it will be helpful when debugging your code.
Fork - MDN Web Docs Glossary: Definitions of Web-related terms
basically, if the license of the original software allows, you can copy the code to develop your own version of it, with your own additions, which will be a "fork".
Function - MDN Web Docs Glossary: Definitions of Web-related terms
a function is a code snippet that can be called by other code or by itself, or a variable that refers to the function.
GPL - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Global scope - MDN Web Docs Glossary: Definitions of Web-related terms
in client-side javascript, the global scope is generally the web page inside which all the code is being executed.
HTML - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge html on wikipedia learning html our html tutorial the web course on codecademy.com technical reference the html documentation on mdn the html specification ...
HTTP/2 - MDN Web Docs Glossary: Definitions of Web-related terms
all the core concepts found in http 1.1, such as http methods, status codes, uris, and header fields, remain in place.
High-level programming language - MDN Web Docs Glossary: Definitions of Web-related terms
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.
I18N - MDN Web Docs Glossary: Definitions of Web-related terms
(the w3c definition) among other things, i18n requires support for multiple character sets (usually via unicode) units of measure (currency, °c/°f, km/miles, etc.) time and date formats keyboard layouts text directions learn more general knowledge i18n on wikipedia technical reference i18n on w3c i18n on gala-global.org learn about it i18n material on i18nguy.com ...
IDE - MDN Web Docs Glossary: Definitions of Web-related terms
an ide normally consists of a source code editor, build automation tools and a debugger.
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
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().
ITU - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Internationalization - MDN Web Docs Glossary: Definitions of Web-related terms
internationalization includes support for multiple character sets (usually via unicode), units of measure (currency, °c/°f, km/miles, etc.), date and time formats, keyboard layouts, and layout and text directions.
Java - MDN Web Docs Glossary: Definitions of Web-related terms
programs are compiled only once ahead of time into a proprietary byte code and package format that runs inside the java virtual machine (jvm).
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge javascript on wikipedia learning javascript the javascript guide on mdn the "javascripting" workshop on nodeschool the javascript course on codecademy.com john resig's learning advanced javascript technical reference the latest ecmascript standard the javascript reference on mdn the eloquent javascript book ...
Latency - MDN Web Docs Glossary: Definitions of Web-related terms
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).
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
lets understand this with an example: var immutablestring = "hello"; // in the above code, a new object with string value is created.
Netscape Navigator - MDN Web Docs Glossary: Definitions of Web-related terms
netscape was based on mosaic and the netscape team was led by marc andreessen, a programmer who also wrote code for mosaic.
PHP - MDN Web Docs Glossary: Definitions of Web-related terms
examples basic syntax // start of php code <?php // php code goes here ?> // end of php code printing data on screen <?php echo "hello world!"; ?> php variables ​​​​​​​​​​​​​​<?php // variables $nome='danilo'; $sobrenome='santos'; $pais='brasil'; $email='danilocarsan@gmailcom'; ​​​​​​​ // printing the variables echo $nome; echo $sobrenome; echo $pais; echo $email; ?> ...
Parser - MDN Web Docs Glossary: Definitions of Web-related terms
a parser is the module of a compiler or interpreter that parses a source code file.
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
a polyfill is a piece of code (usually javascript on the web) used to provide modern functionality on older browsers that do not natively support it.
Polymorphism - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Progressive Enhancement - MDN Web Docs Glossary: Definitions of Web-related terms
progressive enhancement is a design philosophy that provides a baseline of essential content and functionality to as many users as possible, while delivering the best possible experience only to users of the most modern browsers that can run all the required code.
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Repo - MDN Web Docs Glossary: Definitions of Web-related terms
"repository") is a place that hosts an application's code source, together with various metadata.
SDP - MDN Web Docs Glossary: Definitions of Web-related terms
sdp contains the codec, source address, and timing information of audio and video.
SVN - MDN Web Docs Glossary: Definitions of Web-related terms
it allows developers to keep a history of text and code modifications.
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
for instance, the following is invalid: function examplefunction() { var x = "declared inside function"; // x can only be used in examplefunction console.log("inside function"); console.log(x); } console.log(x); // causes error however, the following code is valid due to the variable being declared outside the function, making it global: var x = "declared outside function"; examplefunction(); function examplefunction() { console.log("inside function"); console.log(x); } console.log("outside function"); console.log(x); learn more general knowledge scope (computer science) on wikipedia ...
Server - MDN Web Docs Glossary: Definitions of Web-related terms
a client program and server program traditionally connect by passing messages encoded using a protocol over an api.
Shim - MDN Web Docs Glossary: Definitions of Web-related terms
a shim is a piece of code used to correct the behavior of code that already exists, usually by adding new api that works around the problem.
Sloppy mode - MDN Web Docs Glossary: Definitions of Web-related terms
this isn't an official designation, but you are likely to come across it if you spend time doing serious javascript code.
Statement - MDN Web Docs Glossary: Definitions of Web-related terms
in a computer programming language, a statement is a line of code commanding a task.
Syntax error - MDN Web Docs Glossary: Definitions of Web-related terms
syntax errors are detected while compiling or parsing source code.
Synthetic monitoring - MDN Web Docs Glossary: Definitions of Web-related terms
with a consistent baseline, synthetic monitoring is good for measuring the effects of code changes on performance.
Type conversion - MDN Web Docs Glossary: Definitions of Web-related terms
implicit conversion happens when the compiler automatically assigns data types, but the source code can also explicitly require a conversion to take place.
Validator - MDN Web Docs Glossary: Definitions of Web-related terms
a validator is a program that checks for syntax errors in code.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
browser vendors sometimes add prefixes to experimental or nonstandard css properties and javascript apis, so developers can experiment with new ideas while—in theory—preventing their experiments from being relied upon and then breaking web developers' code during the standardization process.
XLink - MDN Web Docs Glossary: Definitions of Web-related terms
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.
Character - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge character (computing) on wikipedia character encoding on wikipedia ascii on wikipedia utf-8 on wikipedia unicode on wikipedia ...
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.
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
$(document).ready(function(){ alert("hello world!"); $("#blackbox").hide(); }); the above code carries out the same function as the following code: window.onload = function() { alert("hello world!"); document.getelementbyid("blackbox").style.display = "none"; }; or: window.addeventlistener("load", () => { alert("hello world!"); document.getelementbyid("blackbox").style.display = "none"; }); learn more general knowledge jquery on wikipedia jquery official website technica...
Strict mode - MDN Web Docs Glossary: Definitions of Web-related terms
strict mode isn't just a subset: it intentionally has different semantics from normal code.
Accessibility - Learn web development
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.
Type, class, and ID selectors - Learn web development
it results in invalid code, and will cause strange behavior in many places.
Styling tables - Learn web development
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.
CSS building blocks - Learn web development
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.
Grids - Learn web development
to be on the safe side, you could double up and add both properties to make your code more bulletproof.
Multiple-column layout - Learn web development
at the bottom of the section you can see a live example of what the final code should look like.
CSS layout - Learn web development
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.
How CSS works - Learn web development
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.
CSS first steps - Learn web development
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.
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
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.
create fancy boxes - Learn web development
it's fun because it's all about turning a design idea into working code; it's challenging because of annoying constraints and crazy freedom in the use of css.
Styling text - Learn web development
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.
How can we design for all types of users? - Learn web development
many users don't have time, or lack the proper plugin or codec.
How do you host your website on Google App Engine? - Learn web development
drag and drop the sample-app folder into the left pane of the code editor.
How do I start to design my website? - Learn web development
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.
What is a URL? - Learn web development
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.
What is a Domain Name? - Learn web development
(r37-lror) sponsoring registrar iana id: 292 whois server: referral url: domain status: clientdeleteprohibited domain status: clienttransferprohibited domain status: clientupdateprohibited registrant id:mmr-33684 registrant name:dns admin registrant organization:mozilla foundation registrant street: 650 castro st ste 300 registrant city:mountain view registrant state/province:ca registrant postal code:94041 registrant country:us registrant phone:+1.6509030800 as you can see, i can't register mozilla.org because the mozilla foundation has already registered it.
Common questions - Learn web development
every browser features a set of devtools for debugging html, css, and other web code.
Example 1 - Learn web development
this is the first example of code that explains how to build a custom form widget.
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
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).
Example - Learn web development
this is the example code for the article your first html form.
Web forms — Working with user data - Learn web development
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.
Front-end web developer - Learn web development
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.
Add a hitmap on top of an image - Learn web development
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.
Tips for authoring fast-loading HTML pages - Learn web development
if you already follow all javascript best practices, there is no need to change your code.
Multimedia and Embedding - Learn web development
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.
HTML Tables - Learn web development
LearnHTMLTables
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.
JavaScript First Steps - Learn web development
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.
Introducing JavaScript objects - Learn web development
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.
HTML performance features - Learn web development
it is our job, as developers, to ensure that we preserve these two properties when creating or editing html code.
Multimedia: Images - Learn web development
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.
Perceived performance - Learn web development
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.
Web performance - Learn web development
in this article we look at convincing managements, developing a performance culture and performance budget, and introduce ways to ensure regressions don't sneak into your code base.
Properly configuring server MIME types - Learn web development
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.
Using Vue computed properties - Learn web development
adding a summary counter add the following code to your app component object, below the methods property.
Rendering a list of Vue components - Learn web development
e label="my todo item" attribute to :label="item.label", and the :done="false" attribute to :done="item.done", as seen in context below: <ul> <li v-for="item in todoitems" :key="item.id"> <to-do-item :label="item.label" :done="item.done"></to-do-item> </li> </ul> now when you look at your running app, it'll show the todo items with their proper names, and if you inspect the source code you'll see that the inputs all have unique ids, taken from the object in the app component.
Styling Vue components with CSS - Learn web development
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.
Chrome Worker Modules
y load the module and use the values that have been exported // 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).
Web APIs: Mozilla-specific documents
this includes notes about any firefox-only features, or about any experiments or other deviations from the specification that may exist in mozilla code.
omni.ja (formerly omni.jar)
/modules javascript code modules.
Accessibility/LiveRegionDevGuide
sometimes the very best guide for some developers is the code itself.
Software accessibility: Where are we today?
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.
A bird's-eye view of the Mozilla framework
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.
Building Mozilla
in this article, we list documents that will guide you in building firefox or other projects based upon mozilla code.
Building SpiderMonkey with UBSan
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.
C++ portability guide
this document has migrated to using c++ in mozilla code.
Cookies in Mozilla
cookies preferences in mozilla documentation on what the preferences used by the cookies code actually do.
HTTP logging
sometimes, while debugging your web app (or client-side code using necko), it can be useful to log http traffic.
Articles for new developers
contributing to the mozilla code base this page should guide you through the initial steps of contributing to mozilla.
Commenting IDL for better documentation
doxygen is a system of generating documentation from source code.
Multiple Firefox profiles
nightly contains the latest code from firefox developers and is the least stable channel.
Limitations of frame scripts
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.
Firefox UI considerations for web developers
<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.
HTMLIFrameElement.getStructuredData()
examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getstructureddata(); request.onsuccess = function() { console.log(request.result); } }); running this code in a browser api app and then loading up a page that contains microdata (such as the website of british alt-country band salter cane) will result in a json object being returned, along the lines of: { "items": [ { "type":["http://microformats.org/profile/hcard"], "properties":{"fn":["chris askew"], "n":[ { "properties": { ...
mozbrowserloadend
although implementations may change in the future and it is not supported widely across browsers, it is suitable for use in code dedicated to firefox os apps.
Browser API
it currently works in (privileged) chrome code on firefox desktop (version 47 and above).
CSS -moz-bool-pref() @supports function
html <div id="pref-test"> this will have a green background if the <code>test</code> preference is enabled.
-moz-window-dragging
it only works in chrome code, and only on mac os x.
overflow-clip-box
prior to firefox 29, this behavior was hardcoded; since then it uses this property that can be used elsewhere too.
Chrome-only Events reference
this page lists events that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg.
Embedding Tips
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.
Roll your own browser: An embedding how-to
the sections marked 'mozilla examples' refer to clients and sample code to be found within the mozilla source tree.
Gecko SDK
this can be done by downloading the source code for firefox and using the --with-libxul-sdk option to configure.
Gecko
documentation chrome this page contains information specific to browser chrome (not google chrome) code running in gecko.
Geckoview-Junit Tests
to disable a single test, edit the source code and insert junit's @ignore annotation before the existing @test annotation.
How to add a build-time test
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.
How to get a stacktrace for a bug report
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.
How to get a stacktrace with WinDbg
source server maps addresses to source code lines ...
IME handling guide
in native code, you can access it with either nsiselectioncontroller or mozilla::selectiontype (the latter is recommended because of type safer).
IPDL Best Practices
when to run code here's a rundown on appropriate places to run certain kinds of code: manager::allocpprotocol - allocation manager::recvpprotocolconstructor - initialization, protocol deletion (the typeaheadfind protocol uses one-shot protocols like this) actor::recv__delete__ - cleanup, ipdl calls still valid but ill-advised actor::actordestroy - non-ipdl cleanup manager::deallocpprotocol - deallocati...
Creating a New Protocol
create the protocol file the protocol file should live in the same directory as the code which will implement it.
IPC Protocol Definition Language (IPDL)
ipdl, short for "ipc (inter-process communication) protocol definition language", is a mozilla-specific language allowing c++ code to pass messages between processes or threads in an organized and secure way.
JavaScript Tips
xul tips when inserting code with an xul overlay, wrap functions and variables inside an object with a unique name to avoid conflicting with existing or future function and variable names.
Addon
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.
AddonInstall
error integer if an error has been encountered during the download or install this will hold the error code.
Add-on Manager
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.
Add-on Repository
to import the add-on repository code module, use: components.utils.import("resource://gre/modules/addonrepository.jsm"); method overview string getrecommendedurl() string getsearchurl(in string searchterms) void cancelsearch() void retrieverecommendedaddons(in integer maxresults, in searchcallback callback) void searchaddons(in string searchterms, in integer maxresults, in searchcallb...
Download
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.
DownloadError
properties attribute type description result read only nsresult the result code associated with this error.
DownloadTarget
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.
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.
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).
Translation phase
do you prefer unicode text editors to any other applications on earth?
SVN for Localizers
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].
Localization technical reviews
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.
Creating localizable web content
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.
Extras
for example with the style rule: <code style="white-space: nowrap;">*[title] { color: blue; }</code> <math class="cue" display="block"> <mrow> <mrow> <msub title="base-a log"> <mi>log</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> ...
Fonts for Mozilla's MathML engine
fonts with appropriate unicode coverage and open font format features are required for good math rendering.
MathML In Action
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
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.
MathML Demo: <mo> - operator, fence, separator, or accent
but they have no standard unicodes.
MathML Demo: <mspace> - space
interactive sizing html content <p> use the control buttons below to adjust the parameters of the <code>mspace</code> element and see the effects.
MathML Demo: <mtable> - tables and matrices
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).
Mozilla Web Services Security Model
overview (this document is being compiled from scattered documentation and source code and most of the information in it has not been verified.
Mozilla external string guide
the mozilla codebase used to have a notion of "external" strings, which were the string classes visible to code outside of the mozilla codebase (extensions, xulrunner applications, and embedders).
Mozilla Quirks Mode Behavior
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.
Build Metrics
num_constructors number of static constructors found by the compiler in the firefox c++ codebase.
BloatView
the following sample code shows what must be done: mytype::mytype() { moz_count_ctor(mytype); ...
Investigating leaks using DMD heap scan mode
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.
GPU performance
amd gpu shaderanalyzer - will compile a shader and show the machine code and give static pipeline estimations.
javascript.options.strict
javascript warnings are generated when code is executed that doesn't cause a run-time error, but is non-standard, poorly written, or prone to cause logic errors.
ui.SpellCheckerUnderline
type:string default value:#ff0000 exists by default: no application support: gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) status: active; last updated 2012-02-21 introduction: pushed to nightly on 2009-04-03 bugs: bug 338209 values a color code like #ff0000 for red.
ui.textSelectBackground
type:string with rgb hex value as color code default value:#ef0fff (blue) [1] exists by default: no application support: before gecko 1.7 status: active; last updated 2015-09-21 introduction: pushed to trunk on 2000-04-13 bugs: bug 34704 [1]: nsxplookandfeel.cpp, line 628, retrieved 2015-09-21 ...
ui.textSelectForeground
type:string with rgb hex value as color code default value:#ffffff (white) [1] exists by default: no application support: before gecko 1.7 status: active; last updated 2015-09-21 introduction: pushed to trunk on 2000-04-13 bugs: bug 34704 [1]: nsxplookandfeel.cpp, line 635, retrieved 2015-09-21 ...
Preference reference
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.
Preferences system
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> ..
Patches and pushes
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).
Profile Manager
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.
Firefox Sync
android searchfox has links to the main sync code and the storage layer.
Installing JSHydra
prerequisites for building spidermonkey spidermonkey is part of the build process, but since jshydra will get the code if required, you do not need to worry about obtaining the right version of spidermonkey.
L20n HTML Bindings
it doesn't have any specific locale code (internally, it's called i-default in compliance to rfc 2277).
MailNews
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.
Midas editor module security preferences
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!
Nonblocking IO In NSPR
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.
Anonymous Shared Memory
the pseudo-code below shows the use of a file-mapped shared memory by a parent and child processes.
Dynamic Library Linking
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.
I/O Types
for sample code that illustrates basic i/o operations, see introduction to nspr.
Logging
ecution time: nspr_log_modules nspr_log_file logging functions and macros the functions and macros for logging are: pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_static_assert (new in nspr 4.6.6xxx this hasn't been released yet; the number is a logical guess) pr_not_reached use example the following sample code fragment demonstrates use of the logging and debugging aids.
NSPR Types
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.
PRBool
syntax #include <prtypes.h> typedef enum { pr_false = 0, pr_true = 1 } prbool; description wherever possible, do not use prbool in mozilla c++ code.
PRIOMethods
in cases where this partial implementation occurs, the function returns an error indication with an error code of pr_invalid_method_error.
PRJobIoDesc
syntax #include <prtpool.h> typedef struct prjobiodesc { prfiledesc *socket; prerrorcode error; printervaltime timeout; } prjobiodesc; ...
PRStatus
type for status code returned by some functions.
PR_Accept
if the timeout parameter is not pr_interval_no_timeout and no pending connection can be accepted before the time limit, pr_accept returns null with the error code pr_io_timeout_error.
PR_Available
the error code can then be retrieved via pr_geterror.
PR_Available64
the error code can then be retrieved via pr_geterror.
PR_CloseFileMap
the error code can be retrieved via pr_geterror.
PR_ConnectContinue
- other errors: the nonblocking connect has failed with this error code.
PR_CreatePipe
the error code can be retrieved via pr_geterror.
PR_Delete
if the function fails, the error code can then be retrieved via pr_geterror.
PR_GetCurrentThread
returns the current thread object for the currently running code.
PR_GetUniqueIdentity
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.
PR ImportTCPSocket
warning in theory, code that uses pr_importtcpsocket may break when nspr's implementation changes.
PR_Interrupt
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).
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.
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.
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.
PR_OpenSemaphore
returns a pointer to a prsem structure or null/code> on error.
PR_PopIOLayer
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.
PR_ProcessExit
syntax #include <prinit.h> void pr_processexit(printn status); parameter pr_processexit has one parameter: status the exit status code of the process.
PR_Rename
if a file with the new name already exists, pr_rename fails with the error code pr_file_exists_error.
PR_RmDir
if the directory is not empty, pr_rmdir fails and pr_geterror returns the error code pr_directory_not_empty_error.
PR_STATIC_ASSERT
prevents code from compiling when an expression has the value false at compile time.
PR_SetError
syntax #include <prerror.h> void pr_seterror(prerrorcode errorcode, print32 oserr) parameters the function has these parameters: errorcode the nspr (platform-independent) translation of the error.
PR_SetLibraryPath
this allows an environment to express policy decisions globally and lazily, rather than hardcoding and distributing the decisions throughout the code.
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.
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.
PR_Unmap
the error code can be retrieved via pr_geterror.
PR_Wait
in pseudo-code, the sequence is as follows: pr_entermonitor(&ml); while (!expression) wait; ...
PR_Writev
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.
PR_strtod
in both cases, pr_geterror() returns the error code pr_range_error.
Process Initialization
pr_callonce ensures that such initialization code is called only once.
CERT_FindCertByIssuerAndSN
ersn.derissuer.len = caname->len; issuersn.serialnumber.data = authoritykeyid->authcertserialnumber.data; issuersn.serialnumber.len = authoritykeyid->authcertserialnumber.len; issuercert = cert_findcertbyissuerandsn(cert->dbhandle, &issuersn); if ( issuercert == null ) { port_seterror (sec_error_unknown_issuer); } see also occurrences of cert_findcertbyissuerandsn in the current nss source code (generated by lxr).
Introduction to Network Security Services
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.
4.3.1 Release Notes
we provide the jss4.jar in case you do not want to obtain your own jce code signing certificate.
Build instructions for JSS 4.3.x
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.
Using JSS
MozillaProjectsNSSJSSUsing JSS
using jss newsgroup: mozilla.dev.tech.crypto if you have already built jss, or if you are planning to use a binary release of jss, here's how to get jss working with your code.
NSS 3.15.1 release notes
in sslerr.h ssl_error_unsupported_hash_algorithm, ssl_error_digest_failure, ssl_error_incorrect_signature_algorithm - new error codes for tls 1.2.
NSS 3.15.2 release notes
bug 848384 - deprecate the ssl cipher policy code, as it's no longer relevant.
NSS 3.16.1 release notes
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.
NSS 3.16.2.3 release notes
in sslerr.h ssl_error_inappropriate_fallback_alert - a new ssl error code.
NSS 3.17.1 release notes
in sslerr.h ssl_error_inappropriate_fallback_alert - a new ssl error code.
NSS 3.19.2.3 release notes
an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.19.2.4 release notes
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.
NSS 3.19 release notes
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.
NSS 3.21.1 release notes
an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.21.2 release notes
security fixes in nss 3.21.2 bug 1293334 / cve-2016-9074 - fixed a timing side channel in the tls cbc code.
NSS 3.22.2 release notes
an attacker could create a specially-crafted certificate which, when parsed by nss, would cause a crash or execution of arbitrary code with the permissions of the user.
NSS 3.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
s12_aes_cbc_256 - cipher family identifiers corresponding to the pkcs#5 v2.1 aes based encryption schemes used in the pkcs#12 support in nss in pkcs11n.h cka_nss_mozilla_ca_policy - identifier for a boolean pkcs#11 attribute, that should be set to true, if a ca is present because of it's acceptance according to the mozilla ca policy notable changes in nss 3.30 the tls server code has been enhanced to support session tickets when no rsa certificate (e.g.
NSS 3.32 release notes
the code signing trust bit was turned off for all, included root certificates.
NSS 3.36 release notes
notable changes in nss 3.36 replaced existing vectorized chacha20 code with verified hacl* implementation.
NSS 3.37 release notes
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 3.38 release notes
various security fixes in the asn.1 code.
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
in clienthello bug 1581507 - fix unportable grep expression in test scripts bug 1234830 - [cid 1242894][cid 1242852] unused values bug 1580126 - fix build failure on aarch64_be while building freebl/gcm bug 1385039 - build nspr tests as part of nss continuous integration bug 1581391 - fix build on openbsd/arm64 after bug #1559012 bug 1581041 - mach-commands -> mach-completion bug 1558313 - code bugs found by clang scanners.
NSS 3.49.2 release notes
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.
NSS 3.50 release notes
nss 3.49.1 sped up pbkdf2 operations, though pbkdf1 operations are also relevant for older nss databases (also included in nss 3.49.2) bug 1608895 - gyp builds on taskcluster broken by setuptools v45.0.0 (for lacking python3) bug 1574643 - upgrade hacl* verified implementations of chacha20, poly1305, and 64-bit curve25519 bug 1608327 - two problems with neon-specific code in freebl bug 1575843 - detect aarch64 cpu features on freebsd bug 1607099 - remove the buildbot configuration bug 1585429 - add more hkdf test vectors bug 1573911 - add more rsa test vectors bug 1605314 - compare all 8 bytes of an mp_digit when clamping in windows assembly/mp_comba bug 1604596 - update wycheproof vectors and add support for cbc, p256-ecdh, and cmac tests bug 1608493 - use...
NSS 3.53 release notes
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.
nss tech note6
the following applies to nss 3.11 : the low-level freebl cryptographic code has been separated from softoken on all platforms.
NSS Tech Notes
tn1: how to use the nss asn.1 and quickder decoders.
FC_InitPIN
return value fc_initpin() returns the following return codes.
FC_InitToken
return value fc_inittoken() returns the following return codes.
FC_Initialize
return value fc_initialize returns the following return codes.
FC_Login
return value fc_login() returns the following return codes.
NSC_InitToken
return value nsc_inittoken() returns the following return codes.
NSC_Login
return value nsc_login() returns the following return codes.
NSS tools : modutil
the nss site relates directly to nss code changes and releases.
NSS tools : vfyserv
the nss site relates directly to nss code changes and releases.
sslintro.html
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.
NSS Tools pk12util-tasks
nss security tools: pk12util tasks newsgroup: mozilla.dev.tech.crypto task list need to migrate code to use an up-to-date version of nss.
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
MozillaProjectsNSStoolsmodutil
the nss site relates directly to nss code changes and releases.
Necko FAQ
see the code section on the main page.
Multithreading in Necko
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.
Necko
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...
Rhino documentation
performance hints some tips on writing faster javascript code.
Download Rhino
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.
Rhino downloads archive
r3 2011-05-09 new in rhino 1.7r3 rhino1_7r3.zip rhino 1.7r2 2009-03-22 new in rhino 1.7r2 rhino1_7r2.zip rhino 1.7r1 2008-03-06 new in rhino 1.7r1 rhino1_7r1.zip rhino 1.6r7 2007-08-20 new in rhino 1.6r7 rhino1_6r7.zip rhino 1.6r6 2007-07-30 new in rhino 1.6r6 rhino1_6r6.zip rhino 1.6r5 2006-11-19 same code as 1.6r4, but relicensed under mpl/gpl.
Rhino FAQ
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.
Functions
(but note that objects of other classes can be callable and can even have typeof obj == "function".) script functions functions written in javascript and compiled to bytecode.
Garbage collection
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.
JIT Optimization Outcomes
cantinlinegeneric cantinlineclassconstructor cantinlineexceededdepth cantinlineexceededtotalbytecodelength cantinlinebigcaller cantinlinebigcallee cantinlinebigcalleeinlinedbytecodelength cantinlinenothot cantinlinenotindispatch cantinlinenativebadtype cantinlinenotarget unable to inline function call.
INT_FITS_IN_JSVAL
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.
JS::CallArgs
new code should use callargs instead of js_callee etc.
JS::CloneFunctionObject
the new object has the same code and argument list as funobj.
JS::Compile
see also the jsapi user guide contains example code using compiled scripts.
JS::CompileOffThread
see also the jsapi user guide contains example code using compiled scripts.
JS::SourceBufferHolder
any code calling sourcebufferholder::take() must guarantee to keep the memory alive until js compilation completes.
JSCheckAccessOp
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.
JSFastNative
the term "native" here refers to c/c++ code as opposed to javascript code.
JSFinalizeOp
jsclass hooks jsclass offers the following hook: the jsclass.finalize callback is a hook for destructor code.
JSFreeOp
these structures wrap parameters that are passed to the finalizers removing most of explicit dependencies on jscontext in the finalization code.
JSFunctionSpec
selfhostedname const char * the function's name in self-hosted javascript code.
JSID_EMPTY
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.
JSMarkOp
all new code using spidermonkey 1.8 or later should use a jstraceop instead to ensure that the tracing apis work properly.
JSNewResolveOp
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.
JSObjectOps.newObjectMap
jsobjectmaps are reference-counted by generic code in the engine.
JSPRINCIPALS_HOLD
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.
JSPropertyDescriptor
in other words, the above code is equivalent to the following code.
JSScript
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.
JSTraceOp
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.
JSVAL_IS_DOUBLE
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.
JSVAL_IS_INT
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.
JSVAL_IS_NULL
(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.
JSVAL_IS_NUMBER
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.
JSVAL_IS_STRING
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.
JSVAL_IS_VOID
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is void.
JS_AddArgumentFormatter
the actual format trailing substring used in each convert or pusharguments call is passed to the formatter, so that one such function may implement several formats, in order to share code.
JS_AddExternalStringFinalizer
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).
JS_CheckAccess
description js_checkaccess determines whether the property of obj given by id can be accessed by the code currently running in the context cx.
JS_CheckForInterrupt
syntax bool js_checkforinterrupt(jscontext* cx); name type description cx </code>jscontext *<code> the context.
JS_ClearContextThread
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_ClearNewbornRoots
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.
JS_CloneFunctionObject
the new object has the same code and argument list as funobj, but uses parent as its enclosing scope.
JS_CompileScriptForPrincipals
js_compileucscriptforprincipals is the unicode version of the function.
JS_ContextIterator
example the following code snippet illustrates how to cycle through the contexts for a given runtime: jscontext *acx; jscontext *iterp = null; int i = 0; while ((acx = js_contextiterator(rt, &iterp)) != null) { printf("%d ", ++i); } see also mxr id search for js_contextiterator ...
JS_DefineFunction
js_defineucfunction is the unicode version of the function.
JS_DefineOwnProperty
a getter or setter defined with this functions will be observable from js code.
JS_DefinePropertyWithTinyId
js_defineucpropertywithtinyid is the unicode version of the function.
JS_DeleteProperty2
js_deleteucproperty2 is the unicode version of the function.
JS_DumpHeap
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.
JS_DumpNamedRoots
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.
JS_EvaluateScript
js_evaluateucscript is the unicode version of the function.
JS_EvaluateScriptForPrincipals
js_evaluateucscriptforprincipals is the unicode version of the function.
JS_ExecuteScript
the jsapi user guide contains example code using compiled scripts.
JS_FreezeObject
this means that other code cannot delete, add or change any properties on the object.
JS_GC
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.
JS_GetFunctionObject
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.
JS_GetGCParameter
see also mxr id search for js_getgcparameter mxr id search for js_setgcparameter bug 474801 jsgc_bytes jsgc_number bug 474497 jsgc_max_code_cache_bytes this option no-longer exists js_getgcparameterforthread js_setgcparameterforthread bug 624229 jsgc_mode bug 631733 jsgc_unused_chunks bug 674480 jsgc_total_chunks bug 641025 jsgc_slice_time_budget bug 673551 jsgc_mark_stack_limit bug 765435 jsgc_high_frequency_time_limit jsgc_high_frequency_low_limit ...
JS_GetGlobalObject
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!
JS_GetImplementationVersion
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.
JS_GetProperty
js_getucproperty is the unicode version of the function.
JS_GetPropertyAttributes
js_getucpropertyattributes is the unicode version of the function.
JS_GetStringChars
it may contain surrogate code units that aren't properly paired.
JS_HasProperty
js_hasucproperty is the corresponding unicode api.
JS_InitStandardClasses
these include all the standard ecmascript global properties defined in ecma 262-3 §15.1: array, boolean, date, decodeuri, decodeuricomponent, encodeuri, encodeuricomponent, error, eval, evalerror, function, infinity, isnan, isfinite, math, nan, number, object, parseint, parsefloat, rangeerror, referenceerror, regexp, string, syntaxerror, typeerror, undefined, and urierror as well as a few spidermonkey-specific globals, depending on compile-time options: escape, unescape, uneval, internalerror, script, xml, ...
JS_IsAssigning
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.
JS_LeaveLocalRootScopeWithResult
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.
JS_NewContext
for sample code that creates and initializes a jscontext, see jsapi user guide.
JS_NewObjectForConstructor
this function does not run the code of the constructor function--it just creates the object.
JS_NewUCString
js_newucstring is the unicode version of the function.
JS_NewStringCopyN
js_newucstringcopyn is the unicode version of the function.
JS_PushArguments
acter argument type b jsbool c uint16 (16-bit, unsigned integer) i int32 (32-bit, ecma-compliant signed integer) u uint32 (32-bit, ecma-compliant, unsigned integer) j int32 (32-bit, signed integer) d jsdouble i jsdouble (converted to an integer value) s char * (c string) s jsstring * (unicode string) w jschar * (unicode null-terminated string) o jsobject * f jsfunction * * none.
JS_RemoveExternalStringFinalizer
description remove finalizer from the global gc finalizers table, returning its type code if found, -1 if not found.
JS_SetBranchCallback
this is the context that is currently executing the code that triggered the callback.
JS_SetErrorReporter
example code with error handling omitted: class myrequest { public: void execute() { auto rt = js_newruntime(memlimit); js_setruntimeprivate(rt, this); js_seterrorreporter(rt, &myrequest::dispatcherror); // execute js } void onerror(const std::string& error) { // handle error } static void dispatcherror( jscontext* ctx...
JS_SetGCZeal
the drawback is that gc zeal can cause javascript code to run extremely slowly.
JS_SetGlobalObject
see the sample code at jsapi user guide.
JS_SetInterruptCallback
this article covers features introduced in spidermonkey 31 set a callback function that is automatically called periodically while javascript code runs.
JS_SetOperationCallback
this article covers features introduced in spidermonkey 1.8.5 set a callback function that is automatically called periodically while javascript code runs.
JS_SetProperty
js_setucproperty is the unicode version of the function.
JS_SetPropertyAttributes
js_setucpropertyattributes is the unicode version of the function.
JS_ValueToFunction
a jsfunction represents only the compiled code and not the environment of the function.
jschar
embedder code should use char16_t, too.
jsdouble
you should be able to just replace every usage of jsdouble with double in your code.
SpiderMonkey 52
you can download full source code from treeherder, by going to the mozilla-esr52 repository and clicking on the first sm(pkg) link you see.
Running Parsemark
the test files are not checked into the source tree because they're non-mozilla js code.
TPS Tests
steps get the source code clone mozilla-central (choose your flavor): hg clone hg.mozilla.org/mozilla-central or git clone github.com/mozilla/gecko-dev cd into the tps folder cd testing/tps create the environment i suggest the path to be outside of the mc source tree python create_venv.py --username=%email% --password=%password% %path% note: if you are updating the...
Zest runtimes
python no code available yet if you are interested in working on an existing or new zest runtime then please get in touch via the zest group.
Zest
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
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.
Mozinfo
throughout mozmill and other mozilla python code, checking the underlying platform is done in many different ways.
Redis Tips
for example, here's some node code: var redis = require("redis"), client = redis.createclient({ ...
Setting up an update server
open them and find this line: #defines['disable_updater_authenticode_check'] = true.
The Places database
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.
Frecency algorithm
the latter two later ported all of the code from c++ to javascript.
History Service Design
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.
Querying Places
your code should handle this case.
Retrieving part of the bookmarks tree
complete code listing var historyservice = components.classes["@mozilla.org/browser/nav-history-service;1"] .getservice(components.interfaces.nsinavhistoryservice); var options = historyservice.getnewqueryoptions(); var query = historyservice.getnewquery(); var bookmarksservice = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] ...
Using the Places annotation service
it is usable from trusted firefox code such as extensions, but not from web pages.
Places
documentation places migration guide migrating existing code to use the places api.
Preferences API
see also code snippets:preferences (more detailed discussion with multiple examples) ...
FUEL
ventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage fueliapplication objects fueliannotations fueliapplication fuelibookmark fuelibookmarkfolder fuelibookmarkroots fuelibrowsertab fueliwindow xpcom although the fuel application object is preloaded into xul scripts, it is not preloaded into javascript xpcom code.
SMILE
ects extiapplication objects exticonsole extieventitem extieventlistener extievents extiextension extiextensions extipreference extipreferencebranch extisessionstorage smileiapplication objects smileibookmarkroots smileiwindow smileibrowsertab smileiapplication xpcom although the extiapplication object is preloaded into xul scripts, it is not preloaded into javascript xpcom code.
STEEL
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.
extIApplication
xpcom although the application object is preloaded into xul scripts, it is not preloaded into javascript xpcom code.
extIPreferenceBranch
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.
Bundling multiple binary components
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.
Fun With XBL and XPConnect
<handlers> <handler type="keypress" keycode="vk_return" value="autocomplete(anonymouscontent[0].value, this.autocompletelistener);"/> </handlers> </implementation> </binding> original document information author(s): scott macgregor last updated date: april 13, 2000 copyright information: copyright (c) scott macgregor ...
Generic factory
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?
Inheriting from implementation classes
so, in code: idl: interface ia { void funca(); } interface ib : ia { void funcb(); } interface ic : ib { void funcc(); } c++ implementation: class a : public ia { ???
Receiving startup notifications
this is no longer the case, so be sure to remove that when migrating existing code.
Interfacing with the XPCOM cycle collector
ection_traverse_end finally, you need to manually add the js object to the trace method: ns_impl_cycle_collection_trace_begin(nsfoo) //if your class is a wrapper cache: //ns_impl_cycle_collection_trace_preserved_wrapper ns_impl_cycle_collection_trace_js_member_callback(msomeobj) ns_impl_cycle_collection_trace_end note that if your class is a wrapper cache then you likely have generate code that uses ns_impl_cycle_collection_wrappercache_# macro instead of ns_impl_cycle_collection_#.
Components.ID
components.classes, components.classesbyid, components.interfaces provide pretty much all the nsids that most javascript code would ever need to deal with.
Components.results
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.
Components.utils.cloneInto
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.
Components.utils.forceGC
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
var arr = []; arr.push(cu.getweakreference(window)); //now lets say this code runs in another block: for (var i=0; i<arr.length; i++) { if (arr[i].get() == window) { //found the window break; } } ...
Development
source the latest source code is available on the mozilla trunk, in the extensions/java/xpcom directory.
PlXPCOM
plxpcom (perl xpcom) provides language bindings letting you use xpcom from perl code.
PyXPCOM
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.
Architecture basics
you can imagine it like a bridge between javascript code, and mozilla guts.
nsIProfile
this interface is obsolete; you should use nsitoolkitprofileservice instead; however, reference documentation for nsiprofile is available if you're working with old code.
HOWTO
"component returned failure code: 0x80040111 (ns_error_not_available) [nsixpccomponents_utils.import]" nsresult: "0x80040111 (ns_error_not_available)" location: "js frame :: file.js :: <top_level> :: line 12" data: no] solution 1 var loader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); loader.loadsubscript("chrome://myall/content/file.jsm"); see: ...
xpcshell
it is a console application that lets you run javascript code.
XPConnect
with xpconnect, you can use xpcom components from javascript code, and interact with javascript objects from within xpcom components.
nsDirectoryService
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.
nsLocalFile
example code function getfilesize(path) { var file = components.classes["@mozilla.org/file/local;1"].
nsScriptableInputStream
example code const nsiscriptableinputstream = components.interfaces.nsiscriptableinputstream; function consumestream(inputstream) { var factory = components.classes["@mozilla.org/scriptableinputstream;1"]; var sis = factory.createinstance(nsiscriptableinputstream); sis.init(inputstream); try { while (true) { var chunk = sis.read(512); if (chunk.length == 0) break; // ok, chunk now contains a portion of the stream's d...
NS_GetComponentManager
otherwise, it returns an error code.
NS_GetComponentRegistrar
otherwise, it returns an error code.
NS_GetServiceManager
otherwise, it returns an error code.
NS_ShutdownXPCOM
otherwise, it returns an error code.
NS_ConvertASCIItoUTF16
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
NS_ConvertUTF16toUTF8
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
NS_ConvertUTF8toUTF16
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
NS_LossyConvertUTF16toASCII
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
NS_OVERRIDE
ns_override is a macro which allows c++ code in mozilla to specify that a method is intended to override a base class method.
BeginReading
example code // count the number of times a particular character appears in the string pruint32 countchar(const nsacstring& str, char c) { const char* start = str.beginreading(); const char* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length, endreading ...
EndReading
example code see beginreading for an example.
BeginReading
example code // count the number of times a particular character appears in the string pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* start = str.beginreading(); const prunichar* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length ...
EndReading
example code see beginreading for an example.
nsAString
this class is typically used to represent unicode character arrays.
nsAdoptingCString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
nsAdoptingString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
nsAutoString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
nsCAutoString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount le...
nsCOMPtr
« xpcom api reference summary this utility class simplifies managing xpcom interface references from c++ code.
nsCString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
nsDependentCString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
nsDependentCSubstring
it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive.
nsDependentString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
nsDependentSubstring
it is the client code's responsibility to ensure that the external buffer remains valid for a long as the string is alive.
get
const char_type* get() const; example code nsembedcstring str("hello world"); printf("%s\n", str.get()); ...
get
const char_type* get() const; example code void getbar(nsastring &result); void func() { nsembedstring str; getbar(str); const prunichar *data = str.get(); ...
nsFixedCString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
nsFixedString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
HeapMinimize
otherwise, it returns an error code.
nsPromiseFlatCString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
nsPromiseFlatString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
nsString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
nsSupportsWeakReference
example code // supporting weak references to a hypothetical implementation // of the nsifoo interface...
nsXPIDLCString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nscstring&, pruint32, pruint32) const - source parameters nscstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nscstring&, pr...
nsXPIDLString
@param aerrorcode will contain error if one occurs @return float rep of string value parameters print32* aerrorcode tointeger print32 tointeger(print32*, pruint32) const - source parameters print32* aerrorcode pruint32 aradix mid pruint32 mid(nsstring&, pruint32, pruint32) const - source parameters nsstring& aresult pruint32 astartpos pruint32 acount left pruint32 left(nsstring&, pruin...
mozIPersonalDictionary
check() checks a unicode string.
mozISpellCheckingEngine
each dictionary name is typically but not always a locale code.
nsIAboutModule
the section "firefox 4 (second approach)" provides copy paste code for working example.
nsIAccessibleEditableText
native code only!
nsIAccessibleEvent
example to listen to in-process accessibility invents, make your object an nsiobserver, and listen for accessible-event by using code something like this: nscomptr<nsiobserverservice> observerservice = do_getservice("@mozilla.org/observer-service;1", &rv); if (ns_succeeded(rv)) { rv = observerservice->addobserver(this, "accessible-event", pr_true); } ...
nsIAccessibleWin32Object
native code only!
nsIAlertsService
example simple usage the following code was used to display the above notification.
nsIAnnotationService
supported for use from trusted code, such as extensions, but not from web content.
nsIApplicationCache
used on content process to simplify the application cache code.
nsIAutoCompleteListener
new code should use toolkit autocomplete interfaces.
nsIBidiKeyboard
some other part of the code is going to be on gtk+ later, and we will use gtk+ api instead.
nsIBinaryOutputStream
writeutf8z() writes an 8-bit pascal style string (utf8-encoded) to the stream.
nsIBrowserHistory
it is called by history importing code and is used in the history migration tool.
nsIChannel
used by the security manager to grant or deny privileges to mobile code loaded from this channel.
nsIClassInfo
note: this flag is private and is for use by the mozilla codebase only.
nsICommandLineRunner
on windows the character set is utf-8, not the native codepage.
nsIContentPrefObserver
dom/interfaces/base/nsicontentprefservice.idlscriptable this interface allows code to easily watch for changes to the values of content preferences.
nsIContentSecurityPolicy
, in nsisupports acontext, in acstring amimetypeguess, in nsisupports aextra); short shouldprocess(in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetype, in nsisupports aextra); attributes attribute type description allowseval boolean whether this policy allows eval and eval-like functions such as settimeout("code string", time).
nsIContentSniffer
let charset = "iso-8859-1"; try { // 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 } ...
nsIConverterInputStream
this allows reading unicode strings from a stream, automatically converting the bytes from a selected character encoding.
nsICookieManager2
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.
nsIDNSRequest
the listener will passed to asyncresolve will be notified immediately with a status code of ns_error_abort.
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
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.
nsIDOMGeoPositionError
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.
nsIDOMGlobalPropertyInitializer
ensure that you never return any internal xpcom objects to untrusted code.
nsIDOMOrientationEvent
the nsidomorientationevent interface describes the event that can be delivered to dom windows, providing information from the device's accelerometer, allowing code to determine the orientation of the device.
nsIDOMSerializer
return value the serialized subtree in the form of a unicode string.
nsIDirIndex
this is encoded with the encoding specified in the nsidirindexparser, and is also escaped.
nsIDirectoryService
must not be called by external code; called internally by xpcom initialization.
nsIDirectoryServiceProvider
example this code creates a global, read-only string called currdir with the value of the current working directory.
nsIEffectiveTLDService
remarks all returned strings are encoded in ascii/ace and normalized according to rfc 3454.
nsIEventListenerInfo
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.
nsIException
name string the name of the error code (a string representation of result) read only.
nsIExternalProtocolService
return value this code makes little sense and needs to be cleaned up.
nsIFeedProgressListener
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.
nsIFeedTextConstruct
plaintext() returns the text as plain text with all markup stripped and all entities decoded.
nsIFileProtocolHandler
see also code_snippets:file_i/o ...
nsIINIParserFactory
example obtaining a parser object to obtain a parser for an ini file, you can use code that looks like this: to get an nsiiniparser instance for an ini file, you may use the following code: // create an nsilocalfile var cl = "@mozilla.org/file/local;1"; var interf = components.interfaces.nsilocalfile; var file = components.classes[cl].createinstance(interf); // init the file with the path to your ini file var path = "c:\\temp\\example.ini"; file.initwithpath(path); // create the ...
nsIINIParserWriter
constant value description write_utf16 0x1 windows and the nsis installer code sometimes expect ini files to be in utf-16 encoding.
nsIJSID
native code only!
nsILocaleService
nsilocale newlocale( in astring alocale ); parameters alocale a locale code as described in nsilocale.
nsILoginManagerCrypto
note: the current implemention of this inferface simply uses nss/psm's "secret decoder ring" service.
nsIMIMEInputStream
example var postdata = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); ...
nsIMacDockSupport
the result of this code is shown below.
nsIMarkupDocumentViewer
logical text will be reordered for presentation using the unicode bidi algorithm.
nsIMemoryReporter
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().
nsIMenuBoxObject
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.
nsIMessenger
saveattachmenttofolder() is used by the drag and drop code to drop an attachment to a destination folder.
nsIModule
it is very important to ensure that no outstanding references to the module's code/data exist before returning true.
Building an Account Manager Extension
therefore we add the following code to the previous.
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
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.
nsIMsgMessageService
e.g., header=filter return the nsiuri that gets run example for example, the next piece of code shows the selected message code on a dialog: (taken from mozillazine) var content = ""; var messageuri = getfirstselectedmessage(); var msgservice = messenger.messageservicefromuri(messageuri); var msgstream = components.classes["@mozilla.org/network/sync-stream-listener;1"].createinstance(); var consumer = msgstream.queryinterface(components.interfaces.nsiinputstream); var scriptin...
nsIMsgSearchNotify
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(); }; ...
nsINavHistoryService
see this code for how a function to add visits and handle errors using the new api could look like.
nsIParentalControlsService
toolkit/components/parentalcontrols/public/nsiparentalcontrolsservice.idlscriptable this interface provides access to the operating system's parental controls feature, allowing code to detect whether such a service is enabled and to request overrides to bypass the feature.
nsIParserUtils
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.
nsIPlacesView
controllers should not be concerned with these details; controller code should not be required to decode the meaning of a selection depending on what kind of view produced the selection.
nsIPrintingPrompt
if an embedder implemented service returns any error code (other than ns_error_abort) printing will terminate.
nsIPropertyBag
goodies obtained from window.navigator are: appcodename:"mozilla" appname:"netscape" appversion:"5.0 (windows)" battery:batterymanager buildid:"20140529161749" cookieenabled:true donottrack:"yes" geolocation:geolocation language:"en-us" mimetypes:mimetypearray mozalarms:null mozapps:xpcwrappednative_nohelper mozcameras:cameramanager mozconnection:mozconnection mozcontacts:contactmanager mozid:null mozkeyboard:xpcwrappednative_nohelper mozpay:null ...
nsIProtocolProxyCallback
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.
nsIProtocolProxyService
areason the error code corresponding to the proxy failure.
nsIResumableChannel
in both of these cases, no ondataavailable will be called, and onstoprequest will immediately follow with the same status code.
nsISSLErrorListener
error the code associated with the error.
nsIScriptError2
category a string indicating what kind of code caused the message.
nsIScriptableUnescapeHTML
this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0).
nsISimpleEnumerator
see also code example of nsisimpleenumerator ...
nsISupportsString
xpcom/ds/nsisupportsprimitives.idlscriptable this interface provides scriptable access for unicode character strings.
nsISupportsVoid
native code only!
nsITaskbarPreviewController
the controller and its supporting code, however, may change this values at any time.
nsIThread
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.
nsIToolkitProfileService
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.
nsIURI
see also code snippets:uri parsing ...
nsIURIFixup
fixup_flag_use_utf8 4 use utf-8 to encode the uri instead of the platform character set.
nsIUpdate
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.
nsIUpdateItem
internal code uses other constants in nsextensionmanager.js.in.
nsIUploadChannel
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.
nsIWebBrowser
active means that it's visible enough that we want to avoid certain optimizations like discarding decoded image data and throttling the refresh driver.
nsIWebNavigationInfo
example let webnavigationinfo_service = components.classes["@mozilla.org/webnavigation-info;1"] .getservice(components.interfaces.nsiwebnavigationinfo); let support_code = webnavigationinfo_service.istypesupported(contenttype, null); if (support_code == webnavigationinfo_service.unsupported) { dump("unsupported content-type: not displaying in the browser\n"); } see also nsiwebnavigation ...
nsIWebappsSupport
icondata a base64 encoded representation of the application's icon.
nsIXPCScriptable
if an implementation of this method throws an error code, the prototype chain will not be checked for the property.
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 ...
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
otherwise, it returns an error code.
NS_CStringContainerInit2
otherwise, it returns an error code.
NS_CStringCopy
otherwise, it returns an error code.
NS_CStringGetData
example code // count the number of times a particular character appears in a string.
NS_CStringSetData
otherwise, it returns an error code.
NS_CStringSetDataRange
otherwise, it returns an error code.
NS_StringContainerFinish
example code see ns_stringcontainerinit for an example.
NS_StringGetData
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.
Using IndexedDB in chrome
roperties": ["indexeddb"] } var principal = cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsiprincipal); var sandbox = components.utils.sandbox(principal, options); // the sandbox will have access to indexeddb var sandboxscript = 'var req = indexeddb.open("my-database");'; components.utils.evalinsandbox(sandboxscript, sandbox); before firefox 33, you would access indexeddb from chrome code using the initwindowless method of the nsiindexeddatabasemanager service.
Using nsIClassInfo
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.
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
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.
XPCOM ABI
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.
XPCOM ownership guidelines
special code must be provided and called to break the cycle before the participants can be individually released.
pyxpidl
the newer utility has the advantage of not needing any code to be compiled in order to use it, and let us remove a bunch of old code from the tree.
Clang static analysis
moved to https://firefox-source-docs.mozilla.org/code-quality/static-analysis.html ...
Cached compose window FAQ
the downsides are that we have had some bugs, it complicates and bloats the code, and it requires more testing.
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
the server itself is found in mailnews/test/fakeserver/maild.js and was largely based off of the httpd fakeserver from network code.
Mail client architecture overview
datasources - datasources are the glue code that reflect mail data such as folders and messages into rdf.
Spam filtering
the purge code is implemented as a search of the "junk" folder, looking for "old" message that have the proper junk status.
Thunderbird Configuration Files
if you don't already have one, consider running the following code in a terminal.
Building a Thunderbird extension 2: extension file layout
these files contain the code that makes your extension actually do something.
Creating a Custom Column
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.
Styling the Folder Pane
this content covers features introduced in thunderbird 3 the folder pane in thunderbird is predominantly controlled by code in folderpane.js.
Using the Multiple Accounts API
some sample code: (where accountmanager is the account manager.
libmime content type handlers
a necessary capability of this module is to dynamically add the ability to decode and render various content types.
Using C struct and pointers
references this example is based on code found here.
Debugging Tips
running the following code shows only partial value information.
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
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.
Preferences System
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> ..
DOM Inspector internals - Firefox Developer Tools
source code organization the contents of the top-level directory for the dom inspector repository should look like base/ js/ inspector-cmdline.js makefile.in build/ install.js makefile.in resources/ content/ … locale/ … skin/ … makefile.in install.rdf jar.mn makefile.in...
DOM Inspector - Firefox Developer Tools
to find out who knows dom inspector code and where it lives, see the dom inspector module listing.
Application - Firefox Developer Tools
finding an example if you want to test this functionality and you don't have a handy pwa available, you can grab one of our simple examples to use: add to homescreen demo: shows pictures of foxes (source code | live version) js13kpwa demo: show information on entries to the js13k annual competition (source code | live version) how to debug service workers inspect web app manifests ...
Browser Toolbox - Firefox Developer Tools
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.
Breaking on exceptions - Firefox Developer Tools
to instruct the debugger to pause on an exception, tick these checkboxes in the breakpoints list: pause on exceptions pause on caught exceptions when an exception occurs, the line where it occurs is highlighted in the source pane, with a squiggly red line under the problematic code.
Debug eval sources - Firefox Developer Tools
you can debug javascript code that is evaluated dynamically, either as a string passed to eval() or as a string passed to the function constructor.
Highlight and inspect DOM nodes - Firefox Developer Tools
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.
Ignore a source - Firefox Developer Tools
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.
Search - Firefox Developer Tools
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.
How to - Firefox Developer Tools
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
recording call stacks the memory tool can tell you exactly where in your code you are allocating memory.
DOM allocation example - Firefox Developer Tools
for (var i = 0; i < toolbarbuttoncount; i++) { var toolbarbutton = createtoolbarbutton(); toolbar.appendchild(toolbarbutton); } return toolbar; } function createtoolbars() { var container = document.getelementbyid("container"); for (var i = 0; i < toolbarcount; i++) { var toolbar = createtoolbar(); container.appendchild(toolbar); } } createtoolbars(); a simple pseudocode representation of how this code operates looks like this: createtoolbars() -> createtoolbar() // called 200 times, creates 1 div element each time -> createtoolbarbutton() // called 20 times per toolbar, creates 1 span element each time in total, then, it creates 200 htmldivelement objects, and 4000 htmlspanelement objects.
Tree map view - Firefox Developer Tools
it also includes a separate rectangle for code that can't be correlated with a file, such as jit-optimized code.
Examine Event Listeners - Firefox Developer Tools
the inspector shows the word "event" next to elements in the html pane, that have event listeners bound to them: click the icon, then you'll see a popup listing all the event listeners bound to this element: each line 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.
Sorting algorithms comparison - Firefox Developer Tools
you can try out the example program here and clone the code here (be sure to check out the gh-pages branch).
Cache Storage - Firefox Developer Tools
the status code for the request that was made to fetch it.
Style Editor - Firefox Developer Tools
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.
Validators - Firefox Developer Tools
tune-up wizard links back to devedge if you're writing new code that isn't validating immediately, see the available standards-compliant authoring and development tools.
View Source - Firefox Developer Tools
syntax highlighting (toggle) applies syntax highlighting to the code.when syntax highlighting is on, view source also highlights parsing errors in red.
Web Console Helpers - Firefox Developer Tools
see the queryselector code snippet.
Web Console UI Tour - Firefox Developer Tools
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.
Web Console - Firefox Developer Tools
the web console: logs information associated with a web page: network requests, javascript, css, security errors and warnings as well as error, warning and informational messages explicitly logged by javascript code running in the page context enables you to interact with a web page by executing javascript expressions in the context of the page user interface of the web console parts of the web console ui.
Firefox Developer Tools
browser console see messages logged by the browser itself and by add-ons, and run javascript code in the browser's scope.
AbsoluteOrientationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
AbsoluteOrientationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
AbstractWorker.onerror - Web APIs
}; 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.
Accelerometer.Accelerometer() - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Accelerometer.x - Web APIs
WebAPIAccelerometerx
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Accelerometer.y - Web APIs
WebAPIAccelerometery
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Accelerometer.z - Web APIs
WebAPIAccelerometerz
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Accelerometer - Web APIs
if a feature policy blocks the use of a feature, it is because your code is inconsistent with the policies set on your server.
AmbientLightSensor.AmbientLightSensor() - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
AmbientLightSensor.illuminance - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
AmbientLightSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
AnalyserNode.fftSize - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.frequencyBinCount - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.getByteFrequencyData() - Web APIs
for more examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.getByteTimeDomainData() - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.getFloatFrequencyData() - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too).
AnalyserNode.getFloatTimeDomainData() - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too).
AnalyserNode.maxDecibels - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.minDecibels - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.smoothingTimeConstant - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
Animation.finished - Web APIs
examples the following code waits until all animations running on the element elem have finished, then deletes the element from the dom tree: promise.all( elem.getanimations().map( function(animation) { return animation.finished } ) ).then( function() { return elem.remove(); } ); specifications specification status comment web animationsthe definition of 'animation.finish...
AudioBuffer.getChannelData() - Web APIs
you can also run the code live, or view the source.
AudioBufferSourceNode.buffer - Web APIs
example for a full working example, see this code running live, or view the source.
AudioBufferSourceNode.start() - Web APIs
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.
AudioContext.close() - Web APIs
closed contexts cannot have new nodes created, but can decode audio data, create buffers, etc.
AudioContext.createMediaStreamDestination() - Web APIs
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.
AudioDestinationNode - Web APIs
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.
AudioListener.dopplerFactor - Web APIs
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!
AudioListener.forwardX - Web APIs
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!
AudioListener.forwardY - Web APIs
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!
AudioListener.forwardZ - Web APIs
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!
AudioListener.positionX - Web APIs
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!
AudioListener.positionY - Web APIs
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!
AudioListener.positionZ - Web APIs
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!
AudioListener.setOrientation() - Web APIs
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!
AudioListener.setPosition() - Web APIs
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!
AudioListener.speedOfSound - Web APIs
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!
AudioListener.upX - Web APIs
WebAPIAudioListenerupX
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!
AudioListener.upY - Web APIs
WebAPIAudioListenerupY
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!
AudioListener.upZ - Web APIs
WebAPIAudioListenerupZ
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!
AudioListener - Web APIs
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!
AudioNode - Web APIs
WebAPIAudioNode
example this simple snippet of code shows the creation of some audio nodes, and how the audionode properties and methods can be used.
AudioParam.exponentialRampToValueAtTime() - Web APIs
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.
AudioParam.linearRampToValueAtTime() - Web APIs
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.
AudioParam.setTargetAtTime() - Web APIs
onstant 0% 0.5 * timeconstant 39.3% 1 * timeconstant 63.2% 2 * timeconstant 86.5% 3 * timeconstant 95.0% 4 * timeconstant 98.2% 5 * timeconstant 99.3% n * timeconstant 1-e-n1 - e^{-n} examples in this example, we have a media source with two control buttons (see the webaudio-examples repo for the source code, or view the example live.) when these buttons are pressed, settargetattime() is used to fade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeconstant.
AudioParam.setValueAtTime() - Web APIs
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).
AudioParam.setValueCurveAtTime() - Web APIs
examples in this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.) when this button is pressed, setvaluecurveattime() is used to change the gain value between the values contained in the wavearray array: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.que...
AudioTrack - Web APIs
the language is specified as a bcp 47 (rfc 5646) language code, such as "en-us" or "pt-br".
AudioWorklet - Web APIs
the worklet's code is run in the audioworkletglobalscope global execution context, using a separate web audio thread which is shared by the worklet and other audio nodes.
AudioWorkletProcessor() - Web APIs
syntax the audioworkletprocessor and classes that derive from it cannot be instantiated directly from a user-supplied code.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
credentialpublickey (variable length) - a cose encoded public key.
BaseAudioContext.createAnalyser() - Web APIs
for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
BaseAudioContext.createBiquadFilter() - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BaseAudioContext.createChannelMerger() - Web APIs
var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currenttime); splitter.connect(gainnode, 0); // connect th...
BaseAudioContext.createChannelSplitter() - Web APIs
var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currenttime); splitter.connect(gainnode, 0); // connect th...
BaseAudioContext.createDelay() - Web APIs
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).
BaseAudioContext.createOscillator() - Web APIs
for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information.
BaseAudioContext.createPanner() - Web APIs
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!
BaseAudioContext.createStereoPanner() - Web APIs
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.
BasicCardResponse.billingAddress - Web APIs
dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc.
BasicCardResponse.cardNumber - Web APIs
dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc.
BasicCardResponse.cardholderName - Web APIs
dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc.
BasicCardResponse.expiryMonth - Web APIs
dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc.
BasicCardResponse.expiryYear - Web APIs
dick straw", "cardsecuritycode" : "999", "expirymonth" : "07", "expiryyear" : "2021", "billingaddress" : { "country" : "gb", // etc.
BatteryManager - Web APIs
additional methods in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties.
BiquadFilterNode.Q - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.detune - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.frequency - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.gain - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.type - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode - Web APIs
for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
Blob() - Web APIs
WebAPIBlobBlob
usvstring objects are encoded as utf-8.
manufacturerData - Web APIs
the manufacturerdata read-only property of the bluetoothadvertisingdata interface returns a map that relates company identifier codes to arraybuffers.
BluetoothAdvertisingData - Web APIs
bluetoothadvertisingdata.manufacturerdata read only returns a map that relates company identifier codes to arraybuffers.
Body.text() - Web APIs
WebAPIBodytext
the response is always decoded using utf-8.
Body - Web APIs
WebAPIBody
the response is always decoded using utf-8.
BroadcastChannel: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples this code uses addeventlistener to listen for messages and errors: const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); channel.addeventlistener('messageerror', (event) => { console.error(event); }); the same, but using the onmessage and onmessageerror event handler properties: const channel = new broadcastchannel('example-channel'); channel.onmessage = (event) => { received.textcontent = event.data; }; channel.onme...
Broadcast Channel API - Web APIs
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.
CSS.escape() - Web APIs
WebAPICSSescape
examples basic results css.escape(".foo#bar") // "\.foo\#bar" css.escape("()[]{}") // "\(\)\[\]\{\}" css.escape('--a') // "--a" css.escape(0) // "\30 ", the unicode code point of '0' is 30 css.escape('\0') // "\ufffd", the unicode replacement character in context uses to escape a string for use as part of a selector, the escape() method can be used: var element = document.queryselector('#' + css.escape(id) + ' > img'); the escape() method can also be used for escaping strings, although it escapes characters that don't strictly need to be esc...
CSSMathValue.operator - Web APIs
<div>my width has a <code>calc()</code> function</div> we assign a width with a calculation div { width: calc(50% - 0.5vw); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').values ); // cssnumericarray {0: cssunitval...
CSSNumericValue.sub() - Web APIs
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.
CSSNumericValue.sum() - Web APIs
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.
CSSPrimitiveValue.getFloatValue() - Web APIs
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.
CSSPrimitiveValue.setFloatValue() - Web APIs
syntax cssprimitivevalue.setfloatvalue(unittype, floatvalue); parameters unittype an unsigned short representing the code for the unit type, in which the value should be returned.
CSSRule - Web APIs
WebAPICSSRule
(until the documentation is completed, see the interface definition in the mozilla source code: nsidomcssimportrule.) cssrule.media_rule 4 cssmediarule cssrule.font_face_rule 5 cssfontfacerule cssrule.page_rule 6 csspagerule cssrule.keyframes_rule 7 csskeyframesrule cssrule.keyframe_rule 8 csskeyframerule reserved for future use 9 should be used to define color profiles in ...
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
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.
CSSStyleDeclaration.getPropertyPriority() - Web APIs
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.
CSSStyleDeclaration.getPropertyValue() - Web APIs
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.
CSSStyleDeclaration.length - Web APIs
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.
CSSStyleDeclaration.parentRule - Web APIs
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.
CSSStyleDeclaration.removeProperty() - Web APIs
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.
CSSStyleSheet.addRule() - Web APIs
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.
CSSStyleSheet.ownerRule - Web APIs
examples this snippet of code looks for rules which were not imported into the document using an @import at-rule.
CSSValue.cssValueType - Web APIs
syntax cssvaluetype = cssvalue.cssvaluetype; value an unsigned short representing a code defining the type of the value.
CSSValue - Web APIs
WebAPICSSValue
cssvalue.cssvaluetyperead only an unsigned short representing a code defining the type of the value.
Managing screen orientation - Web APIs
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.
Using dynamic styling information - Web APIs
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.
Using the CSS Typed Object Model - Web APIs
open up this example in codepen or jsfiddle, and change some features.
CSS Typed Object Model API - Web APIs
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.
Cache.add() - Web APIs
WebAPICacheadd
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.
Cache.addAll() - Web APIs
WebAPICacheaddAll
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.
Cache.match() - Web APIs
WebAPICachematch
if fetch() returns a valid http response with an response code in the 4xx or 5xx range, the catch() will not be called.
CacheStorage.delete() - Web APIs
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.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
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.
CanvasRenderingContext2D.clearRect() - Web APIs
examples erasing the whole canvas this code snippet erases the entire canvas.
CanvasRenderingContext2D.fillRect() - Web APIs
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.
CanvasRenderingContext2D.isPointInPath() - Web APIs
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 circ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
html <canvas id="canvas"></canvas> <p>in stroke: <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.stroke(); result.innertext = ctx.ispointinstroke(50, 10); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in th...
CanvasRenderingContext2D.measureText() - Web APIs
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.
CanvasRenderingContext2D.stroke() - Web APIs
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.
CanvasRenderingContext2D - Web APIs
this code draws a house: // set line width ctx.linewidth = 10; // wall ctx.strokerect(75, 140, 150, 110); // door ctx.fillrect(130, 190, 40, 60); // roof ctx.beginpath(); ctx.moveto(50, 140); ctx.lineto(150, 60); ctx.lineto(250, 140); ctx.closepath(); ctx.stroke(); the resulting drawing looks like this: reference drawing rectangles there are three methods that immediately draw rectangles to the ...
Advanced animations - Web APIs
the following code will set us up.
Basic usage of canvas - Web APIs
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.
Finale - Web APIs
WebAPICanvas APITutorialFinale
more examples and tutorials there are a variety of demos and further explanations about canvas on these sites: codepen.io front end developer playground & code editor in the browser.
Hit regions and accessibility - Web APIs
see also this codepen demo.
Pixel manipulation with canvas - Web APIs
canvas.toblob(callback, type, encoderoptions) creates a blob object representing the image contained in the canvas.
Transformations - Web APIs
this would be easy for two properties, but if we have more than that, our code would become very long, very fast.
Canvas tutorial - Web APIs
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.
ChannelMergerNode - Web APIs
var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currenttime); splitter.connect(gainnode, 0); // connect th...
ChannelSplitterNode - Web APIs
var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currenttime); splitter.connect(gainnode, 0); // connect th...
ChildNode.after() - Web APIs
WebAPIChildNodeafter
with(node) { after("foo"); } // referenceerror: after is not defined polyfill you can polyfill the after() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { return; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.call(argu...
ChildNode.before() - Web APIs
WebAPIChildNodebefore
with(node) { before("foo"); } // referenceerror: before is not defined polyfill you can polyfill the before() method in internet explorer 9 and higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { return; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice.call...
ChildNode.remove() - Web APIs
WebAPIChildNoderemove
with(node) { remove(); } // referenceerror: remove is not defined polyfill you can polyfill the remove() method in internet explorer 9 and higher with the following code: // from:https://github.com/jserz/js_piece/blob/master/dom/childnode/remove()/remove().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('remove')) { return; } object.defineproperty(item, 'remove', { configurable: true, enumerable: true, writable: true, value: function remove() { this.parentnode.removechild(this); ...
ChildNode.replaceWith() - Web APIs
with(node) { replacewith("foo"); } // referenceerror: replacewith is not defined polyfill you can polyfill the replacewith() method in internet explorer 10+ and higher with the following code: function replacewithpolyfill() { 'use-strict'; // for safari, and ie > 10 var parent = this.parentnode, i = arguments.length, currentnode; if (!parent) return; if (!i) // if there are no arguments parent.removechild(this); while (i--) { // i-- decrements i and returns the value of i before the decrement currentnode = arguments[i]; if (typeof currentnode !== 'object'){ ...
Clipboard.write() - Web APIs
WebAPIClipboardwrite
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.
Clipboard API - Web APIs
since readtext() (and read(), for that matter) returns an empty string if the clipboard isn't text, this code is safe.
CloseEvent() - Web APIs
"code", optional and defaulting to 0, of type unsigned short, that is the connection close code sent by the server.
console.assert() - Web APIs
WebAPIConsoleassert
examples the following code example demonstrates the use of a javascript object following the assertion: const errormsg = 'the # is not even'; for (let number = 2; number <= 5; number += 1) { console.log('the # is ' + number); console.assert(number % 2 === 0, {number: number, errormsg: errormsg}); // or, using es2015 object property shorthand: // console.assert(number % 2 === 0, {number, errormsg}); } // ou...
console.count() - Web APIs
WebAPIConsolecount
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.
Console.countReset() - Web APIs
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.
Console.group() - Web APIs
WebAPIConsolegroup
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.
Console.timeStamp() - Web APIs
WebAPIConsoletimeStamp
this lets you correlate a point in your code with the other events recorded in the timeline, such as layout and paint events.
Console API - Web APIs
the console api provides functionality to allow developers to perform debugging tasks, such as logging messages or the values of variables at set points in your code, or timing how long an operation takes to complete.
ConvolverNode.buffer - Web APIs
// 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(); ...
ConvolverNode.normalize - Web APIs
// 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(); ...
CustomElementRegistry - Web APIs
examples the following code is taken from our word-count-web-component example (see it live also).
DOMHighResTimeStamp - Web APIs
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(); /* ...
DOMImplementation.createHTMLDocument() - Web APIs
teelement("p"); p.innerhtml = "this is a new paragraph."; try { doc.body.appendchild(p); } catch(e) { console.log(e); } // copy the new html document into the frame let destdocument = frame.contentdocument; let srcnode = doc.documentelement; let newnode = destdocument.importnode(srcnode, true); destdocument.replacechild(newnode, destdocument.documentelement); } the code in lines 4–12 handle creating the new html document and inserting some content into it.
DOMParser - Web APIs
WebAPIDOMParser
the domparser interface provides the ability to parse xml or html source code from a string into a dom document.
DOMPointInit - Web APIs
this same code will work to create a dompointreadonly object; just change the interface name in the code.
DOMPointReadOnly.x - Web APIs
this property cannot be changed by javascript code in this read-only version of the dompoint object.
DOMRect.DOMRect() - Web APIs
WebAPIDOMRectDOMRect
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.
DOMRectReadOnly() - Web APIs
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.
DOMTokenList.replace() - Web APIs
the following code will only work with ie10-11.
DOMTokenList.supports() - Web APIs
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.items - Web APIs
items[" + i + "].kind = " + ev.datatransfer.items[i].kind + " ; type = " + ev.datatransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples of <code>datatransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">drag item 1 to the drop zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">drag item 2 to the drop zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</...
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
the datatransferitem.getasstring() method invokes the given callback with the drag data item's string data as the argument if the item's kind is a plain unicode string (i.e.
DataTransferItem.kind - Web APIs
'string' if the kind of drag data item is a plain unicode string.
DataTransferItem.type - Web APIs
the type is a unicode string generally given by a mime type, although a mime type is not required.
DataTransferItem.webkitGetAsEntry() - Web APIs
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.
DataTransferItemList.add() - Web APIs
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.
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
bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and sends it a message using worker.postmessage(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); the worker can listen for this message using addeventlistener(): // inside static/scripts/worker.js self.addeventlistener('message', (event) => { console.log(`received message from parent: ${event.data}`); });...
DedicatedWorkerGlobalScope.onmessage - Web APIs
}; example the following code snippet shows creation of a worker object using the worker() constructor.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
example the following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script.
DelayNode.delayTime - Web APIs
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).
DelayNode - Web APIs
WebAPIDelayNode
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).
Using light sensors - Web APIs
the code alerts the user that they are working in a dark environment and then changes the page's background to a darker color.
Document: animationcancel event - Web APIs
examples this code adds a listener to the animationcancel event.
Document: animationiteration event - Web APIs
examples this code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationcount = 0; document.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: let iterationcount = 0; document.onanimationiteration = () => { ...
Document.createEntityReference() - Web APIs
which has the value referred to by the entity, using unicode escape sequences or fromcharcode() as necessary.
Document.createTouch() - Web APIs
in following code snippet, two touch objects are created for the target element.
Document.createTouchList() - Web APIs
in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects.
Document.currentScript - Web APIs
(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.
Document: drag event - Web APIs
interface dragevent event handler property ondrag examples see this code in a jsfiddle demo or interact with it below.
Document: dragend event - Web APIs
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.
Document: dragenter event - Web APIs
interface dragevent event handler property ondragenter examples see the drag event for example code or this jsfiddle demo.
Document: dragexit event - Web APIs
interface dragevent event handler property ondragexit examples see the drag event for example code or this jsfiddle demo.
Document: dragleave event - Web APIs
interface dragevent event handler property ondragleave examples see the drag event for example code or this jsfiddle demo.
Document: dragover event - Web APIs
interface dragevent event handler property ondragover examples see the drag event for example code or this jsfiddle demo.
Document: dragstart event - Web APIs
interface dragevent event handler property ondragstart examples see the drag event for example code or this jsfiddle demo.
Document: drop event - Web APIs
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.
Document.evaluate() - Web APIs
WebAPIDocumentevaluate
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
example an example of how to use it on codepen.
Document.getAnimations() - Web APIs
examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate.
Document.getElementById() - Web APIs
</head> <body> <p id="para">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button> </body> </html> javascript function changecolor(newcolor) { var elem = document.getelementbyid('para'); elem.style.color = newcolor; } result usage notes the capitalization of "id" in the name of this method must be correct for the code to function; getelementbyid() is not valid and will not work, however natural it may seem.
Document.mozSetImageElement() - Web APIs
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.
Document.onbeforescriptexecute - Web APIs
fired when the code in a <script> element declared in an html document is about to start executing.
Document.open() - Web APIs
WebAPIDocumentopen
examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again.
Document.styleSheetSets - Web APIs
example given an <ul> (list) element with the id "sheetlist", you can populate it with the names of all the available style sheet sets with code like this: let list = document.getelementbyid('sheetlist'); let sheets = document.stylesheetsets; list.innerhtml = ''; for (let i = 0; i < sheets.length; i++) { let item = document.createelement('li'); item.innerhtml = sheets[i]; list.appendchild(item); } notes the list of available style sheet sets is constructed by enumerating all the style sheets available for the document, in the order in which they're listed in...
Document: touchcancel event - Web APIs
bubbles yes cancelable no interface touchevent event handler property ontouchcancel examples code samples for those events are available on the dedicated page: touch events.
Document: touchend event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchend examples code samples for those events are available on the dedicated page: touch events.
Document: touchmove event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchmove examples code samples for those events are available on the dedicated page: touch events.
Document: touchstart event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchstart examples code samples for those events are available on the dedicated page: touch events.
Document: transitioncancel event - Web APIs
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.
Document: transitionend event - Web APIs
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.
Document: transitionrun event - Web APIs
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.
Document: transitionstart event - Web APIs
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.
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
the code for it is below the demo.
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
utput = document.getelementbyid("output"); if (document.elementsfrompoint) { let elements = document.elementsfrompoint(30, 20); for (var i = 0; i < elements.length; i++) { output.textcontent += elements[i].localname; if (i < elements.length - 1) { output.textcontent += " < "; } } } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code>document.elementsfrompoint()</code>" + "</span>"; } specifications specification status shadow domthe definition of 'elementsfrompoint()' in that specification.
DocumentTimeline.DocumentTimeline() - Web APIs
this bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline = new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes = new keyframeeffect(cat, keyframes, timing); var catanimation = new animation(catkeyframes, sharedtimelin...
DocumentTimeline - Web APIs
this bit of code would start all the cats animating 500 milliseconds into their animations: const cats = document.queryselectorall('.sharedtimelinecat'); const sharedtimeline = new documenttimeline({ origintime: 500 }); for (const cat of cats) { const catkeyframes = new keyframeeffect(cat, keyframes, timing); const catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); } speci...
Events and the DOM - Web APIs
html attribute <button onclick="alert('hello world!')"> the javascript code in the attribute is passed the event object via the event parameter.
Examples of web and XML development using the DOM - Web APIs
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.
How to create a DOM tree - Web APIs
it applies to all gecko-based applications (such as firefox) both in privileged (extensions) and unprivileged (web pages) code.
Document Object Model (DOM) - Web APIs
dnode comment customevent document documentfragment documenttype domerror domexception domimplementation domstring domtimestamp domstringlist domtokenlist element event eventtarget htmlcollection mutationobserver mutationrecord namednodemap node nodefilter nodeiterator nodelist nondocumenttypechildnode parentnode processinginstruction selection range text textdecoder textencoder timeranges treewalker url window worker xmldocument obsolete dom interfaces the document object model has been highly simplified.
Element.attachShadow() - Web APIs
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.
Element: auxclick event - Web APIs
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).
Element.classList - Web APIs
WebAPIElementclassList
if (!hasownprop.call(this, "classlist")) polyfillclasslist(this); return this.classlist; }, configurable: 0, set: function(val){this.classname = val} }); } catch(e) { // less performant fallback for older browsers (ie 6-8): window[" ucl"] = polyfillclasslist; // the below code ensures polyfillclasslist is applied to all current and future elements in the doc.
Element.getAnimations() - Web APIs
examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document.
Element.getBoundingClientRect() - Web APIs
scripts without access to these properties can use code like this: // for scrollx (((t = document.documentelement) || (t = document.body.parentnode)) && typeof t.scrollleft == 'number' ?
Element.getClientRects() - Web APIs
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.
Element.insertAdjacentElement() - Web APIs
entelement('beforebegin',tempdiv); } setlistener(tempdiv); }); afterbtn.addeventlistener('click', function() { var tempdiv = document.createelement('div'); tempdiv.style.backgroundcolor = randomcolor(); if (activeelem) { activeelem.insertadjacentelement('afterend',tempdiv); } setlistener(tempdiv); }); have a look at our insertadjacentelement.html demo on github (see the source code too.) here we have a sequence of <div> elements inside a container.
Element: mousewheel event - Web APIs
see webinputeventfactory::mousewheelevent of the chromium's source code for the detail.
Element.scrollTop - Web APIs
WebAPIElementscrollTop
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.
Element: touchcancel event - Web APIs
bubbles yes cancelable no interface touchevent event handler property ontouchcancel examples code samples for those events are available on the dedicated page: touch events.
Element: touchend event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchend examples code samples for those events are available on the dedicated page: touch events.
Element: touchmove event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchmove examples code samples for those events are available on the dedicated page: touch events.
Element: touchstart event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchstart examples code samples for those events are available on the dedicated page: touch events.
ElementCSSInlineStyle.style - Web APIs
the following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the getcomputedstyle() method: <!doctype html> <html> <body style="font-weight:bold;"> <div style="color:red" id="myelement">..</div> </body> </html> var element = document.getelementbyid("myelement"); var out = ""; var elementstyle = element.style; var computedsty...
Event.cancelable - Web APIs
WebAPIEventcancelable
custom events created by other javascript code control if they can be canceled when they are created.
Event.currentTarget - Web APIs
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.
Event.originalTarget - Web APIs
note: originaltarget may also be native anonymous content (see bug 208427), in which case it's useless for non-privileged code.
Event.returnValue - Web APIs
WebAPIEventreturnValue
note: while returnvalue has been adopted into the dom standard, it is present primarily to support existing code.
EventSource - Web APIs
once the connection is opened, incoming messages from the server are delivered to your code in the form of events.
EventTarget.dispatchEvent() - Web APIs
all applicable event handlers will execute and return before the code continues on after the call to dispatchevent().
EventTarget.removeEventListener() - Web APIs
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.
EventTarget - Web APIs
additional methods in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties.
ExtendableMessageEvent.data - Web APIs
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.
ExtendableMessageEvent.lastEventId - Web APIs
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.
ExtendableMessageEvent.origin - Web APIs
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.
ExtendableMessageEvent.ports - Web APIs
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.
ExtendableMessageEvent.source - Web APIs
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.
File.File() - Web APIs
WebAPIFileFile
usvstring objects are encoded as utf-8.
File.getAsDataURL() - Web APIs
WebAPIFilegetAsDataURL
summary the getasdataurl provides a data: url that encodes the entire contents of the referenced file.
File.getAsText() - Web APIs
WebAPIFilegetAsText
ed media types var accept = { binary : ["image/png", "image/jpeg"], text : ["text/plain", "text/css", "application/xml", "text/html"] }; var file; for (var i = 0; i < files.length; i++) { file = files[i]; // if file type could be detected if (file !== null) { if (accept.text.indexof(file.mediatype) > -1) { // file is of type text, which we accept // make sure it's encoded as utf-8 var data = file.getastext("utf-8"); // modify data with string methods } else if (accept.binary.indexof(file.mediatype) > -1) { // binary } } } specification not part of any specification.
File.mozFullPath - Web APIs
WebAPIFilemozFullPath
this property is only available from within browser code or old-style xpcom-based firefox extensions.
FileList - Web APIs
WebAPIFileList
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.
FileReader() - Web APIs
example the following code snippet shows creation of a filereader object using the filereader() constructor and subsequent usage of the object: function printfile(file) { var reader = new filereader(); reader.onload = function(evt) { console.log(evt.target.result); }; reader.readastext(file); } specifications specification status comment file api working draft initial definition ...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
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.
FileSystemDirectoryEntry - Web APIs
example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes.
FileSystemEntry.toURL() - Web APIs
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 ...
FileSystemFileEntry - Web APIs
example the following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "meow".
FileSystemFlags.create - Web APIs
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).
FileSystemFlags.exclusive - Web APIs
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).
FileSystemFlags - Web APIs
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).
FileHandle API - Web APIs
note: the above code only creates a "temporary file" that exists only while you hold the filehandle instance.
Introduction to the File and Directory Entries API - Web APIs
its direct, in-order programming model can make code easier to read.
FontFace.FontFace() - Web APIs
WebAPIFontFaceFontFace
it can have the following keys: family: family style: style weight: weight stretch: stretch unicoderange: unicode range variant: variant featuresettings: feature settings example async function loadfonts() { const font = new fontface('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load(); // add font to document document.fonts.add(font); // enable font with css class document.body.classlist.add('fonts-loaded'); } specifications ...
FontFaceSet.check() - Web APIs
WebAPIFontFaceSetcheck
"italic bold 16px roboto" text: limit the font faces to those whose unicode range contains at least one of the characters in text.
FormData() - Web APIs
WebAPIFormDataFormData
it will also encode file input content.
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
example code of the interfaces described in this document is included in using the frame timing api.
Gamepad.buttons - Web APIs
WebAPIGamepadbuttons
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 gamepad...
GamepadButton - Web APIs
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 gamepad...
Geolocation.clearWatch() - Web APIs
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
lse | true examples var options = { enablehighaccuracy: true, timeout: 5000, maximumage: 0 }; function success(pos) { var crd = pos.coords; console.log('your current position is:'); console.log(`latitude : ${crd.latitude}`); console.log(`longitude: ${crd.longitude}`); console.log(`more or less ${crd.accuracy} meters.`); } function error(err) { console.warn(`error(${err.code}): ${err.message}`); } navigator.geolocation.getcurrentposition(success, error, options); specifications specification status comment geolocation api recommendation initial specification.
Geolocation.watchPosition() - Web APIs
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.
GeolocationCoordinates.longitude - Web APIs
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.
GeolocationPositionError - Web APIs
geolocationpositionerror.code read only secure context returns an unsigned short representing the error code.
Geolocation API - Web APIs
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.
GlobalEventHandlers.onauxclick - Web APIs
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).
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.
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.
GlobalEventHandlers.onresize - Web APIs
examples window size logger <p>resize the browser window to fire the <code>resize</code> event.</p> <p>window height: <span id="height"></span></p> <p>window width: <span id="width"></span></p> const heightoutput = document.queryselector('#height'); const widthoutput = document.queryselector('#width'); function resize() { heightoutput.textcontent = window.innerheight; widthoutput.textcontent = window.innerwidth; } window.onresize = resize; specification ...
Gyroscope.Gyroscope() - Web APIs
if a feature policy blocks use of a feature, it is because your code is inconsistent with the policies set on your server.
Gyroscope.x - Web APIs
WebAPIGyroscopex
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Gyroscope.y - Web APIs
WebAPIGyroscopey
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Gyroscope.z - Web APIs
WebAPIGyroscopez
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Gyroscope - Web APIs
WebAPIGyroscope
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
msAudioCategory - Web APIs
note that you must set the msaudiocategory before setting the src property in code.
HTMLCanvasElement.getContext() - Web APIs
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 { ...
HTMLCanvasElement.height - Web APIs
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.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
also uses netutil.jsm 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(); var netutilcallback = function() { return function(result) { if (!components.issuccesscode(result)) { alert('failed to create icon'); } else { alert('succesfully made'); } }; } var mfascallback = function(iconname) { return function(instream) { var file = fileutils.getfile('desk', [iconname + '.ico']); var outstream = fileutils.openfileoutputstream(file); cu.import('resource://gre/modules/netutil.jsm'); netutil.asy...
HTMLCanvasElement.mozGetAsFile() - Web APIs
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.
HTMLCanvasElement.width - Web APIs
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.
HTMLElement: animationcancel event - Web APIs
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.
HTMLElement: animationiteration event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationiteration examples this code uses animationiteration to keep track of the number of iterations an animation has completed: const animated = document.queryselector('.animated'); let iterationcount = 0; animated.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: const anim...
HTMLElement.lang - Web APIs
WebAPIHTMLElementlang
the language code returned by this property is defined in the tags for identifying languages (bcp47) ietf document.
HTMLElement: transitioncancel event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property globaleventhandlers.ontransitioncancel examples this code gets an element that has a transition defined and adds a listener to the transitioncancel event: const transition = document.queryselector('.transition'); transition.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): const transition = document.queryselector('.transition'); transition.ontransitioncancel = () => { console.log('transition c...
HTMLElement: transitionend event - Web APIs
examples this code gets an element that has a transition defined and adds a listener to the transitionend event: const transition = document.queryselector('.transition'); transition.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend: const transition = document.queryselector('.transition'); transition.ontransitionend = () => { console.log(...
HTMLElement: transitionrun event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property ontransitionrun examples this code adds a listener to the transitionrun event: el.addeventlistener('transitionrun', () => { console.log('transition is running but hasn\'t necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): el.ontransitionrun = () => { console.log('transition started running, and will start transitioning when the transition delay has expired'); }; live example in the following example, we have a simple <div> element, styled with a transition...
HTMLElement: transitionstart event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property ontransitionstart examples this code adds a listener to the transitionstart event: element.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): element.ontransitionrun = () => { console.log('started transitioning'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .t...
HTMLFormElement.requestSubmit() - Web APIs
if, on the other hand, requestsubmit() isn't available, this code falls back to calling the form's submit() method.
HTMLHyperlinkElementUtils.hash - Web APIs
the fragment is not percent-decoded.
HTMLHyperlinkElementUtils.origin - Web APIs
the htmlhyperlinkelementutils.origin read-only property is a usvstring containing the unicode serialization of the origin of the represented url; that is: for url using the http or https, 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 url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:.
HTMLImageElement.align - Web APIs
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.
HTMLImageElement.crossOrigin - Web APIs
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.
HTMLImageElement.height - Web APIs
<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.
HTMLImageElement.naturalHeight - Web APIs
javascript let output = document.queryselector(".output"); let image = document.queryselector("img"); window.addeventlistener("load", event => { output.innerhtml += `natural size: ${image.naturalwidth} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output.
HTMLImageElement.naturalWidth - Web APIs
javascript let output = document.queryselector(".output"); let image = document.queryselector("img"); window.addeventlistener("load", event => { output.innerhtml += `natural size: ${image.naturalwidth} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output.
HTMLImageElement.sizes - Web APIs
</article> css article { margin: 1em; max-width: 60em; min-width: 20em; height: 100vh; border: 4em solid #880e4f; border-radius: 7em; padding: 1.5em; font: 16px "open sans", verdana, arial, helvetica, sans-serif; } article img { display: block; max-width: 100%; border: 1px solid #888; box-shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em; } javascript the javascript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the javascript string object method replace() to replace the relevant portion of the sizes string.
HTMLImageElement.width - Web APIs
<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.
HTMLImageElement.x - Web APIs
<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.
HTMLImageElement.y - Web APIs
<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.
HTMLInputElement.webkitEntries - Web APIs
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.
HTMLLinkElement - Web APIs
htmllinkelement.hreflang is a domstring representing the language code for the linked resource.
HTMLMediaElement.audioTracks - Web APIs
<video id="video" src="somevideo.mp4"></video> javascript the javascript code handles muting the video element's audio tracks.
HTMLMediaElement.captureStream() - Web APIs
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.
HTMLMediaElement.error - Web APIs
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.
HTMLMediaElement.play() - Web APIs
be sure your code doesn't expect an immediate response.
HTMLScriptElement - Web APIs
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).
HTMLSelectElement.form - Web APIs
the below code gives all select elements in a particular form a css class of "selectclass": <script type="text/javascript"> var form_element = document.getelementbyid('subscribe_form'); var vist = form_element.style; if (vist.display=='' || vist.display=='none') { vist.display = 'block'; } else { vist.display = 'none'; } </script> specifications specification status comment html ...
HTMLSelectElement.selectedOptions - Web APIs
javascript the javascript code that establishes the event handler for the button, as well as the event handler itself, looks like this: let orderbutton = document.getelementbyid("order"); let itemlist = document.getelementbyid("foods"); let outputbox = document.getelementbyid("output"); orderbutton.addeventlistener("click", function() { let collection = itemlist.selectedoptions; let output = ""; for (let i=0; i<collec...
HTMLTableCellElement - Web APIs
they are documented primarily to help understand older code bases.
Drag Operations - Web APIs
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.
HTML Drag and Drop API - Web APIs
identify what is draggable making an element draggable requires adding the draggable attribute and the ondragstart global event handler, as shown in the following code sample: <script> function dragstart_handler(ev) { // add the target element's id to the data transfer object ev.datatransfer.setdata("text/plain", ev.target.id); } window.addeventlistener('domcontentloaded', () => { // get the element by id const element = document.getelementbyid("p1"); // add the ondragstart event listener element.addeventlistener("dragstart", dra...
Headers - Web APIs
WebAPIHeaders
see their dedicated pages for example code.
History.pushState() - Web APIs
WebAPIHistorypushState
with the hash-based approach, you need to encode all of the relevant data into a short string.
History.state - Web APIs
WebAPIHistorystate
examples the code below logs the value of history.state before using the pushstate() method to push a value to the history.
Working with the History API - Web APIs
with the hash-based approach, you need to encode all of the relevant data into a short string.
IDBDatabase - Web APIs
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).
IDBEnvironment - Web APIs
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; }; } browser compatibility the compatibility table on this page is generated from structured da...
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
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.
IDBFactory - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
IDBFactorySync - Web APIs
exceptions this method can raise an idbdatabaseexception with the following codes: non_transient_err if the name parameter is not valid.
IDBKeyRange - Web APIs
to retrieve all keys within a certain range, you can use the following code constructs: range code all keys ≥ x idbkeyrange.lowerbound(x) all keys > x idbkeyrange.lowerbound(x, true) all keys ≤ y idbkeyrange.upperbound(y) all keys < y idbkeyrange.upperbound(y, true) all keys ≥ x && ≤ y idbkeyrange.bound(x, y) all keys > x &&< y idbkeyrange.bound(x, y, true, true) all ke...
IDBObjectStore.add() - Web APIs
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().
IDBObjectStore.autoIncrement - Web APIs
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().
IDBObjectStore.clear() - Web APIs
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().
IDBObjectStore.createIndex() - Web APIs
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.
IDBObjectStore.delete() - Web APIs
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".
IDBObjectStore.get() - Web APIs
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".
IDBObjectStore.indexNames - Web APIs
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().
IDBObjectStore.keyPath - Web APIs
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().
IDBObjectStore.name - Web APIs
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().
IDBObjectStore.transaction - Web APIs
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().
IDBOpenDBRequest.onupgradeneeded - Web APIs
inside the event handler function you can include code to upgrade the database structure, as shown in the example below.
IDBRequest - Web APIs
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.
IDBTransaction.abort() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.db - Web APIs
WebAPIIDBTransactiondb
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.error - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.mode - Web APIs
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.
IDBTransaction.objectStore() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.onabort - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.oncomplete - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBTransaction.onerror - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IDBVersionChangeEvent.newVersion - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
IDBVersionChangeEvent - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
the old name is being kept as an alias to avoid code breakage.
ImageBitmapRenderingContext - Web APIs
the old name is being kept as an alias to avoid code breakage.
ImageCapture - Web APIs
example the following code is taken from chrome's grab frame - take photo sample.
IndexedDB API - Web APIs
they are still documented in case you need to update previously written code: idbversionchangerequest represents a request to change the version of a database.
compareVersion - Web APIs
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.
enabled - Web APIs
example the following code uses the startsoftwareupdate method to unconditionally trigger a download from http://royalairways/royalpkg.xpi as long as software installation is enabled on the browser: if (installtrigger.enabled() ) { installtrigger.startsoftwareupdate ("http://royalair.com/rasoft.xpi"); } ...
InstallTrigger - Web APIs
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.
IntersectionObserverEntry.intersectionRect - Web APIs
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.
Keyboard - Web APIs
WebAPIKeyboard
a list of valid code values is found in the ui events keyboardevent code values spec.
KeyboardEvent.altKey - Web APIs
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.
KeyboardEvent.location - Web APIs
dom_key_location_numpad 3 the key was on the numeric keypad, or has a virtual key code that corresponds to the numeric keypad.
KeyboardEvent.shiftKey - Web APIs
syntax var shiftkeypressed = instanceofkeyboardevent.shiftkey return value a boolean example <html> <head> <title>shiftkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key pressed: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "shift key pressed: " + e.shiftkey + "\n" + "alt key pressed: " + e.altkey + "\n" ); } </script> </head> <body onkeypress="showchar(event);"> <p>press any character key, with or without holding down the shift key.<br /> you can also use the shift key together with the alt key.</p> </body> </html> specifications sp...
KeyboardLayoutMap.get() - Web APIs
a list of valid keys is found in the ui events keyboardevent code values spec.
KeyboardLayoutMap.has() - Web APIs
a list of valid keys is found in the ui events keyboardevent code values spec.
KeyboardLayoutMap - Web APIs
a list of valid keys is found in the ui events keyboardevent code values specification.
LinearAccelerationSensor.LinearAccelerationSensor() - Web APIs
if a feature policy blocks use of a feature, it is because your code is inconsistent with the policies set on your server.
LinearAccelerationSensor.x - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
LinearAccelerationSensor.y - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
LinearAccelerationSensor.z - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
LinearAccelerationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
LocalMediaStream - Web APIs
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.
Location: hash - Web APIs
WebAPILocationhash
the fragment is not percent-decoded.
Location: origin - Web APIs
WebAPILocationorigin
the origin read-only property of the location interface is a usvstring containing the unicode serialization of the origin of the represented url; that is: for url using the http or https, 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 url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:.
Locks.name - Web APIs
WebAPILockname
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.
Magnetometer.Magnetometer() - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Magnetometer.x - Web APIs
WebAPIMagnetometerx
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Magnetometer.y - Web APIs
WebAPIMagnetometery
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Magnetometer.z - Web APIs
WebAPIMagnetometerz
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Magnetometer - Web APIs
if a feature policy blocks use of a feature, it's because your code is inconsistent with the policies set on your server.
MediaCapabilities - Web APIs
the api can be used to query the browser about the decoding abilities of the device based on codecs, profile, resolution, and bitrates.
MediaDecodingConfiguration - Web APIs
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.
MediaDevices.getSupportedConstraints() - Web APIs
"constraintlist"> </ul> css body { font: 15px arial, sans-serif; } javascript let constraintlist = document.getelementbyid("constraintlist"); let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); for (let constraint in supportedconstraints) { if (supportedconstraints.hasownproperty(constraint)) { let elem = document.createelement("li"); elem.innerhtml = "<code>" + constraint + "</code>"; constraintlist.appendchild(elem); } } result specifications specification status comment media capture and streamsthe definition of 'getsupportedconstraints()' in that specification.
MediaEncodingConfiguration - Web APIs
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.
MediaQueryList.media - Web APIs
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.
MediaQueryList - Web APIs
is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textcontent = 'this is a wide screen — more than 600px wide.'; document.body.style.backgroundcolor = 'blue'; } } mql.addeventlistener('change', screentest); note: you can find this example on github (see the source code, and also see it running live).
MediaRecorder: error event - Web APIs
the mediarecorder interface's error event is fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
MediaRecorder.isTypeSupported - Web APIs
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.onerror - Web APIs
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.
MediaRecorder.onpause - Web APIs
the mediarecorder.onpause event handler (part of the mediarecorder api) handles the pause event, allowing you to run code in response to the media recording being paused.
MediaRecorder.onresume - Web APIs
the mediarecorder.onresume event handler (part of the mediarecorder api) handles the resume event, allowing you to run code in response to the media recording being resumed after pausing.
MediaRecorder.onstart - Web APIs
the mediarecorder.onstartevent handler (part of the mediarecorder api) handles the start event, allowing you to run code in response to media recording being started by a mediarecorder.
MediaRecorder.onwarning - Web APIs
the mediarecorder.onwarning event handler (part of the mediarecorder api) handles the recordingwarning event, allowing you to run code in response to non-fatal errors being thrown during media recording via a mediarecorder, which don't halt recording.
MediaSession.setPositionState() - Web APIs
this can be particularly useful if your code implements a player for type of media not directly supported by the browser.
MediaSource.activeSourceBuffers - Web APIs
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.activesourcebuffers); // will contain the source buffer that was added above, // as it is selected for playing in the video player video.play(); //console.log(mediasource.readystate); // ended }); sourc...
MediaSource.duration - Web APIs
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); }); }; ...
MediaSource.removeSourceBuffer() - Web APIs
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.
MediaSource.sourceBuffers - Web APIs
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); }); }; ...
MediaStream.onaddtrack - Web APIs
the addtrack event does not get fired when javascript code explicitly adds tracks to the stream (by calling addtrack()).
MediaStream.onremovetrack - Web APIs
the removetrack event does not get fired when javascript code explicitly removes tracks from the stream (by calling removetrack()).
MediaStreamTrack.getConstraints() - Web APIs
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.
MediaStreamTrack - Web APIs
not doing so correctly will result in your code being unreliable.
MediaTrackConstraints.logicalSurface - Web APIs
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.
MediaTrackSettings.noiseSuppression - Web APIs
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.
MediaTrackSupportedConstraints.frameRate - Web APIs
"not supported" with code to provide alternative methods for presenting the audiovisual information you want to share with the user or otherwise work with.
Media Capture and Streams API (Media Stream) - Web APIs
these no longer exist, and you should update any existing code to instead use mediastreamtrack directly.
MerchantValidationEvent() - Web APIs
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().
MessageChannel() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessageChannel.port1 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel() constructor.
MessageChannel.port2 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessageEvent - Web APIs
the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
MessagePort.close() - Web APIs
WebAPIMessagePortclose
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.
MessagePort.onmessage - Web APIs
}; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessagePort.postMessage() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
MessagePort.start() - Web APIs
WebAPIMessagePortstart
example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using onmessage: channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } another option would be to do this using eventtarget.addeventlistener, however, when this method is used, you need to explicitly call start() to begin the flow of messages to this document: channel.port1.addeventlistener('me...
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.altKey - Web APIs
WebAPIMouseEventaltKey
html <p>click anywhere to test the <code>altkey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the alt key is pressed: ${e.altkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.altkey...
MouseEvent.button - Web APIs
WebAPIMouseEventbutton
logmousebutton); function logmousebutton(e) { if (typeof e === 'object') { switch (e.button) { case 0: log.textcontent = 'left button clicked.'; break; case 1: log.textcontent = 'middle button clicked.'; break; case 2: log.textcontent = 'right button clicked.'; break; default: log.textcontent = `unknown button code: ${e.button}`; } } } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.button' in that specification.
MouseEvent.ctrlKey - Web APIs
html <p>click anywhere to test the <code>ctrlkey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the ctrl key is pressed: ${e.ctrlkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.ctr...
MouseEvent.metaKey - Web APIs
html <p>click anywhere to test the <code>metakey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the meta key is pressed: ${e.metakey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.met...
MouseEvent.shiftKey - Web APIs
html <p>click anywhere to test the <code>shiftkey</code> property.</p> <p id="log"></p> javascript let log = document.queryselector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the shift key is pressed: ${e.shiftkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.
msRealTime - Web APIs
you must set the msrealtime before setting the src property in code.
MutationObserver.MutationObserver() - Web APIs
creating and starting the observer this code actually sets up the observation process.
MutationObserver.takeRecords() - Web APIs
*/ /* 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.
MutationObserver - Web APIs
mutation observer & customize resize event listener & demo https://codepen.io/webgeeker/full/yjrzgg/ example the following example was adapted from this blog post.
MutationObserverInit.attributeFilter - Web APIs
this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline.
MutationObserverInit.attributeOldValue - Web APIs
this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline.
MutationObserverInit.attributes - Web APIs
this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline.
NDEFRecord.encoding - Web APIs
the encoding property ofthe ndefrecord interface is usvstring containing the name of the encoding used to encode ndef payload if it contains textual data.
NDEFRecord - Web APIs
ndefrecord.lang read only represents a language tag of the content, if it was encoded.
Navigator.getBattery() - Web APIs
this implements the battery status api; see that documentation for additional details, a guide to using the api, and sample code.
Navigator.getUserMedia() - Web APIs
errors examples width and height here's an example of using getusermedia(), including code to cope with various browsers' prefixes.
Navigator.mediaSession - Web APIs
note that the code begins by ensuring that the navigator.mediasession property is available before attempting to use it.
Navigator.oscpu - Web APIs
WebAPINavigatoroscpu
x.y mac os x (i386/x64 build) intel mac os x or macos version x.y linux 64-bit (32-bit build) output of uname -s plus "i686 on x86_64" linux output of uname -sm x.y refers to the version of the operating system example function osinfo() { alert(window.navigator.oscpu); } osinfo(); // alerts "windows nt 6.0" for example usage notes unless your code is privileged (chrome or at least has the universalbrowserread privilege), it may get the value of the general.oscpu.override preference instead of the true platform.
Navigator.registerProtocolHandler() - Web APIs
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.
Navigator.requestMediaKeySystemAccess() - Web APIs
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).
Navigator.serviceWorker - Web APIs
syntax var workercontainerinstance = navigator.serviceworker; value serviceworkercontainer examples this code checks if the browser supports service workers.
Navigator.share() - Web APIs
WebAPINavigatorshare
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.
NavigatorID.appVersion - Web APIs
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.
NetworkInformation.onchange - Web APIs
the networkinformation.onchange event handler contains the code that is fired when connection information changes, and the change is received by the networkinformation object.
Node.baseURIObject - Web APIs
in addition, this property may only be accessed from privileged code.
Node.getRootNode() - Web APIs
WebAPINodegetRootNode
(see the full source code): <!-- source: https://github.com/jserz/js_piece/blob/master/dom/node/getrootnode()/demo/getrootnode.html --> <div class="js-parent"> <div class="js-child"></div> </div> <div class="js-shadowhost"></div> <script> // works on chrome 54+,opera 41+ var parent = document.queryselector('.js-parent'), child = document.queryselector('.js-child'), shadowhost = document.queryselector...
Node.isConnected - Web APIs
WebAPINodeisConnected
block; border: 1px solid black; padding: 10px; background: white; border-radius: 10px; opacity: 0; transition: 0.6s all; positions: absolute; bottom: 20px; left: 10px; z-index: 3 } `; // attach the created style element to the shadow dom shadow.appendchild(style); console.log(style.isconnected); // returns true polyfill node.isconnected can be polyfilled with the following code for ie10 and edgehtml: /* * node.isconnected polyfill for ie and edgehtml * 2020-02-04 * * by eli grey, https://eligrey.com * public domain.
Node.nodePrincipal - Web APIs
in addition, this property may only be accessed from privileged code.
Node.nodeType - Web APIs
WebAPINodenodeType
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.
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
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
WebAPINotificationlang
see the sitepoint iso 2 letter language codes page for a simple reference.
NotifyAudioAvailableEvent - Web APIs
encoded audio).
OES_fbo_render_mipmap - Web APIs
examples see the sample code in the khronos specification.
OES_standard_derivatives - Web APIs
glsl built-in functions the following new functions can be used in glsl shader code, if this extension is enabled: gentype dfdx(gentype) gentype dfdy(gentype) gentype fwidth(gentype) examples enabling the extensions: gl.getextension('oes_standard_derivatives'); 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_st...
OVR_multiview2 - Web APIs
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
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.
OrientationSensor.populateMatrix() - Web APIs
where: w = cos(θ/2) x = vx * sin(θ/2) y = vy * sin(θ/2) z = vz * sin(θ/2) if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
OrientationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
OscillatorNode.detune - Web APIs
for applied examples/information, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.frequency - Web APIs
for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.onended - Web APIs
for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.start() - Web APIs
for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.stop() - Web APIs
for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.type - Web APIs
for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode - Web APIs
for an applied example, check out our violent theremin demo (see app.js for relevant code).
PannerNode.coneInnerAngle - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which ...
PannerNode.coneOuterAngle - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which ...
PannerNode.coneOuterGain - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which ...
PannerNode.distanceModel - Web APIs
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!
PannerNode.maxDistance - Web APIs
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!
PannerNode.orientationX - Web APIs
they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which ...
PannerNode.panningModel - Web APIs
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!
PannerNode.positionX - Web APIs
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.
PannerNode.positionY - Web APIs
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.
PannerNode.positionZ - Web APIs
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.
PannerNode.refDistance - Web APIs
me + note_length); }; // this tone should decay immediately and fairly quickly scheduletesttone(1, context.currenttime); // this tone should decay slower and later than the previous one scheduletesttone(4, context.currenttime + note_length); // this tone should decay only slightly, and only start decaying fairly late scheduletesttone(7, context.currenttime + note_length * 2); after running this code, the resulting waveforms should look something like this: specifications specification status comment web audio apithe definition of 'refdistance' in that specification.
PannerNode.rolloffFactor - Web APIs
t.destination); osc.start(starttime); osc.stop(starttime + note_length); }; // this tone should decay fairly quickly scheduletesttone(1, context.currenttime); // this tone should decay slower than the previous one scheduletesttone(0.5, context.currenttime + note_length); // this tone should decay only slightly scheduletesttone(0.1, context.currenttime + note_length * 2); after running this code, the resulting waveforms should look something like this: specifications specification status comment web audio apithe definition of 'rollofffactor' in that specification.
PannerNode.setOrientation() - Web APIs
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!
PannerNode.setPosition() - Web APIs
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!
PannerNode.setVelocity() - Web APIs
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!
PannerNode - Web APIs
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!
ParentNode.append() - Web APIs
WebAPIParentNodeappend
let parent = document.createelement("div") with(parent) { append("foo") } // referenceerror: append is not defined polyfill you can polyfill the append() method in internet explorer 9 and higher with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { return; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argarr = array.prototype.slice.c...
ParentNode.lastElementChild - Web APIs
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.
ParentNode.replaceChildren() - Web APIs
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.
PasswordCredential.passwordName - Web APIs
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.
PaymentAddress.country - Web APIs
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.
PaymentRequest.onmerchantvalidation - Web APIs
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.
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...
PaymentValidationErrors - Web APIs
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.
Payment processing concepts - Web APIs
payment handler the implementation of the code needed to interface with a particular payment method provider in order to process payments.
PerformanceObserver.observe() - Web APIs
unrecognized types are ignored, though the browser may output a warning message to the console to help developers debug their code.
PerformancePaintTiming - Web APIs
ow.performance) { let performance = window.performance; let performanceentries = performance.getentriesbytype('paint'); performanceentries.foreach( (performanceentry, i, entries) => { console.log("the time to " + performanceentry.name + " was " + performanceentry.starttime + " milliseconds."); }); } else { console.log('performance timing isn\'t supported.'); } } the code above produces console output something like the following: the time to first-paint was 2785.915 milliseconds.
PerformanceResourceTiming.transferSize - Web APIs
if ("decodedbodysize" in perfentry) console.log("decodedbodysize = " + perfentry.decodedbodysize); else console.log("decodedbodysize = not supported"); if ("encodedbodysize" in perfentry) console.log("encodedbodysize = " + perfentry.encodedbodysize); else console.log("encodedbodysize = not supported"); if ("transfersize" in perfentry) console.log("transfersize = " + perfentry.tr...
Using the Performance API - Web APIs
the following code example shows the use of domhighrestimestamp and the performance.now() method.
Performance API - Web APIs
resource timing level 2 working draft adds the nexthopprotocol, workerstart, transfersize, encodedbodysize, and decodedbodysize properties to the performanceresourcetiming interface.
Permissions API - Web APIs
you can run the example live, or view the source code on github.
PointerEvent.pointerId - Web APIs
example the following code snippet compares a previously saved pointerid with the one of the pointerdown event that was just fired.
PointerEvent - Web APIs
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).
Pointer Lock API - Web APIs
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).
Pinch zoom gestures - Web APIs
the source code is available on github; pull requests and bug reports are welcome.
PopStateEvent - Web APIs
the popstate event as an example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1...
PromiseRejectionEvent() - Web APIs
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.
PromiseRejectionEvent.reason - Web APIs
this could be anything from an error code to an object with text, links, and whatever else you might wish to include.
PromiseRejectionEvent - Web APIs
events rejectionhandled fired when a javascript promise is rejected, and after the rejection is handled by the promise's rejection handling code.
PublicKeyCredential.rawId - Web APIs
the publickeycredential.id property is a base64url encoded version of this identifier.
PublicKeyCredentialCreationOptions.user - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { // to be changed for each user id: new uint8array.from(window.atob("laegmlkjnrlkgnamlafalfka="), c=>c.charcodeat(0)); name: "jdoe@example.com", displayname: "john doe", icon: "https://gravatar.com/avatar/jdoe.png" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration ...
PushManager.getSubscription() - Web APIs
example this code snippet is taken from a push messaging and notification sample.
PushManager.subscribe() - Web APIs
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.
RTCDTMFSender.insertDTMF() - Web APIs
syntax rtcdtmfsender.insertdtmf(tones[, duration[, intertonegap]]); parameters tones a domstring containing the dtmf codes to be transmitted to the recipient.
RTCDataChannel.binaryType - Web APIs
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.
RTCDataChannel.bufferedAmount - Web APIs
this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them.
RTCDataChannel: close event - Web APIs
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).
RTCDataChannel.negotiated - Web APIs
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.
RTCDataChannel.onmessage - Web APIs
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.
RTCDataChannel.reliable - Web APIs
use rtcdatachannel.ordered instead in any new code, and update existing code as soon as possible.
RTCDataChannel.stream - Web APIs
if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream.
RTCDataChannelEvent.channel - Web APIs
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.
RTCDtlsTransport.state - Web APIs
"connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; case "failed": results.failed++; break; default: results.unknown++; break; } } }); return results; } note that in this code, the new and connecting states are being treated as a single connectionpending status in the returned object.
RTCErrorEvent - Web APIs
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).
RTCIceCandidate.address - Web APIs
example this code snippet uses the value of address to implement an ip address based ban feature.
RTCIceCandidate.component - Web APIs
example this code snippet examines a candidate's component type and dispatches the candidate to different handlers depending on the value.
RTCIceCandidate.foundation - Web APIs
example this code snippet uses the foundation of two candidates to determine if they're actually the same candidate.
RTCIceCandidate.port - Web APIs
example this code snippet fetches the ip address and port number of the candidate, storing them into an object for future use.
RTCIceCandidate.protocol - Web APIs
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.
RTCIceCandidate.usernameFragment - Web APIs
to avoid including candidates obsoleted by an ice restart, we can use code like this: const ssnewcandidate = signalmsg => { let candidate = new rtcicecandidate(signalmsg.candidate); let receivers = pc.getreceivers(); receivers.foreach(receiver => { let parameters = receiver.transport.getparameters(); if (parameters.usernamefragment === candidate.usernamefragment) { return; } }); pc.addicecandidate(candidate) .catch(reporterror); } t...
RTCIceCandidateInit.candidate - Web APIs
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.
RTCIceCandidateStats.mozLocalTransport - Web APIs
syntax instead of using mozlocaltransport, you should use code like this: localtransport = rtcicecandidatestats.relayprotocol; specifications not part of any specification.
RTCIceCandidateStats - Web APIs
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.
RTCIceServer - Web APIs
because many older books and examples still use this, we include it to help developers update their code or make sense of older examples.
RTCIceTransport.getLocalCandidates() - Web APIs
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.
RTCIceTransport.getRemoteCandidates() - Web APIs
each time your signaling code calls rtcpeerconnection.addicecandidate() to add a received candidate to the ice session, the ice agent places it in the list returned by this function.
RTCIceTransport.state - Web APIs
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.
RTCIceTransportState - Web APIs
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.
RTCIdentityEvent.assertion - Web APIs
the read-only property rtcidentityevent.assertion returns the domstring containing a blob being the coded assertion associated with the event.
RTCInboundRtpStreamStats.firCount - Web APIs
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.
RTCOfferAnswerOptions - Web APIs
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.
RTCOutboundRtpStreamStats.firCount - Web APIs
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.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
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.
RTCPeerConnection: datachannel event - Web APIs
this same code can also instead use the rtcpeerconnection interface's ondatachannel event handler property, like this: pc.ondatachannel = ev => { receivechannel = ev.channel; receivechannel.onmessage = myhandlemessage; receivechannel.onopen = myhandleopen; receivechannel.onclose = myhandleclose; } specifications specification status comment webrtc 1.0: real-time communication...
RTCPeerConnection.getStats() - Web APIs
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.
RTCPeerConnection.getTransceivers() - Web APIs
example the following snippet of code stops all transceivers associated with an rtcpeerconnection.
RTCPeerConnection: negotiationneeded event - Web APIs
this starts the process of ice negotiation by instructing your code to begin exchanging ice candidates through the signaling server.
RTCPeerConnection.onicecandidate - Web APIs
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.
RTCPeerConnection.oniceconnectionstatechange - Web APIs
your code can look at the value of rtcpeerconnection.iceconnectionstate to determine what the new state is.
RTCPeerConnection.onidentityresult - Web APIs
the rtcpeerconnection.onidentityresult event handler is a property containing the code to execute when the identityresult event, of type rtcidentityevent, is received by this rtcpeerconnection.
RTCPeerConnection.onidpassertionerror - Web APIs
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.
RTCPeerConnection.onidpvalidationerror - Web APIs
the rtcpeerconnection.onidpvalidationerror event handler is a property containing the code to execute whent the idpvalidationerror event, of type rtcidentityerrorevent, is received by this rtcpeerconnection.
RTCPeerConnection.onpeeridentity - Web APIs
the rtcpeerconnection.onpeeridentity event handler is a property containing the code to execute whent the peeridentity event, of type event, is received by this rtcpeerconnection.
RTCPeerConnection.onremovestream - Web APIs
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.
RTCPeerConnection.remoteDescription - Web APIs
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.
RTCPeerConnection.restartIce() - Web APIs
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.
RTCPeerConnection.setConfiguration() - Web APIs
var restartconfig = { iceservers: [{ urls: "turn:asia.myturnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeerconnection.createoffer({"icerestart": true}).then(function(offer) { return mypeerconnection.setlocaldescription(offer); }) .then(function() { // send the offer to the other peer using the signaling server }) .catch(reporterror); first, a new rt...
RTCPeerConnection: signalingstatechange event - Web APIs
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.
RTCPeerConnection: track event - Web APIs
examples this example shows code that creates a new rtcpeerconnection, then adds a new track event handler.
RTCRtpEncodingParameters.scaleResolutionDownBy - Web APIs
the default value, 1.0, means that the video will be encoded at its original size.
RTCRtpParameters - Web APIs
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.
RTCRtpReceiver - Web APIs
rtcrtpreceiver.getparameters() returns an rtcrtpparameters object which contains information about how the rtc data is to be decoded.
RTCRtpSendParameters - Web APIs
encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media.
RTCRtpStreamStats.firCount - Web APIs
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.
RTCRtpStreamStats.kind - Web APIs
it will also match the statistics object's rtccodecstats.codec property's media type.
RTCRtpStreamStats.sliCount - Web APIs
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 the received media.
RTCRtpTransceiver.sender - Web APIs
syntax var rtpsender = rtcrtptransceiver.sender; value an rtcrtpsender object used to encode and send media whose media id matches the current value of mid.
RTCRtpTransceiver - Web APIs
methods setcodecpreferences() a list of rtcrtpcodecparameters objects which override the default preferences used by the user agent for the transceiver's codecs.
RTCStatsReport - Web APIs
codec an rtccodecstats object containing statistics about a codec currently being used by rtp streams to send or receive data for the rtcpeerconnection.
RTCStatsType - Web APIs
codec an rtccodecstats object containing statistics about a codec currently being used by rtp streams to send or receive data for the rtcpeerconnection.
Range.compareBoundaryPoints() - Web APIs
if the value of the parameter is invalid, a domexception with a notsupportederror code is thrown.
Range - Web APIs
WebAPIRange
range.createcontextualfragment() returns a documentfragment created from a given string of code.
ReadableStream.ReadableStream() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStream.getReader() - Web APIs
(see our simple random stream example for the full code).
ReadableStream.tee() - Web APIs
see simple tee example for the full code.
ReadableStreamBYOBReader - Web APIs
properties readablestreambyobreader.closed read only allows you to write code that responds to an end to the streaming process.
ReadableStreamDefaultController.close() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStreamDefaultController.enqueue() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStreamDefaultController - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
(see our simple random stream example for the full code).
ReadableStreamDefaultReader.cancel() - Web APIs
(this code is based on our simple random stream example).
ReadableStreamDefaultReader - Web APIs
properties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process.
RelativeOrientationSensor.RelativeOrientationSensor() - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
RelativeOrientationSensor - Web APIs
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
ReportingObserver - Web APIs
note: if you look at the complete source code, you'll notice that we actually call the deprecated getusermedia() method twice.
Request.destination - Web APIs
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.
Response.redirect() - Web APIs
WebAPIResponseredirect
status optional an optional status code for the response (e.g., 302.) return value a response object.
Response.redirected - Web APIs
in the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation.
Response.status - Web APIs
WebAPIResponsestatus
the status read-only property of the response interface contains the status code of the response (e.g., 200 for a success).
Response.statusText - Web APIs
the statustext read-only property of the response interface contains the status message corresponding to the status code (e.g., ok for 200).
SVGAElement.target - Web APIs
sample values can be found here example the code is taken from the "svgaelement example code" ...
SVGMatrix - Web APIs
WebAPISVGMatrix
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.
SVGNumber - Web APIs
WebAPISVGNumber
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.
SVGPreserveAspectRatio - Web APIs
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.
SVGScriptElement - Web APIs
a domexception is raised with the code no_modification_allowed_err on an attempt to change the value of a read only attribut.
Screen - Web APIs
WebAPIScreen
additional methods in mozilla chrome codebase mozilla includes a couple of extensions for use by js-implemented event targets to implement onevent properties.
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
statuscode: the statuscode of the securitypolicyviolationevent (required).
SecurityPolicyViolationEvent - Web APIs
securitypolicyviolationevent.statuscoderead only a number representing the http status code of the document or worker in which the violation occurred.
Selection - Web APIs
WebAPISelection
in cross-browser compatible code, it's better to handle them separately.
Selection API - Web APIs
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.
Sensor - Web APIs
WebAPISensor
if a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server.
Server-sent events - Web APIs
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.
ServiceWorkerContainer.ready - Web APIs
the ready read-only property of the serviceworkercontainer interface provides a way of delaying code execution until a service worker is active.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
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.
ServiceWorkerMessageEvent.data - Web APIs
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.
ServiceWorkerMessageEvent.lastEventId - Web APIs
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.
ServiceWorkerMessageEvent.origin - Web APIs
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.
ServiceWorkerMessageEvent.ports - Web APIs
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.
ServiceWorkerMessageEvent.source - Web APIs
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.
ServiceWorkerMessageEvent - Web APIs
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.
ServiceWorkerRegistration - Web APIs
examples in this example, the code first checks whether the browser supports service workers and if so registers one.
SharedWorker() - Web APIs
examples the following code snippet shows creation of a sharedworker object using the sharedworker() constructor and subsequent usage of the object: var myworker = new sharedworker('worker.js'); myworker.port.start(); first.onchange = function() { myworker.port.postmessage([first.value,second.value]); console.log('message posted to worker'); } second.onchange = function() { myworker.port.postmessage([first.value,s...
SharedWorker.port - Web APIs
WebAPISharedWorkerport
example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
SharedWorker - Web APIs
the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
SharedWorkerGlobalScope.onconnect - Web APIs
the onconnect property of the sharedworkerglobalscope interface is an event handler 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.
SourceBuffer.abort() - Web APIs
for example, consider this code: sourcebuffer.addeventlistener('updateend', function (_) { ...
SourceBuffer.appendWindowEnd - Web APIs
coded media frames with timestamps wthin this range will be appended, whereas those outside the range will be filtered out.
SourceBuffer.appendWindowStart - Web APIs
coded media frames with timestamps wthin this range will be appended, whereas those outside the range will be filtered out.
SpeechGrammarList.addFromString() - Web APIs
the addfromstring() method of the speechgrammarlist interface takes a grammar present in a specific domstring within the code base (e.g.
SpeechGrammarList - Web APIs
speechgrammarlist.addfromstring() takes a grammar present in a specific domstring within the code base (e.g.
SpeechRecognition() - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.continuous - Web APIs
true means continuous, and false means not continuous (single result each time.) examples this code is excerpted from our speech color changer example.
SpeechRecognition.grammars - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.interimResults - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.lang - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.maxAlternatives - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.onresult - Web APIs
}; examples this code is excerpted from our speech color changer example.
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.
SpeechRecognitionAlternative.confidence - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionAlternative.transcript - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionAlternative - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionEvent.results - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionEvent - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResult.item() - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResult.length - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResult - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResultList.item() - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResultList.length - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResultList - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechSynthesisErrorEvent - Web APIs
speechsynthesiserrorevent.error read only returns an error code indicating what has gone wrong with a speech synthesis attempt.
StereoPannerNode.pan - Web APIs
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.
StereoPannerNode - Web APIs
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.
Storage API - Web APIs
the storage api gives sites' code the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the user agent disposes of site data in order to make room for other things.
Streams API - Web APIs
simple writer: this example shows how to to write to a writable stream, then decode the stream and write the contents to the ui.
StylePropertyMapReadOnly.forEach() - Web APIs
syntax stylepropertymapreadonly.foreach(function callback(currentvalue[, index[, array]]) { //your code }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
SubmitEvent() - Web APIs
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.
Text.wholeText - Web APIs
WebAPITextwholeText
syntax str = textnode.wholetext; notes and example suppose you have the following simple paragraph within your webpage (with some whitespace added to aid formatting throughout the code samples here), whose dom node is stored in the variable para: <p>thru-hiking is great!
TextMetrics.width - Web APIs
WebAPITextMetricswidth
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
WebAPITextTrack
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.
Touch.pageX - Web APIs
WebAPITouchpageX
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.
Touch.pageY - Web APIs
WebAPITouchpageY
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.
Touch.radiusX - Web APIs
WebAPITouchradiusX
the following simple code snippet, registers a single handler for the touchstart, touchmove and touchend events.
Touch.screenX - Web APIs
WebAPITouchscreenX
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.
Touch.target - Web APIs
WebAPITouchtarget
in following simple code snippet, we assume the user initiates one or more touch contacts on the source element.
TouchEvent.altKey - Web APIs
WebAPITouchEventaltKey
in following code snippet, the touchstart event handler logs the state of the event's modifier keys.
TouchEvent.changedTouches - Web APIs
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.
TouchEvent.targetTouches - Web APIs
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.
TouchEvent.touches - Web APIs
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.
TouchEvent - Web APIs
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).
TouchList.item() - Web APIs
WebAPITouchListitem
example this code example illustrates the use of the touchlist interface's item method and the length property.
TouchList.length - Web APIs
WebAPITouchListlength
example this code example illustrates the use of the touchlist interface's item method and the length property.
Supporting both TouchEvent and MouseEvent - Web APIs
here is a code snippet of the touchmove event handler calling preventdefault().
Touch events - Web APIs
convenience functions this example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.
TrackDefault.TrackDefault() - Web APIs
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.
TrackDefault.language - Web APIs
this should be a valid language code, e.g.
UIEvent.pageX - Web APIs
WebAPIUIEventpageX
do not look for pagex on any non-mouse events in new code and update existing code as soon as possible.
UIEvent - Web APIs
WebAPIUIEvent
uievent.which read only returns the numeric keycode of the key pressed, or the character code (charcode) for an alphanumeric key pressed.
URL.createObjectURL() - Web APIs
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.
URL.hash - Web APIs
WebAPIURLhash
the fragment is not percent-decoded.
URL.origin - Web APIs
WebAPIURLorigin
the origin read-only property of the url interface returns a usvstring containing the unicode serialization of the origin of the represented url.
URL.searchParams - Web APIs
WebAPIURLsearchParams
the searchparams readonly property of the url interface returns a urlsearchparams object allowing access to the get decoded query arguments contained in the url.
URLSearchParams() - Web APIs
syntax var urlsearchparams = new urlsearchparams(init); parameters init optional one of: a usvstring, which will be parsed from application/x-www-form-urlencoded format.
URLSearchParams.set() - Web APIs
you can copy and paste the example in a code environment like codepen, jsfiddle, or the multi-line javascript interpreter in firefox.
URLSearchParams.sort() - Web APIs
the sort order is according to unicode code points of the keys.
URLSearchParams - Web APIs
var paramsstring1 = "http://example.com/search?query=%40"; var searchparams1 = new urlsearchparams(paramsstring1); searchparams1.has("query"); // false searchparams1.has("http://example.com/search?query"); // true searchparams1.get("query"); // null searchparams1.get("http://example.com/search?query"); // "@" (equivalent to decodeuricomponent('%40')) var paramsstring2 = "?query=value"; var searchparams2 = new urlsearchparams(paramsstring2); searchparams2.has("query"); // true var url = new url("http://example.com/search?query=%40"); var searchparams3 = new urlsearchparams(url.search); searchparams3.has("query") // true specifications specification status comment urlthe definition of 'urlsea...
URLUtilsReadOnly.origin - Web APIs
the urlutilsreadonly.origin read-only property is a domstring containing the unicode serialization of the origin of the represented url, that is, for http and https, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified).
USB.requestDevice() - Web APIs
WebAPIUSBrequestDevice
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.
USBDevice - Web APIs
WebAPIUSBDevice
usbdevice.productid read only the manufacturer-defined code that identifies a usb device.
USBEndpoint - Web APIs
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.
Using the User Timing API - Web APIs
a live version of the examples is available on github, as is the source code.
User Timing API - Web APIs
for more details and example code regarding these two performance event types and the methods, see using the user timing api.
ValidityState.patternMismatch - Web APIs
examples given the following: <p> <label>enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"/> </label> </p> here we have 3 sections for a north american phone number with an implicit label encompassing all three components of the phone number, expecting 3-...
validityState.tooLong - Web APIs
the read-only toolong property of a validitystate object indicates if the value of an <input> or <textarea>, after having been edited by the user, exceeds the maximum code-unit length established by the element's maxlength attribute.
validityState.tooShort - Web APIs
the read-only tooshort property of a validitystate object indicates if the value of an <input>, <button>, <select>, <output>, <fieldset> or <textarea>, after having been edited by the user, is less than the minimum code-unit length established by the element's minlength attribute.
Vibration API - Web APIs
most modern mobile devices include vibration hardware, which lets software code provide physical feedback to the user by causing the device to shake.
VideoTrack - Web APIs
the language is specified as a bcp 47 (rfc 5646) language code, such as "en-us" or "pt-br".
VisualViewport - Web APIs
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.
Visual Viewport API - Web APIs
example the code below is based on the sample the specification, though it adds a few things that make it function better.
WEBGL_draw_buffers.drawBuffersWEBGL() - Web APIs
examples see webgl_draw_buffers for more context with this example code.
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...
WebGLProgram - Web APIs
this is shown in the code below.
WebGLRenderingContext.attachShader() - Web APIs
examples the following code attaches pre-existing shaders to a webglprogram.
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
examples the following code gets the precision format of a gl.vertex_shader with a gl.medium_float precision type.
WebGLRenderingContext.linkProgram() - Web APIs
the webglrenderingcontext interface's linkprogram() method links a given webglprogram, completing the process of preparing the gpu code for the program's fragment and vertex shaders.
Basic scissoring - Web APIs
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.
Canvas size and WebGL - Web APIs
" + "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.
Clearing by clicking - Web APIs
function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
Clearing with colors - Web APIs
gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github.
Color masking - Web APIs
on"; else evt.target.innerhtml="off"; gl.colormask(mask[0], mask[1], mask[2], true); drawanimation(); }; function drawanimation () { var color = getrandomcolor(); gl.clearcolor(color[0], color[1], color[2], 1.0); gl.clear(gl.color_buffer_bit); } function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
Detect WebGL - Web APIs
" + "your browser or device may not support webgl."; } } }, false); the source code of this example is also available on github.
Hello vertex attributes - Web APIs
experimental-webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Scissor animation - Web APIs
experimental-webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Simple color animation - Web APIs
function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
WebGL: 2D and 3D graphics for the web - Web APIs
WebAPIWebGL API
guides data in webgl a guide to variables, buffers, and other types of data used when writing webgl code.
WebRTC coding guide - Web APIs
this coding guide will explain in depth how webrtc works, and will dive into actual code that uses webrtc to do useful things.
Introduction to WebRTC protocols - Web APIs
sdp session description protocol (sdp) is a standard for describing the multimedia content of the connection such as resolution, formats, codecs, encryption, etc.
WebSocket - Web APIs
WebAPIWebSocket
methods websocket.close([code[, reason]]) closes the connection.
The WebSocket API (WebSockets) - Web APIs
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.
Tools for analyzing Web Audio usage - Web APIs
while working on your web audio api code, you may find that you need tools to analyze the graph of nodes you create or to otherwise debug your work.
Window: animationcancel event - Web APIs
examples this code adds a listener to the animationcancel event.
Window: animationiteration event - Web APIs
examples this code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationcount = 0; window.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: let iterationcount = 0; window.onanimationiteration = () => { it...
Window.clearImmediate() - Web APIs
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.
window.dump() - Web APIs
WebAPIWindowdump
privileged code can also use components.utils.reporterror and nsiconsoleservice to log messages to the error console/browser console.
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
defaultview in many code samples, getcomputedstyle is used from the document.defaultview object.
Window: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples suppose a script sends a message to a different browsing context, 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('...
Window.onmozbeforepaint - Web APIs
this is used in concert with the window.mozrequestanimationframe() method to perform smooth, synchronized animations from javascript code.
Window.pageYOffset - Web APIs
<div id="info"> </div> javascript var frame = document.getelementbyid("frame"); var framedoc = frame.contentdocument; var info = document.getelementbyid("info"); var target = framedoc.getelementbyid("overview"); framedoc.scrollingelement.scrolltop = target.offsettop; info.innertext = "y offset after scrolling: " + frame.contentwindow.pageyoffset + " pixels"; the javascript code begins by getting into frame and info the <iframe> element that contains our content as well as the <div> element into which we'll output the result of our scroll position check.
Window: popstate event - Web APIs
examples a page at http://example.com/example.html running the following code will generate logs as indicated: window.addeventlistener('popstate', (event) => { console.log("location: " + document.location + ", state: " + json.stringify(event.state)); }); history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // logs "location: http://example.com/exampl...
Window: resize event - Web APIs
<p>resize the browser window to fire the <code>resize</code> event.</p> <p>window height: <span id="height"></span></p> <p>window width: <span id="width"></span></p> const heightoutput = document.queryselector('#height'); const widthoutput = document.queryselector('#width'); function reportwindowsize() { heightoutput.textcontent = window.innerheight; widthoutput.textcontent = window.innerwidth; } window.onresize = reportwindowsize; ...
Window.screenLeft - Web APIs
WebAPIWindowscreenLeft
, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); 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); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenTop - Web APIs
WebAPIWindowscreenTop
, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); 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); also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using window.screenx/window.screeny.
Window.screenY - Web APIs
WebAPIWindowscreenY
also in the code we include a snippet that detects whether screenleft is supported, and if not, polyfills in screenleft/screentop using screenx/screeny.
Window: transitioncancel event - Web APIs
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.
Window: transitionend event - Web APIs
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.
Window: transitionrun event - Web APIs
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.
Window: transitionstart event - Web APIs
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.
Window.window - Web APIs
WebAPIWindowwindow
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".
WindowEventHandlers.onhashchange - Web APIs
polyfill for event.newurl and event.oldurl // let this snippet run before your hashchange event binding code if (!window.hashchangeevent)(function(){ var lasturl = document.url; window.addeventlistener("hashchange", function(event){ object.defineproperty(event, "oldurl", {enumerable:true,configurable:true,value:lasturl}); object.defineproperty(event, "newurl", {enumerable:true,configurable:true,value:document.url}); lasturl = document.url; }); }()); specifications specifica...
WindowEventHandlers.onpopstate - Web APIs
examples for example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1...
self.createImageBitmap() - Web APIs
colorspaceconversion: specifies whether the image should be decoded using color space conversion.
WindowOrWorkerGlobalScope.indexedDB - Web APIs
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.
Worker() - Web APIs
WebAPIWorkerWorker
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).
Worker: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and listens to messages from it using addeventlistener(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); alternatively, it could listen using the onmessage event handler property: const worker = new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`received message fro...
Worker.onmessage - Web APIs
WebAPIWorkeronmessage
} example the following code snippet shows creation of a worker object using the worker() constructor.
Worker.terminate() - Web APIs
WebAPIWorkerterminate
example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated.
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
}; 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
}; 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.
WorkerGlobalScope.onlanguagechange - Web APIs
}; 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.
WorkerGlobalScope.onoffline - Web APIs
}; 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.
WorkerGlobalScope.ononline - Web APIs
}; 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.
WorkerGlobalScope.performance - Web APIs
which would basically be the equivalent of self.console.log(self.performance);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerperformance object written to the console — something like the following: workerperformance {now: function} __proto__: workerperformance constructor: function workerperformance() { [native code] } now: function now() { [native code] } __proto__: object you could use this performance object to return performance data, as you might do with a normal performance object.
WorkerNavigator - Web APIs
inherited properties navigatorid.appcodename read only always returns 'mozilla', in any browser.
WritableStreamDefaultWriter.ready - Web APIs
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.
XDomainRequest.onprogress - Web APIs
this method is called periodically as an event handler for progress events on xdomainrequests, so that code can monitor progress while loading content.
Using XMLHttpRequest in IE6 - Web APIs
in all modern browsers, you can create a new xmlhttprequest object using the following code: var request = new xmlhttprequest() however, if you need to also support internet explorer 6 and older, you need to extend your code like this: if (window.xmlhttprequest) { //firefox, opera, ie7, and other browsers will use the native object var request = new xmlhttprequest(); } else { //ie 5 and 6 will use the activex control var request = new activexobject("microsoft.xmlhttp"); } see also using xmlhttprequest ...
init() - Web APIs
initializes the object for use from c++ code.
XMLHttpRequest.abort() - Web APIs
when a request is aborted, its readystate is changed to xmlhttprequest.unsent (0) and the request's status code is set to 0.
XMLHttpRequest.getAllResponseHeaders() - Web APIs
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.
XMLHttpRequest.onreadystatechange - Web APIs
warning: this should not be used with synchronous requests and must not be used from native code.
XMLHttpRequest.send() - Web APIs
}; 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.
XMLHttpRequest.status - Web APIs
the read-only xmlhttprequest.status property returns the numerical http status code of the xmlhttprequest's response.
XMLHttpRequest.statusText - Web APIs
unlike xmlhttprequest.status which indicates a numerical status code, this property contains the text of the response status, such as "ok" or "not found".
XMLSerializer - Web APIs
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().
XPathException - Web APIs
properties xpathexception.code read only returns a short that contains one of the error code constants.
XPathResult - Web APIs
xpathresult.resulttyperead only a number code representing the type of the result, as defined by the type constants.
XRInputSourceArray - Web APIs
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.
XRInputSourceEvent() - Web APIs
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.
XRInputSourceEvent.frame - Web APIs
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.
XRInputSourceEvent - Web APIs
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.
XRInputSourcesChangeEvent() - Web APIs
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.
XRRigidTransform.inverse - Web APIs
*/ } 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.
XRRigidTransform - Web APIs
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.
XRSession.cancelAnimationFrame() - Web APIs
example in the example below we see code which starts up a webxr session if immersive vr mode is supported.
XRSession.onsqueezestart - Web APIs
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.
XRSession.requestAnimationFrame() - Web APIs
} // assumed to be called by a user gesture event elsewhere in code.
XRSession: squeeze event - Web APIs
this code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity.
XRSystem: devicechange event - Web APIs
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.
XRView.eye - Web APIs
WebAPIXRVieweye
examples this code, from the viewer pose's renderer, iterates over the pose's views and renders them.
XRView.transform - Web APIs
WebAPIXRViewtransform
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.
XRView - Web APIs
WebAPIXRView
return refspace.getoffsetreferencespace(newtransform); } this code is broken into four sections.
XRWebGLLayer.ignoreDepthValues - Web APIs
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.
XSL Transformations in Mozilla FAQ - Web APIs
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.
msGetRegionContent - Web APIs
if an element is not a region, this method throws a domexception with the invalidaccesserror error code.
msPutPropertyEnabled - Web APIs
otherwise, it returns an hresult error code.
msWriteProfilerMark - Web APIs
otherwise, it returns an hresult error code.
ARIA Technique Template - Accessibility
examples example 1: code working examples: notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
Using the alertdialog role - Accessibility
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.
Using the aria-activedescendant attribute - Accessibility
examples example 1: code working examples: notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
Using the log role - Accessibility
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.
Using the status role - Accessibility
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.
Using the toolbar role - Accessibility
examples example 1: code working examples: w3c toolbar example notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
ARIA Test Cases - Accessibility
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.
ARIA annotations - Accessibility
below we'll introduce the new features associated with aria annotations, and have a look at some code examples that show them in action.
ARIA: feed role - Accessibility
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.
ARIA: gridcell role - Accessibility
this sample code demonstrates a table-style grouping of information where the third and fourth columns have been removed.
ARIA: Main role - Accessibility
<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.
ARIA: switch role - Accessibility
<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.
ARIA: dialog role - Accessibility
this approach is shown in the code snippet below: <div role="dialog" aria-labelledby="dialog1title" aria-describedby="dialog1desc"> <h2 id="dialog1title">your personal details were successfully updated</h2> <p id="dialog1desc">you can change your details at any time in the user account section.</p> <button>close</button> </div> keep in mind that a dialog's title and description text do not have to be focusable in order to ...
ARIA: heading role - Accessibility
the heading role and aria-level attribute should only be used to retrofit accessibility on legacy code that you cannot make major changes to.
ARIA: listbox role - Accessibility
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.
Alerts - Accessibility
below is example javascript code which could be inserted above the closing “head” tag: <script type="application/javascript"> function removeoldalert() { var oldalert = document.getelementbyid("alert"); if (oldalert){ document.body.removechild(oldalert); } } function addalert(amsg) { removeoldalert(); var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newal...
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
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.
Web accessibility for seizures and physical reactions - Accessibility
@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.
Color contrast - Accessibility
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.
-webkit-line-clamp - CSS: Cascading Style Sheets
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.
:-moz-window-inactive - CSS: Cascading Style Sheets
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.
::-webkit-progress-bar - CSS: Cascading Style Sheets
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
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
you can see this example in action or view or remix the code on glitch.
::first-letter (:first-letter) - CSS: Cascading Style Sheets
punctuation includes any unicode character defined in the open (ps), close (pe), initial quote (pi), final quote (pf), and other punctuation (po) classes.
::marker - CSS: Cascading Style Sheets
WebCSS::marker
::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.
:disabled - CSS: Cascading Style Sheets
WebCSS:disabled
html <form action="#"> <fieldset id="shipping"> <legend>shipping address</legend> <input type="text" placeholder="name"> <input type="text" placeholder="address"> <input type="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> <...
:fullscreen - CSS: Cascading Style Sheets
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.
:placeholder-shown - CSS: Cascading Style Sheets
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.
:read-only - CSS: Cascading Style Sheets
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.
:read-write - CSS: Cascading Style Sheets
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.
:state() - CSS: Cascading Style Sheets
WebCSS:state
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.
font-variation-settings - CSS: Cascading Style Sheets
if the <string> has more or fewer characters or contains characters outside the u+20 - u+7e codepoint range, the whole property is invalid.
light-level - CSS: Cascading Style Sheets
examples this code will likely not work on any devices (device compatibility is low).
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
WebCSS@supports
the rule may be placed at the top level of your code or nested inside any other conditional group at-rule.
Attribute selectors - CSS: Cascading Style Sheets
it is often used for language subcode matches.
Using multiple backgrounds - CSS: Cascading Style Sheets
: 400px; background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png), url(https://mdn.mozillademos.org/files/11307/bubbles.png), linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)); background-repeat: no-repeat, no-repeat, no-repeat; background-position: bottom right, left, right; } result (if image does not appear in codepen, click the 'tidy' button in the css section) as you can see here, the firefox logo (listed first within background-image) is on top, directly above the bubbles graphic, followed by the gradient (listed last) sitting underneath all previous 'images'.
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
you can take a look at the code of this example below.
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
the following code would set the flex-grow property to 2, flex-shrink to 1 and flex-basis to auto.
Ordering Flex Items - CSS: Cascading Style Sheets
in the live code example below i have items laid out using flexbox.
Introduction to formatting contexts - CSS: Cascading Style Sheets
if you do this, it would be a good idea to comment the code to explain.
CSS Fonts - CSS: Cascading Style Sheets
WebCSSCSS Fonts
font-size-adjust font-stretch font-style font-synthesis font-variant font-variant-alternates font-variant-caps font-variant-east-asian font-variant-ligatures font-variant-numeric font-variant-position font-variation-settings font-weight line-height at-rules @font-face font-family font-feature-settings font-style font-variant font-weight font-stretch src unicode-range @font-feature-values guides fundamental text and font styling in this beginner's learning article we go through all the basic fundamentals of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
Basic Concepts of grid layout - CSS: Cascading Style Sheets
have a play with the code examples, and then move onto the next part of this guide where we will really start to dig into the detail of css grid layout.
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
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.
Using z-index - CSS: Cascading Style Sheets
source code for the example html <div id="abs1"> <b>div #1</b> <br />position: absolute; <br />z-index: 5; </div> <div id="rel1"> <b>div #2</b> <br />position: relative; <br />z-index: 3; </div> <div id="rel2"> <b>div #3</b> <br />position: relative; <br />z-index: 2; </div> <div id="abs2"> <b>div #4</b> <br />position: absolute; <br />z-index: 1; </div> <div id="sta1"> <b>div...
Stacking with floated blocks - CSS: Cascading Style Sheets
source code for the example html <div id="abs1"> <b>div #1</b><br />position: absolute;</div> <div id="flo1"> <b>div #2</b><br />float: left;</div> <div id="flo2"> <b>div #3</b><br />float: right;</div> <br /> <div id="sta1"> <b>div #4</b><br />no positioning</div> <div id="abs2"> <b>div #5</b><br />position: absolute;</div> css div { padding: 10px; text-align: center; } b { font-f...
Stacking context example 2 - CSS: Cascading Style Sheets
example source code <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html> <head><style type="text/css"> div { font: 12px arial; } span.bold { font-weight: bold; } #div2 { z-index: 2; } #div3 { z-index: 1; } #div4 { z-index: 10; } #div1,#div3 { height: 80px; position: relative; border: 1px dashed #669966; background-color: #cc...
Stacking without the z-index property - CSS: Cascading Style Sheets
source code for the example html <div id="abs1" class="absolute"> <b>div #1</b><br />position: absolute;</div> <div id="rel1" class="relative"> <b>div #2</b><br />position: relative;</div> <div id="rel2" class="relative"> <b>div #3</b><br />position: relative;</div> <div id="abs2" class="absolute"> <b>div #4</b><br />position: absolute;</div> <div id="sta1" class="static"> <b>div #5</b><br />posi...
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
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.
Using CSS transitions - CSS: Cascading Style Sheets
before we look at code snippets, you might want to take a look at the live demo (assuming your browser supports transitions).
CSS Writing Modes - CSS: Cascading Style Sheets
reference properties direction glyph-orientation-horizontal text-combine-upright text-orientation unicode-bidi writing-mode specifications specification status comment css writing modes module level 3 proposed recommendation css level 2 (revision 1) recommendation css level 1 recommendation initial definition ...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
WebCSSCascade
some browsers use actual style sheets for this purpose, while others simulate them in code, but the end result is the same.
Comments - CSS: Cascading Style Sheets
WebCSSComments
a css comment is used to add explanatory notes to the code or to prevent the browser from interpreting specific parts of the style sheet.
Layout and the containing block - CSS: Cascading Style Sheets
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.
General sibling combinator - CSS: Cascading Style Sheets
/* 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.
Grid wrapper - CSS: Cascading Style Sheets
lternative methods when using this recipe at page level it can be useful to set a max-width along with left and right auto margins to center the content horizontally: .grid { max-width: 1200px; margin: 0 auto; // horizontally centers the container } /* remove the max-width and margins if the browser supports grid */ @supports (display: grid) { .grid { display: grid; /* other grid code goes here */ max-width: none; margin: 0; } } to “break out” a full-width item to the edge of the viewport you can then use this trick (courtesy of una kravets): .item { width: 100vw; margin-left: 50%; transform: translate3d(-50%, 0, 0); } this gives a good approximation of the layout, only without the benefit of being able to align items easily on an exact grid.
CSS Layout cookbook - CSS: Cascading Style Sheets
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.
Media queries - CSS: Cascading Style Sheets
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).
CSS reference - CSS: Cascading Style Sheets
WebCSSReference
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
playing with code really is the best way to get to grips with html and css.
Specificity - CSS: Cascading Style Sheets
<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.
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
consider the code snippet below.
WebKit CSS extensions - CSS: Cascading Style Sheets
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.
backface-visibility - CSS: Cascading Style Sheets
html <table> <tr> <th><code>backface-visibility: visible;</code></th> <th><code>backface-visibility: hidden;</code></th> </tr> <tr> <td> <div class="container"> <div class="cube showbf"> <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> ...
border-bottom-left-radius - CSS: Cascading Style Sheets
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 .
border-bottom-right-radius - CSS: Cascading Style Sheets
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 .
border-image-slice - CSS: Cascading Style Sheets
html <div class="wrapper"> <div></div> </div> <ul> <li> <label for="width">slide to adjust <code>border-width</code></label> <input type="range" min="10" max="45" id="width"> <output id="width-output">30px</output> </li> <li> <label for="slice">slide to adjust <code>border-image-slice</code></label> <input type="range" min="10" max="45" id="slice"> <output id="slice-output">30</output> </li> </ul> css .wrapper { width: 400px; height: 300px; } div > div { wi...
border-top-left-radius - CSS: Cascading Style Sheets
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 ellipse is used as the border div { border-top-left-radius: 40px 40px; } an arc of ellipse is used as the border div { border-top-left-radius: 40px 20px; } the box is a square: an arc of circle is used as the border div { border-top-left-radius: 40%; } the box ...
border-top-right-radius - CSS: Cascading Style Sheets
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
WebCSScalc
consider the following code: .foo { --widtha: 100px; --widthb: calc(var(--widtha) / 2); --widthc: calc(var(--widthb) / 2); width: var(--widthc); } after all variables are expanded, widthc's value will be calc( calc( 100px / 2) / 2), then when it's assigned to .foo's width property, all inner calc()s (no matter how deeply nested) will be flattened to just parentheses, so the width property's value will be eventuall...
clamp() - CSS: Cascading Style Sheets
WebCSSclamp
it has the same effect as the code in fluid typography but in one line, and without the use of media queries.
content - CSS: Cascading Style Sheets
WebCSScontent
non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol.
counters() - CSS: Cascading Style Sheets
WebCSScounters
non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol.
cross-fade() - CSS: Cascading Style Sheets
the percent value must be coded without quotes, must contain the “%” symbol, and its value must be between 0% and 100%.
font-family - CSS: Cascading Style Sheets
"open sans", "fira sans", "lucida sans", "lucida sans unicode", "trebuchet ms", "liberation sans", "nimbus sans l", sans-serif.
font-feature-settings - CSS: Cascading Style Sheets
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.
font-language-override - CSS: Cascading Style Sheets
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.
font-variant-alternates - CSS: Cascading Style Sheets
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).
font-variation-settings - CSS: Cascading Style Sheets
if the <string> has more or fewer characters or contains characters outside the u+20 - u+7e codepoint range, the whole property is invalid.
gap (grid-gap) - CSS: Cascading Style Sheets
WebCSSgap
<div></div> <div></div> </div> css #grid { grid-gap: 20px 5px; } #grid { display: grid; height: 200px; grid-template: repeat(3, 1fr) / repeat(3, 1fr); gap: 20px 5px; } #grid > div { border: 1px solid green; background-color: lime; } result multi-column layout html <p class="content-box"> this is some multi-column text with a 40px column gap created with the css <code>gap</code> property.
image-orientation - CSS: Cascading Style Sheets
will not apply any additional image rotation; the image is oriented as encoded or as other css property values dictate.
ime-mode - CSS: Cascading Style Sheets
WebCSSime-mode
this property should only be used for private web applications or to undo the property if it was previously set by legacy code.
<integer> - CSS: Cascading Style Sheets
WebCSSinteger
\35 escaped unicode characters are not allowed, even if they are an integer (here: 5).
margin-bottom - CSS: Cascading Style Sheets
this property has no effect on non-replaced inline elements, such as <span> or <code>.
margin-top - CSS: Cascading Style Sheets
this property has no effect on non-replaced inline elements, such as <span> or <code>.
margin - CSS: Cascading Style Sheets
WebCSSmargin
the top and bottom margins have no effect on non-replaced inline elements, such as <span> or <code>.
order - CSS: Cascading Style Sheets
WebCSSorder
items in a container are sorted by ascending order value and then by their source code order.
overscroll-behavior-block - CSS: Cascading Style Sheets
html <main> <div> <div> <p><code>overscroll-behavior-block</code> has been used to make it so that when the scroll boundaries of the yellow inner box are reached, the whole page does not begin to scroll.</p> </div> </div> </main> css main { height: 3000px; width: 500px; background-color: white; background-image: repeating-linear-gradient(to bottom, rgba(0,0,0,0) 0px, rgba(0,0,0,0) 19px, rgba(0,0,0,0.5) 20px); } ...
overscroll-behavior-inline - CSS: Cascading Style Sheets
html <main> <div> <div> <p><code>overscroll-behavior-inline</code> has been used to make it so that when the scroll boundaries of the yellow inner box are reached, the whole page does not begin to scroll.</p> </div> </div> </main> css main { height: 400px; width: 3000px; background-color: white; background-image: repeating-linear-gradient(to right, rgba(0,0,0,0) 0px, rgba(0,0,0,0) 19px, rgba(0,0,0,0.5) 20px); } ...
overscroll-behavior-x - CSS: Cascading Style Sheets
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.
overscroll-behavior - CSS: Cascading Style Sheets
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.
text-decoration-skip - CSS: Cascading Style Sheets
spaces all spacing is skipped: all unicode white space characters and all word separators, plus any adjacent letter-spacing or word-spacing.
transform-box - CSS: Cascading Style Sheets
e the pen won't work properly on chrome for mac, ff, safari will still work properly on chrome for pc & opera*/ transform-box: fill-box; /*alternatively i can use transform-origin:15px 15px;*/ /*+++++++++++++++++++++++++++*/ animation: rotatebox 3s linear infinite; } @keyframes rotatebox { to { transform: rotate(360deg); } full credit for this example goes to pogany; see this codepen for a live version.
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...
transform-style - CSS: Cascading Style Sheets
html <section id="example-element"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </section> <div class="checkbox"> <label for="preserve"><code>preserve-3d</code></label> <input type="checkbox" id="preserve" checked> </div> css #example-element { margin: 50px; width: 100px; height: 100px; transform-style: preserve-3d; transform: rotate3d(1, 1, 1, 30deg); } .face { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; position: absolute; backface-visibility: inherit; font-si...
will-change - CSS: Cascading Style Sheets
so it is a good practice to switch will-change on and off using script code before and after the change occurs.
CSS: Cascading Style Sheets
WebCSS
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.
regexp:match() - EXSLT
WebEXSLTregexpmatch
for example: <xsl:for-each select="regexp:match('http://developer.mozilla.org/en/docs/firefox_3_for_developers', '(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)')"> part <xsl:value-of select="position()" /> = <xsl:value-of select="." /> </xsl:for-each> this code generates the following output: part 1 = http://developer.mozilla.org/en/docs/firefox_3_for_developers part 2 = http part 3 = developer.mozilla.org part 4 = part 5 = /en/docs/firefox_3_for_developers specifications exslt - regexp:match ...
Index - Event reference
WebEventsIndex
found 2 pages: # page tags and summary 1 event reference event, overview, reference dom events are sent to notify code of interesting things that have taken place.
Event reference
dom events are sent to notify code of interesting things that have taken place.
Community - Developer guides
WebGuideAJAXCommunity
ajax resources ajax workshops and courses skillsmatter.com: courses and events on javascript, ajax, and reverse ajax technologies telerik.com: an active community forum for ajax community.tableau.com: community support forum and courses available for ajax codementor.io: social platform with ajax forums and tutorials lynda.com: tutorials available for learning the fundamentals of ajax ajax interview questions and answer and answerinterwiki links ...
WAI ARIA Live Regions/API Support - Developer guides
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.
Challenge solutions - Developer guides
color three-digit color codes challenge in your css file, change all the color names to 3-digit color codes without affecting the result.
Creating and triggering events - Developer guides
elem.dispatchevent(event); the above code example uses the eventtarget.dispatchevent() method.
Media events - Developer guides
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.
Mouse gesture events - Developer guides
note: these gesture events are available to add-ons and other browser chrome code, but are never sent to regular web page content.
Using device orientation with 3D transforms - Developer guides
here's a simple code snippet to sum it up: var elem = document.getelementbyid("view3d"); window.addeventlistener("deviceorientation", function(e) { // remember to use vendor-prefixed transform property elem.style.transform = "rotatez(" + ( e.alpha - 180 ) + "deg) " + "rotatex(" + e.beta + "deg) " + "rotatey(" + ( -e.gamma ) + "deg)"; }); orientation compensation compensating the orientation of th...
Event developer guide - Developer guides
WebGuideEvents
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.
Making content editable - Developer guides
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.
Introduction to HTML5 - Developer guides
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.
HTML5 - Developer guides
WebGuideHTMLHTML5
html5 reference guide quick-reference html5 sheet containing markup generators, code examples and web developer tools.
HTML attribute: accept - HTML: Hypertext Markup Language
> using file inputs a basic example <form method="post" enctype="multipart/form-data"> <div> <label for="file">choose file to upload</label> <input type="file" id="file" name="file" multiple> </div> <div> <button>submit</button> </div> </form> div { margin-bottom: 10px; } this produces the following output: note: you can find this example on github too — see the source code, and also see it running live.
HTML attribute: required - HTML: Hypertext Markup Language
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.
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
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.
<caption>: The Table Caption element - HTML: Hypertext Markup Language
WebHTMLElementcaption
they are documented below for reference when updating existing code and for historical interest only.
<del>: The Deleted Text element - HTML: Hypertext Markup Language
WebHTMLElementdel
this can be used when rendering "track changes" or source code diff information, for example.
<dl>: The Description List element - HTML: Hypertext Markup Language
WebHTMLElementdl
codepen - html buddies: dt & dd specifications specification status comment html living standardthe definition of '<dl>' in that specification.
<form> - HTML: Hypertext Markup Language
WebHTMLElementform
possible values: application/x-www-form-urlencoded: the default value.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
integrity contains inline metadata — a base64-encoded cryptographic hash of the resource (file) you’re telling the browser to fetch.
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
WebHTMLElementmeta
if the charset attribute is set, the meta element is a charset declaration, giving the character encoding in which the document is encoded.
<plaintext>: The Plain Text element (Deprecated) - HTML: Hypertext Markup Language
instead of <plaintext>, use the <pre> element or, if semantically accurate (such as for inline text), the <code> element.
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
WebHTMLElementrb
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.
<samp>: The Sample Output element - HTML: Hypertext Markup Language
WebHTMLElementsamp
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.
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
WebHTMLElementshadow
for this code to work, the browser you display it in must support web components.
<slot> - HTML: Hypertext Markup Language
WebHTMLElementslot
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
WebHTMLElementsource
type the mime media type of the resource, optionally with a codecs parameter.
<strike> - HTML: Hypertext Markup Language
WebHTMLElementstrike
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.
<tbody>: The Table Body element - HTML: Hypertext Markup Language
WebHTMLElementtbody
it is a 6-digit hexadecimal rgb code, prefixed by a '#'.
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
WebHTMLElementtd
it is a 6-digit hexadecimal rgb code, prefixed by a '#'.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
<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.
<tfoot>: The Table Foot element - HTML: Hypertext Markup Language
WebHTMLElementtfoot
it is one of the 6-digit hexadecimal code as defined in srgb, prefixed by a '#'.
<th> - HTML: Hypertext Markup Language
WebHTMLElementth
it consists of a 6-digit hexadecimal code as defined in srgb and is prefixed by '#'.
<thead>: The Table Head element - HTML: Hypertext Markup Language
WebHTMLElementthead
it is one of the 6-digit hexadecimal code as defined in srgb, prefixed by a '#'.
<var>: The Variable element - HTML: Hypertext Markup Language
WebHTMLElementvar
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" whe...
<xmp> - HTML: Hypertext Markup Language
WebHTMLElementxmp
use the <pre> element or, if semantically adequate, the <code> element instead.
dir - HTML: Hypertext Markup Language
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.
id - HTML: Hypertext Markup Language
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.
is - HTML: Hypertext Markup Language
examples the following code is taken from our word-count-web-component example (see it live also).
itemscope - HTML: Hypertext Markup Language
</div> </div> results html the following is an example rendering of the preceding code example.
title - HTML: Hypertext Markup Language
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.
Inline elements - HTML: Hypertext Markup Language
list of "inline" elements the following elements are inline by default (although block and inline elements are no longer defined in html 5, use content categories instead): <a> <abbr> <acronym> <audio> (if it has visible controls) <b> <bdi> <bdo> <big> <br> <button> <canvas> <cite> <code> <data> <datalist> <del> <dfn> <em> <embed> <i> <iframe> <img> <input> <ins> <kbd> <label> <map> <mark> <meter> <noscript> <object> <output> <picture> <progress> <q> <ruby> <s> <samp> <script> <select> <slot> <small> <span> <strong> <sub> <sup> <svg> <template> <textarea> <time> <u> <tt> <var> <video> <wbr> see also block-level elements html elemen...
Using the application cache - HTML: Hypertext Markup Language
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.
Choosing between www and non-www URLs - HTTP
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.
Identifying resources on the Web - HTTP
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.
Resource URLs - HTTP
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).
Basics of HTTP - HTTP
this article explains the frame structure, its purpose, and the way it's encoded.
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
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.
Reason: CORS request external redirect not allowed - HTTP
to fix the problem, update your code to use the new url as reported by the redirect, thereby avoiding the redirect.
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
make sure your code only uses the permitted http methods when accessing the service.
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
to fix this problem on the client side, revise the code to not request the use of credentials.
Reason: CORS header ‘Origin’ cannot be added - HTTP
this can happen if the javascript code is running with enhanced privileges allowing it access to multiple domains' content, for example.
Reason: CORS preflight channel did not succeed - HTTP
make sure your code only preflights once per connection.
HTTP caching - HTTP
WebHTTPCaching
this can be useful if pages with http authentication, or response status codes that aren't normally cacheable, should now be cached.
Content negotiation - HTTP
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.
Using HTTP cookies - HTTP
WebHTTPCookies
there are companies that offer "cookie banner" code that helps you comply with these regulations.
Feature Policy - HTTP
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.
Accept-Charset - HTTP
if the server cannot serve any character encoding from this request header, it can theoretically send back a 406 not acceptable error code.
Accept-Language - HTTP
if the server cannot serve any matching language, it can theoretically send back a 406 (not acceptable) error code.
Allow - HTTP
WebHTTPHeadersAllow
this header must be sent if the server responds with a 405 method not allowed status code to indicate which request methods can be used.
Authorization - HTTP
the resulting string is base64 encoded (ywxhzgrpbjpvcgvuc2vzyw1l).
Content-Encoding - HTTP
it lets the client know how to decode in order to obtain the media-type referenced by the content-type header.
Content-Language - HTTP
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.
CSP: report-uri - HTTP
$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 "...
CSP: require-sri-for - HTTP
<script src="https://code.jquery.com/jquery-3.1.1.slim.js" integrity="sha256-5i/mq300m779n2ovdrl16lbohwxnudzl/r2avuxyxwa=" crossorigin="anonymous"></script> however, scripts without integrity won't load anymore: <script src="https://code.jquery.com/jquery-3.1.1.slim.js"></script> ...
CSP: trusted-types - HTTP
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.
Content-Security-Policy-Report-Only - HTTP
status-code the http status code of the resource on which the global object was instantiated.
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
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.
Date - HTTP
WebHTTPHeadersDate
note that date is listed in the forbidden header names in the fetch spec - so this code will not send date header: fetch('https://httpbin.org/get', { 'headers': { 'date': (new date()).toutcstring() } }) header type general header forbidden header name yes syntax date: <day-name>, <day> <month> <year> <hour>:<minute>:<second> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive).
Early-Data - HTTP
the early-data header is set by an intermediary to indicate that the request has been conveyed in tls early data, and also indicates that the intermediary understands the 425 (too early) status code.
Feature-Policy: geolocation - HTTP
when this policy is enabled, calls to getcurrentposition() and watchposition() will cause those functions' callbacks to be invoked with a positionerror code of permission_denied.
Feature-Policy - HTTP
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.
Host - HTTP
WebHTTPHeadersHost
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.
Location - HTTP
WebHTTPHeadersLocation
all responses with one of these status codes send a location header.
Proxy-Authorization - HTTP
the resulting string is base64 encoded (ywxhzgrpbjpvcgvuc2vzyw1l).
Public-Key-Pins-Report-Only - HTTP
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.
Public-Key-Pins - HTTP
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.
Range - HTTP
WebHTTPHeadersRange
the server can also ignore the range header and return the whole document with a 200 status code.
Sec-WebSocket-Accept - HTTP
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.
Set-Cookie - HTTP
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.
SourceMap - HTTP
the sourcemap http response header links generated code to a source map, enabling the browser to reconstruct the original source and present the reconstructed original in the debugger.
User-Agent - HTTP
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.
HTTP headers - HTTP
WebHTTPHeaders
sourcemap links generated code to a source map.
Proxy Auto-Configuration (PAC) file - HTTP
isresolvable() isinnet() related utility functions dnsresolve() convert_addr() myipaddress() dnsdomainlevels() url/hostname based conditions shexpmatch() time based conditions weekdayrange() daterange() timerange() logging utility alert() there was one associative array (object) already defined, because at the time javascript code was unable to define it by itself: proxyconfig.bindings note: pactester (part of the pacparser package) was used to test the following syntax examples.
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 ...
101 Switching Protocols - HTTP
WebHTTPStatus101
the http 101 switching protocols response code indicates the protocol the server is switching to as requested by a client which sent the message including the upgrade request header.
103 Early Hints - HTTP
WebHTTPStatus103
the http 103 early hints information response status code is primarily intended to be used with the link header to allow the user agent to start preloading resources while the server is still preparing a response.
200 OK - HTTP
WebHTTPStatus200
the http 200 ok success status response code indicates that the request has succeeded.
202 Accepted - HTTP
WebHTTPStatus202
the hypertext transfer protocol (http) 202 accepted response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet.
203 Non-Authoritative Information - HTTP
WebHTTPStatus203
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.
204 No Content - HTTP
WebHTTPStatus204
the http 204 no content success status response code indicates that the request has succeeded, but that the client doesn't need to go away from its current page.
206 Partial Content - HTTP
WebHTTPStatus206
the http 206 partial content success status response code indicates that the request has succeeded and has the body contains the requested ranges of data, as described in the range header of the request.
304 Not Modified - HTTP
WebHTTPStatus304
the http 304 not modified client redirection response code indicates that there is no need to retransmit the requested resources.
307 Temporary Redirect - HTTP
WebHTTPStatus307
http 307 temporary redirect redirect status response code indicates that the resource requested has been temporarily moved to the url given by the location headers.
400 Bad Request - HTTP
WebHTTPStatus400
the hypertext transfer protocol (http) 400 bad request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
401 Unauthorized - HTTP
WebHTTPStatus401
the http 401 unauthorized client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
403 Forbidden - HTTP
WebHTTPStatus403
the http 403 forbidden client error status response code indicates that the server understood the request but refuses to authorize it.
405 Method Not Allowed - HTTP
WebHTTPStatus405
the hypertext transfer protocol (http) 405 method not allowed response status code indicates that the request method is known by the server but is not supported by the target resource.
407 Proxy Authentication Required - HTTP
WebHTTPStatus407
the http 407 proxy authentication required client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for a proxy server that is between the browser and the server that can access the requested resource.
408 Request Timeout - HTTP
WebHTTPStatus408
the hypertext transfer protocol (http) 408 request timeout response status code means that the server would like to shut down this unused connection.
409 Conflict - HTTP
WebHTTPStatus409
the http 409 conflict response status code indicates a request conflict with current state of the server.
411 Length Required - HTTP
WebHTTPStatus411
the hypertext transfer protocol (http) 411 length required client error response code indicates that the server refuses to accept the request without a defined content-length header.
412 Precondition Failed - HTTP
WebHTTPStatus412
the hypertext transfer protocol (http) 412 precondition failed client error response code indicates that access to the target resource has been denied.
413 Payload Too Large - HTTP
WebHTTPStatus413
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.
414 URI Too Long - HTTP
WebHTTPStatus414
the http 414 uri too long response status code indicates that the uri requested by the client is longer than the server is willing to interpret.
415 Unsupported Media Type - HTTP
WebHTTPStatus415
the http 415 unsupported media type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.
416 Range Not Satisfiable - HTTP
WebHTTPStatus416
the hypertext transfer protocol (http) 416 range not satisfiable error response code indicates that a server cannot serve the requested ranges.
417 Expectation Failed - HTTP
WebHTTPStatus417
the http 417 expectation failed client error response code indicates that the expectation given in the request's expect header could not be met.
422 Unprocessable Entity - HTTP
WebHTTPStatus422
the hypertext transfer protocol (http) 422 unprocessable entity response status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions.
425 Too Early - HTTP
WebHTTPStatus425
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.
426 Upgrade Required - HTTP
WebHTTPStatus426
the http 426 upgrade required client error response code indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
501 Not Implemented - HTTP
WebHTTPStatus501
the hypertext transfer protocol (http) 501 not implemented server error response code means that the server does not support the functionality required to fulfill the request.
502 Bad Gateway - HTTP
WebHTTPStatus502
the hypertext transfer protocol (http) 502 bad gateway server error response code indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server.
503 Service Unavailable - HTTP
WebHTTPStatus503
the hypertext transfer protocol (http) 503 service unavailable server error response code indicates that the server is not ready to handle the request.
504 Gateway Timeout - HTTP
WebHTTPStatus504
the hypertext transfer protocol (http) 504 gateway timeout server error response code indicates that the server, while acting as a gateway or proxy, did not get a response in time from the upstream server that it needed in order to complete the request.
505 HTTP Version Not Supported - HTTP
WebHTTPStatus505
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.
507 Insufficient Storage - HTTP
WebHTTPStatus507
the hypertext transfer protocol (http) 507 insufficient storage response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol (see rfc 4918).
508 Loop Detected - HTTP
WebHTTPStatus508
the hypertext transfer protocol (http) 508 loop detected response status code may be given in the context of the web distributed authoring and versioning (webdav) protocol.
HTTP
WebHTTP
http status response codes http response codes indicate whether a specific http request has been successfully completed.
Equality comparisons and sameness - JavaScript
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.
Meta programming - JavaScript
function.prototype.apply.call(math.floor, undefined, [1.75]) with reflect.apply this becomes less verbose and easier to understand: 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" checking if property definition has been successful with object.defineproperty, which returns an object if successful, or throws a typeerror otherwise, you would use a try...catch block to catch any error that occurred while...
Groups and ranges - JavaScript
for example, to extract the united states area code from a phone number, we could use /\((?<area>\d\d\d)\)/.
Quantifiers - JavaScript
note: in the following, item refers not only to singular characters, but also includes character classes, unicode property escapes, groups and ranges.
JavaScript technologies overview - JavaScript
parseint, parsefloat, decodeuri, encodeuri...
JavaScript language resources - JavaScript
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.
About the JavaScript reference - JavaScript
as you write javascript code, you'll refer to these pages often (thus the title "javascript reference").
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
with source maps, the debugger can map the code being executed to the original source files.
SyntaxError: return not in function - JavaScript
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.
TypeError: can't assign to property "x" on "y": not an object - JavaScript
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.
TypeError: can't redefine non-configurable property "x" - JavaScript
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.
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
with source maps, the debugger can map the code being executed to the original source files.
SyntaxError: identifier starts immediately after numeric literal - JavaScript
the names of variables, called identifiers, conform to certain rules, which your code must adhere to!
SyntaxError: JSON.parse: bad parsing - JavaScript
message syntaxerror: json.parse: unterminated string literal syntaxerror: json.parse: bad control character in string literal syntaxerror: json.parse: bad character in string literal syntaxerror: json.parse: bad unicode escape syntaxerror: json.parse: bad escape character syntaxerror: json.parse: unterminated string syntaxerror: json.parse: no number after minus sign syntaxerror: json.parse: unexpected non-digit syntaxerror: json.parse: missing digits after decimal point syntaxerror: json.parse: unterminated fractional number syntaxerror: json.parse: missing digits after exponent indicator syntaxerror: json.parse: missing digits after exponent sign syntaxerror: json.parse: exponent part is missin...
SyntaxError: missing : after property id - JavaScript
equal signs this code fails, as the equal sign can't be used this way in this object initializer syntax.
SyntaxError: missing formal parameter - JavaScript
an identifier differs from a string in that a string is data, while an identifier is part of the code.
SyntaxError: missing name after . operator - JavaScript
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.
SyntaxError: missing variable name - JavaScript
this is likely due to a syntax error in your code.
ReferenceError: "x" is not defined - JavaScript
put the <script> tag that loads the library before your code that uses it.
InternalError: too much recursion - JavaScript
both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).
Method definitions - JavaScript
given the following code: const obj = { foo: function() { // ...
getter - JavaScript
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.
Rest parameters - JavaScript
from arguments to an array rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments // before rest parameters, "arguments" could be converted to a normal array using: function f(a, b) { let normalarray = array.prototype.slice.call(arguments) // -- or -- let normalarray = [].slice.call(arguments) // -- or -- let normalarray = array.from(arguments) let first = normalarray.shift() // ok, gives the first argument let first = argum...
Array.prototype[@@unscopables] - JavaScript
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.
Array.prototype.reduce() - JavaScript
the code below will produce the same output as the code in the block above: [0, 1, 2, 3, 4].reduce( (accumulator, currentvalue, currentindex, array) => accumulator + currentvalue ) if you were to provide an initialvalue as the second argument to reduce(), the result would look like this: [0, 1, 2, 3, 4].reduce((accumulator, currentvalue, currentindex, array) => { return accumulator + currentvalue ...
Array.prototype.reduceRight() - JavaScript
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.
Array.prototype.every() - JavaScript
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.
Array.prototype.filter() - JavaScript
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.
Array.prototype.indexOf() - JavaScript
you can work around this by utilizing the following code at the beginning of your scripts.
Array.isArray() - JavaScript
polyfill running the following code before any other code will create array.isarray() if it's not natively available.
Array.of() - JavaScript
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.
Array.prototype.push() - JavaScript
examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it.
Array.prototype.shift() - JavaScript
examples removing an element from an array the following code displays the myfish array before and after removing its first element.
Array.prototype.some() - JavaScript
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.
Boolean.prototype.toString() - JavaScript
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
this method is usually called internally by javascript and not explicitly in code.
Date.prototype.valueOf() - JavaScript
this method is usually called internally by javascript and not explicitly in code.
Date - JavaScript
(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
defaults to the name of the file containing the code that called the error() constructor.
Error.prototype.stack - JavaScript
e@file:///c:/example.html:9 b@file:///c:/example.html:16 a@file:///c:/example.html:19 @file:///c:/example.html:21 firefox 13 and earlier would instead produce the following text: error("myerror")@:0 trace()@file:///c:/example.html:9 b(3,4,"\n\n",(void 0),[object object])@file:///c:/example.html:16 a("first call, firstarg")@file:///c:/example.html:19 @file:///c:/example.html:21 stack of eval'ed code starting with firefox 30, the error stack of code in function() and eval() calls, now produces stacks with more detailed information about the line and column numbers inside these calls.
Error.prototype.fileName - JavaScript
if called from a debugger context, the firefox developer tools for example, "debugger eval code" is returned.
FinalizationRegistry - JavaScript
when the finalizationregistry instance itself is no longer reachable by javascript code.
Intl.Collator - JavaScript
collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions.
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
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.
Intl.Locale.prototype.baseName - JavaScript
basename returns the language ["-" script] ["-" region] *("-" variant) subsequence of the unicode_language_id grammar.
Intl.Locale.prototype.caseFirst - JavaScript
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.
Intl.Locale.prototype.hourCycle - JavaScript
adding an hour cycle via the locale string in the unicode locale string spec, the hour cycle is a locale string "extension subtag".
Intl.Locale.prototype.numeric - JavaScript
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.
Intl.Locale.prototype.region - JavaScript
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.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
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.
JSON - JavaScript
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.
Map.prototype.forEach() - JavaScript
examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new map([['foo', 3], ['bar', {}], ['baz', undefined]]).foreach(logmapelements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object object]" // "map.get('baz') = undefined" specifications specification ecmascript (ecma-262)t...
Math.clz32() - JavaScript
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.
Number.MAX_VALUE - JavaScript
examples using max_value the following code multiplies two numeric values.
Number.MIN_VALUE - JavaScript
examples using min_value the following code divides two numeric values.
Number.prototype.valueOf() - JavaScript
description this method is usually called internally by javascript and not explicitly in web code.
Number - JavaScript
a number literal like 37 in javascript code is a floating-point value, not an integer.
Object.entries() - JavaScript
ntries repositories; or, you can use the simple, ready-to-deploy polyfill listed below: if (!object.entries) { object.entries = function( obj ){ var ownprops = object.keys( obj ), i = ownprops.length, resarray = new array(i); // preallocate the array while (i--) resarray[i] = [ownprops[i], obj[ownprops[i]]]; return resarray; }; } for the above polyfill code snippet, if you need support for ie<9, then you will also need an object.keys() polyfill (such as the one found on the object.keys page).
Object.freeze() - JavaScript
> object.freeze(1) typeerror: 1 is not an object // es5 code > object.freeze(1) 1 // es2015 code an arraybufferview with elements will cause a typeerror, as they are views over memory and will definitely cause other possible issues: > object.freeze(new uint8array(0)) // no elements uint8array [] > object.freeze(new uint8array(1)) // has elements typeerror: cannot freeze array buffer views with elements > object.freeze(new ...
Object.getOwnPropertyDescriptor() - JavaScript
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
instead, you can use this code to set the prototype: function superclass() {} superclass.prototype = { // define your methods and properties here }; function subclass() {} subclass.prototype = object.create( superclass.prototype, { // define your methods and properties here } ); specifications specification ecmascript (ecma-262)the definition of 'object.getownpropertydescriptors' in that speci...
Object.getOwnPropertyNames() - JavaScript
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.
Object.getPrototypeOf() - JavaScript
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
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
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
type); baz.prototype = object.create(bar.prototype); var baz = new baz(); console.log(baz.prototype.isprototypeof(baz)); // true console.log(bar.prototype.isprototypeof(baz)); // true console.log(foo.prototype.isprototypeof(baz)); // true console.log(object.prototype.isprototypeof(baz)); // true isprototypeof() method, along with the instanceof operator particularly comes in handy if you have code that can only function when dealing with objects descended from a specific prototype chain, e.g., to guarantee that certain methods or properties will be present on that object.
Object.isSealed() - JavaScript
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.keys() - JavaScript
, prop, i; for (prop in obj) { if (hasownproperty.call(obj, prop)) { result.push(prop); } } if (hasdontenumbug) { for (i = 0; i < dontenumslength; i++) { if (hasownproperty.call(obj, dontenums[i])) { result.push(dontenums[i]); } } } return result; }; }()); } please note that the above code includes non-enumerable keys in ie7 (and maybe ie8), when passing in an object from a different window.
Object.preventExtensions() - JavaScript
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
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.
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
examples trapping a function call the following code traps a function call.
handler.defineProperty() - JavaScript
examples trapping of defineproperty the following code traps object.defineproperty().
handler.deleteProperty() - JavaScript
examples trapping the delete operator the following code traps the delete operator.
RangeError() constructor - JavaScript
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 using rangeerror (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple",...
Reflect.apply() - JavaScript
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.
Set.prototype.forEach() - JavaScript
examples logging the contents of a set object the following code logs a line for each element in a set object: function logsetelements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); } new set(['foo', 'bar', undefined]).foreach(logsetelements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.foreach' in ...
String.prototype[@@iterator]() - JavaScript
the [@@iterator]() method returns a new iterator object that iterates over the code points of a string value, returning each code point as a string value.
String.prototype.link() - JavaScript
the link() method creates a string representing the code for an <a> html element to be used as a hypertext link to another url.
String.prototype.match() - JavaScript
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.
String.raw() - JavaScript
you can even re-implement it with normal javascript code.
String.prototype.substr() - JavaScript
to use this feature in jscript, you can use the following code: // only run when the substr() function is broken if ('ab'.substr(-1) != 'b') { /** * get the substring of a string * @param {integer} start where to start the substring * @param {integer} length how many characters to return * @return {string} */ string.prototype.substr = function(substr) { return function(start, length) { // call the original method ...
String.prototype.substring() - JavaScript
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.
String.prototype.toLocaleLowerCase() - JavaScript
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.
String.prototype.toLocaleUpperCase() - JavaScript
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.
String.prototype.trim() - JavaScript
polyfill running the following code before any other code will create trim() if it's not natively available.
String.prototype.valueOf() - JavaScript
this method is usually called internally by javascript and not explicitly in code.
Symbol() constructor - JavaScript
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.
Symbol.for() - JavaScript
/ create a new global symbol symbol.for('foo'); // retrieve the already created symbol // same global symbol, but not locally symbol.for('bar') === symbol.for('bar'); // true symbol('bar') === symbol('bar'); // false // the key is also used as the description var sym = symbol.for('mario'); sym.tostring(); // "symbol(mario)" to avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols: symbol.for('mdn.foo'); symbol.for('mdn.bar'); specifications specification ecmascript (ecma-262)the definition of 'symbol.for' in that specification.
Symbol.match - JavaScript
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.
Symbol.unscopables - JavaScript
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.
TypedArray.prototype.forEach() - JavaScript
examples logging the contents of a typed array the following code logs a line for each element in a typed array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element); } new uint8array([0, 1, 2, 3]).foreach(logarrayelements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.foreach' in that specif...
TypedArray.from() - JavaScript
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.
TypedArray.prototype.toString() - JavaScript
for example, the following code creates a typed array and uses tostring to convert the array to a string.
URIError - JavaScript
examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n"...
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.
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.
WebAssembly.Instance.prototype.exports - JavaScript
instance.exports examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process.
WebAssembly.Instance - JavaScript
instance objects contain all the exported webassembly functions that allow calling into webassembly code from javascript.
WebAssembly.Memory.prototype.buffer - JavaScript
examples using buffer 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.
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.
WebAssembly.Module.exports() - JavaScript
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().
WebAssembly.Module.imports() - JavaScript
examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module.
WebAssembly.Table() constructor - JavaScript
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.
WebAssembly.Table.prototype.get() - JavaScript
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.
WebAssembly.Table.prototype.set() - JavaScript
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.
WebAssembly.instantiateStreaming() - JavaScript
this is the most efficient, optimized way to load wasm code.
Iteration protocols - JavaScript
}, [symbol.iterator]: function() { return this; } }; examples using the iteration protocols a string is an example of a built-in iterable object: let somestring = 'hi'; console.log(typeof somestring[symbol.iterator]); // "function" string's default iterator returns the string's code points one by one: let iterator = somestring[symbol.iterator](); console.log(iterator + ''); // "[object string iterator]" console.log(iterator.next()); // { value: "h", done: false } console.log(iterator.next()); // { value: "i", done: false } console.log(iterator.next()); // { value: undefined, done: true } some built-in constructs—such as the spread syntax—use the same iteration protoco...
Less than (<) - JavaScript
if both values are strings, they are compared as strings, based on the values of the unicode code points they contain.
Logical AND (&&) - JavaScript
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.
Logical NOT (!) - JavaScript
examples using not the following code shows examples of the !
Logical OR (||) - JavaScript
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.
Pipeline operator (|>) - JavaScript
the result is syntactic sugar in which a function call with a single argument can be written like this: let url = "%21" |> decodeuri; the equivalent call in traditional syntax looks like this: let url = decodeuri("%21"); syntax expression |> function the value of the specified expression is passed into the function as its sole parameter.
Spread syntax (...) - JavaScript
arguments.length: 6 // (internal log of myconstructor): ["hi", "how", "are", "you", "mr", null] // (log of "new myconstructorwitharguments"): {prop1: "val1", prop2: "val2"} spread in array literals a more powerful array literal without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of push(), splice(), concat(), etc.
Function expression - JavaScript
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
examples using super in classes this code snippet is taken from the classes sample (live demo).
yield* - JavaScript
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().
block - JavaScript
in non-strict code, function declarations inside blocks behave strangely.
for await...of - JavaScript
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.
for...in - JavaScript
alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method.
for...of - JavaScript
ray.prototype.arrcustom = function() {}; const iterable = [3, 5, 7]; iterable.foo = 'hello'; for (const i in iterable) { console.log(i); // logs 0, 1, 2, "foo", "arrcustom", "objcustom" } for (const i in iterable) { if (iterable.hasownproperty(i)) { console.log(i); // logs 0, 1, 2, "foo" } } for (const i of iterable) { console.log(i); // logs 3, 5, 7 } let us look into the above code step by step.
function* - JavaScript
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}.
switch - JavaScript
ction = 'say_hello'; switch (action) { case 'say_hello': { // added brackets let message = 'hello'; console.log(message); break; } // added brackets case 'say_hi': { // added brackets let message = 'hi'; console.log(message); break; } // added brackets default: { // added brackets console.log('empty action received.'); break; } // added brackets } this code will now output hello in the console as it should, without any errors at all.
JavaScript reference - JavaScript
value properties infinity nan undefined globalthis function properties eval() isfinite() isnan() parsefloat() parseint() decodeuri() decodeuricomponent() encodeuri() encodeuricomponent() fundamental objects object function boolean symbol error objects error aggregateerror evalerror internalerror rangeerror referenceerror syntaxerror typeerror urierror numbers & dates number bigint math date text processing string regexp indexed collections array int8ar...
dir - Web app manifests
WebManifestdir
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.
<mglyph> - MathML
WebMathMLElementmglyph
the mathml <mglyph> element is used to display non-standard symbols where existing unicode characters are not available.
<semantics> - MathML
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.
Handling media support issues in web content - Web media technologies
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.
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
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.
Recommended Web Performance Timings: How long is too long? - Web Performance
for this reason, script execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less.
Performance budgets - Web Performance
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.
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
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.
Installing and uninstalling web apps - Progressive web apps (PWAs)
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.
How to make PWAs installable - Progressive web apps (PWAs)
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.
Web API reference - Web technology reference
WebReferenceAPI
these can be accessed using javascript code, and let you do anything from making minor adjustments to any window or element, to generating intricate graphical and audio effects using apis such as webgl and web audio.
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
example: masking for example, you can make a gradient mask for html content using svg and css code similar to the following, inside your html document: <svg height="0"> <mask id="mask-1"> <lineargradient id="gradient-1" y2="1"> <stop stop-color="white" offset="0"/> <stop stop-opacity="0" offset="1"/> </lineargradient> <circle cx="0.25" cy="0.25" r="0.25" id="circle" fill="white"/> <rect x="0.5" y="0.2" width="300" height="100" fill="url(#gradient-1)"/> </mask> ...
glyph-name - SVG: Scalable Vector Graphics
the glyph names can be used in situations where unicode character numbers do not provide sufficient information to access the correct glyph, such as when there are multiple glyphs per unicode character.
href - SVG: Scalable Vector Graphics
WebSVGAttributehref
value <url> default value none animatable yes script for <script>, href defines a url referring to an external resource containing the script code.
textLength - SVG: Scalable Vector Graphics
javascript finally, let's have a look at the javascript code.
writing-mode - SVG: Scalable Vector Graphics
(note that the inline-progression-direction can change within a <text> element due to the unicode bidirectional algorithm and properties direction and unicode-bidi.) note: as a presentation attribute, writing-mode can be used as a css property.
xlink:href - SVG: Scalable Vector Graphics
value <iri> default value none animatable yes script for <script>, xlink:href defines a reference to an external resource containing the script code.
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 url is a sequence of unicode characters, building an address to an internal or external resource.
<font-face> - SVG: Scalable Vector Graphics
WebSVGElementfont-face
attributes global attributes core attributes specific attributes font-family font-style font-variant font-weight font-stretch font-size unicode-range units-per-em panose-1 stemv stemh slope cap-height x-height accent-height ascent descent widths bbox ideographic alphabetic mathematical hanging v-ideographic v-alphabetic v-mathematical v-hanging underline-position underline-thickness strikethrough-position strikethrough-thickness overline-position overline-thickness dom interface this element implements the sv...
Linking - SVG: Scalable Vector Graphics
WebSVGLinking
to get around this, requires a little ugly javascript hacking: button.svg: <?xml version="1.1" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <g onclick="top.document.href='page2.html'" cursor="pointer"> <!-- button graphical elements here --> </g> </svg> example for an example of this solution at work see www.codedread.com.
Namespaces crash course - SVG: Scalable Vector Graphics
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.
Specification Deviations - SVG: Scalable Vector Graphics
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.
Basic shapes - SVG: Scalable Vector Graphics
the code to generate that looks something like: <?xml version="1.0" standalone="no"?> <svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/> <rect x="60" y="10" rx="10" ry="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/> <circle cx="25" cy="75"...
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
fixing the bug need to look at the exthandler code.
Mixed content - Web security
the attacker can also rewrite the response to include malicious javascript code.
How to turn off form autocompletion - Web security
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).
Securing your site - Web security
code is executed by the victims and lets the attackers bypass access controls and impersonate users.
current - XPath
<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 .
Common XSLT Errors - XSLT: Extensible Stylesheet Language Transformations
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.
<xsl:number> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementnumber
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.
<xsl:sort> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementsort
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.
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order.
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
setting parameters while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful.
Exported WebAssembly functions - WebAssembly
testfunc.tostring() returns an interesting result: function 0() { [native code] } this gives you more of an idea of its wrapper-type nature.
Converting WebAssembly text format to wasm - WebAssembly
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.